From 22328c0a637cb6d62cfa8c89fbf55d09d6202ce1 Mon Sep 17 00:00:00 2001 From: Gabriele Cardosi Date: Mon, 7 Oct 2024 10:11:52 +0200 Subject: [PATCH 001/141] [NO_ISSUE] Cleanup incubator-kie-issues#1504 - Conditionally build all or only reproducible modules based on only.reproducible flag (#6111) Co-authored-by: Gabriele-Cardosi --- drools-drlonyaml-parent/pom.xml | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/drools-drlonyaml-parent/pom.xml b/drools-drlonyaml-parent/pom.xml index 9976e1ecbfe..a1f8cb50797 100644 --- a/drools-drlonyaml-parent/pom.xml +++ b/drools-drlonyaml-parent/pom.xml @@ -31,6 +31,15 @@ Drools :: DRL on YAML pom + + + drools-drlonyaml-schemagen + drools-drlonyaml-model + drools-drlonyaml-todrl + drools-drlonyaml-cli + drools-drlonyaml-cli-tests + + allSubmodules @@ -40,30 +49,9 @@ - drools-drlonyaml-schemagen - drools-drlonyaml-model - drools-drlonyaml-todrl - drools-drlonyaml-cli - drools-drlonyaml-cli-tests drools-drlonyaml-integration-tests - - - onlyReproducible - - - only.reproducible - - - - drools-drlonyaml-schemagen - drools-drlonyaml-model - drools-drlonyaml-todrl - drools-drlonyaml-cli - drools-drlonyaml-cli-tests - - From 1bbecc8bb4f6d1582d1ecab530142d04a17d0d32 Mon Sep 17 00:00:00 2001 From: Jozef Marko Date: Mon, 7 Oct 2024 12:10:49 +0200 Subject: [PATCH 002/141] Fix extry -> entry (#6114) --- .../kie-dmn-core/src/main/java/org/kie/dmn/core/util/Msg.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/util/Msg.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/util/Msg.java index 2f65e3e2639..d099f5b0131 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/util/Msg.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/util/Msg.java @@ -112,8 +112,8 @@ public final class Msg { public static final Message2 ERR_COMPILING_ALLOWED_VALUES_LIST_ON_ITEM_DEF = new Message2( DMNMessageType.ERR_COMPILING_FEEL, "Error compiling allowed values list '%s' on item definition '%s'" ); public static final Message2 ERR_COMPILING_TYPE_CONSTRAINT_LIST_ON_ITEM_DEF = new Message2( DMNMessageType.ERR_COMPILING_FEEL, "Error compiling type constraint list '%s' on item definition '%s'" ); public static final Message4 ERR_COMPILING_FEEL_EXPR_FOR_NAME_ON_NODE = new Message4( DMNMessageType.ERR_COMPILING_FEEL, "Error compiling FEEL expression '%s' for name '%s' on node '%s': %s" ); - public static final Message2 ERR_EVAL_CTX_ENTRY_ON_CTX = new Message2( DMNMessageType.ERR_EVAL_CTX, "Error evaluating context extry '%s' on context '%s'" ); - public static final Message3 ERR_EVAL_CTX_ENTRY_ON_CTX_MSG = new Message3( DMNMessageType.ERR_EVAL_CTX, "Unrecoverable error evaluating context extry '%s' on context '%s': %s" ); + public static final Message2 ERR_EVAL_CTX_ENTRY_ON_CTX = new Message2( DMNMessageType.ERR_EVAL_CTX, "Error evaluating context entry '%s' on context '%s'" ); + public static final Message3 ERR_EVAL_CTX_ENTRY_ON_CTX_MSG = new Message3( DMNMessageType.ERR_EVAL_CTX, "Unrecoverable error evaluating context entry '%s' on context '%s': %s" ); public static final Message1 DECISION_NOT_FOUND_FOR_NAME = new Message1( DMNMessageType.DECISION_NOT_FOUND, "Decision not found for name '%s'" ); public static final Message1 DECISION_NOT_FOUND_FOR_ID = new Message1( DMNMessageType.DECISION_NOT_FOUND, "Decision not found for type '%s'" ); public static final Message1 DECISION_SERVICE_NOT_FOUND_FOR_NAME = new Message1( DMNMessageType.DECISION_NOT_FOUND, "Decision Service not found for name '%s'"); From 00576e535cd500e5631395e64952ac3276b04678 Mon Sep 17 00:00:00 2001 From: Paolo Bizzarri Date: Fri, 11 Oct 2024 09:04:24 +0200 Subject: [PATCH 003/141] NO ISSUE: Migrate tests in drools traits to JUnit5. (#6122) * First steps * More small cleanups * More cleanups... * More cleanups... * More cleanups... * More cleanups... * More cleanups, progressing * Fixed size assertions * Fixed instanceof in tests * Fixed equals in assertj * Cleaned up isTrue assertions * Proper use of assertions on exceptions * Removed last bits of JUnit5 from tests --- drools-traits/pom.xml | 6 +- .../UseOfRuleFlowGroupPlusLockOnTest.java | 2 +- .../traits/compiler/CommonTraitTest.java | 4 +- .../factmodel/traits/LegacyTraitTest.java | 134 +- .../factmodel/traits/LogicalTraitTest.java | 105 +- .../factmodel/traits/StandaloneTest.java | 8 +- .../TraitFieldsAndLegacyClassesTest.java | 184 +- .../factmodel/traits/TraitMapCoreTest.java | 87 +- .../compiler/factmodel/traits/TraitTest.java | 3650 ++++++++--------- .../TraitTypeGenerationTest.java | 24 +- .../core/factmodel/ClassBuilderTest.java | 655 ++- .../factmodel/InstancesHashcodedTest.java | 2 +- .../traits/core/factmodel/JeneratorTest.java | 2 +- .../core/factmodel/TripleStoreTest.java | 36 +- .../traits/core/meta/org/MetadataTest.java | 69 +- .../traits/core/util/HierarchyTest.java | 371 +- 16 files changed, 2455 insertions(+), 2884 deletions(-) diff --git a/drools-traits/pom.xml b/drools-traits/pom.xml index f2c5f685fd1..70d75678a7b 100644 --- a/drools-traits/pom.xml +++ b/drools-traits/pom.xml @@ -184,10 +184,10 @@ - junit - junit + org.junit.jupiter + junit-jupiter test - + org.mockito mockito-core diff --git a/drools-traits/src/test/java/org/drools/traits/UseOfRuleFlowGroupPlusLockOnTest.java b/drools-traits/src/test/java/org/drools/traits/UseOfRuleFlowGroupPlusLockOnTest.java index 76a68c0a133..12460df4967 100644 --- a/drools-traits/src/test/java/org/drools/traits/UseOfRuleFlowGroupPlusLockOnTest.java +++ b/drools-traits/src/test/java/org/drools/traits/UseOfRuleFlowGroupPlusLockOnTest.java @@ -19,8 +19,8 @@ package org.drools.traits; import org.drools.kiesession.agenda.DefaultAgenda; +import org.junit.jupiter.api.Test; import org.drools.core.reteoo.ReteDumper; -import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.event.rule.DebugAgendaEventListener; import org.kie.api.io.ResourceType; 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 7f42e4fd45e..efa4b0786d1 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 @@ -21,7 +21,7 @@ import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.kiesession.rulebase.KnowledgeBaseFactory; import org.drools.traits.core.base.evaluators.IsAEvaluatorDefinition; -import org.junit.BeforeClass; +import org.junit.jupiter.api.BeforeAll; import org.kie.api.KieBase; import org.kie.api.io.ResourceType; import org.kie.internal.builder.KnowledgeBuilder; @@ -33,7 +33,7 @@ public class CommonTraitTest { - @BeforeClass + @BeforeAll public static void beforeClass() { System.setProperty(EvaluatorOption.PROPERTY_NAME + "isA", IsAEvaluatorDefinition.class.getName()); } 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 6b54b117bfa..47f7e41b0d7 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 @@ -19,21 +19,19 @@ package org.drools.traits.compiler.factmodel.traits; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import org.drools.base.factmodel.traits.Trait; import org.drools.base.factmodel.traits.Traitable; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.kiesession.rulebase.KnowledgeBaseFactory; import org.drools.traits.compiler.CommonTraitTest; -import org.drools.traits.core.factmodel.LogicalTypeInconsistencyException; import org.drools.traits.core.factmodel.TraitFactoryImpl; import org.drools.traits.core.factmodel.VirtualPropertyMode; import org.drools.traits.core.util.StandaloneTraitFactory; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.Message; import org.kie.api.definition.type.PropertyReactive; @@ -47,41 +45,26 @@ import org.slf4j.LoggerFactory; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; import static org.drools.traits.compiler.factmodel.traits.TraitTestUtils.createStandaloneTraitFactory; -@RunWith(Parameterized.class) public class LegacyTraitTest extends CommonTraitTest { private static final Logger LOGGER = LoggerFactory.getLogger(LegacyTraitTest.class); - public VirtualPropertyMode mode; - - @Parameterized.Parameters - public static Collection modes() { - return Arrays.asList( new VirtualPropertyMode[][] - { - { VirtualPropertyMode.MAP }, - { VirtualPropertyMode.TRIPLES } - } ); - } - - public LegacyTraitTest( VirtualPropertyMode m ) { - this.mode = m; + public static Collection modes() { + return List.of(VirtualPropertyMode.MAP, VirtualPropertyMode.TRIPLES); } - - - private KieSession getSessionFromString( String drl ) { + private KieSession getSessionFromString(String drl) { KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - knowledgeBuilder.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), - ResourceType.DRL ); + knowledgeBuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), + ResourceType.DRL); if (knowledgeBuilder.hasErrors()) { - throw new RuntimeException( knowledgeBuilder.getErrors().toString() ); + throw new RuntimeException(knowledgeBuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( knowledgeBuilder.getKnowledgePackages() ); + kbase.addPackages(knowledgeBuilder.getKnowledgePackages()); KieSession session = kbase.newKieSession(); return session; @@ -149,8 +132,9 @@ public void setPers(Pers pers) { } - @Test - public void traitWithPojoInterface() { + @ParameterizedTest + @MethodSource("modes") + public void traitWithPojoInterface(VirtualPropertyMode mode) { String source = "package org.drools.compiler.test;\n" + "import " + LegacyTraitTest.Procedure.class.getCanonicalName() + ";\n" + "import " + LegacyTraitTest.class.getCanonicalName() + ";\n" + @@ -160,7 +144,7 @@ public void traitWithPojoInterface() { // enhanced so that declaration is not needed // "declare ProcedureImpl end " + "declare trait ExtendedProcedure " + - " @role( event )" + + " @role(event)" + "end " + // Surgery must be declared as trait, since it does not extend Thing @@ -174,54 +158,54 @@ public void traitWithPojoInterface() { "when " + " $p : ExtendedProcedure() " + "then " + - " don( $p, Surgery.class ); " + + " don($p, Surgery.class); " + "end " + "rule 'Test 1' " + "dialect 'mvel' " + "when " + - " $s1 : ExtendedProcedure( $subject : subject ) " + - " $s2 : ExtendedProcedure( subject == $subject ) " + + " $s1 : ExtendedProcedure($subject : subject) " + + " $s2 : ExtendedProcedure(subject == $subject) " + "then " + "end " + "rule 'Test 2' " + "dialect 'mvel' " + "when " + - " $s1 : ExtendedProcedure( $subject : subject.name ) " + - " $s2 : ExtendedProcedure( subject.name == $subject ) " + + " $s1 : ExtendedProcedure($subject : subject.name) " + + " $s2 : ExtendedProcedure(subject.name == $subject) " + "then " + "end " + "rule 'Test 3' " + "dialect 'mvel' " + "when " + - " $s1 : ExtendedProcedure( ) " + + " $s1 : ExtendedProcedure() " + "then " + - " update( $s1 ); " + + " update($s1); " + "end " + "\n"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); ExtendedProcedureImpl procedure1 = new ExtendedProcedureImpl(); ExtendedProcedureImpl procedure2 = new ExtendedProcedureImpl(); PatientImpl patient1 = new PatientImpl(); patient1.setName("John"); - procedure1.setSubject( patient1 ); + procedure1.setSubject(patient1); procedure1.setPers(new PatientImpl()); PatientImpl patient2 = new PatientImpl(); patient2.setName("John"); - procedure2.setSubject( patient2 ); + procedure2.setSubject(patient2); procedure2.setPers(new PatientImpl()); - ks.insert( procedure1 ); - ks.insert( procedure2 ); + ks.insert(procedure1); + ks.insert(procedure2); - ks.fireAllRules( 500 ); + ks.fireAllRules(500); } @@ -237,8 +221,9 @@ public static interface Trunk extends Root { } @Trait public static interface Foo extends Trunk { } - @Test - public void traitWithMixedInterfacesExtendingEachOther() { + @ParameterizedTest + @MethodSource("modes") + public void traitWithMixedInterfacesExtendingEachOther(VirtualPropertyMode mode) { String source = "package org.drools.compiler.test;" + "import " + BarImpl.class.getCanonicalName() + "; " + "import " + Foo.class.getCanonicalName() + "; " + @@ -256,67 +241,64 @@ public void traitWithMixedInterfacesExtendingEachOther() { "rule 'Bar Don'" + "when " + - " $b : BarImpl( this isA Foo.class, this not isA Foo2.class )\n" + + " $b : BarImpl(this isA Foo.class, this not isA Foo2.class)\n" + " String()\n" + "then " + - " list.add( 3 ); " + - " retract( $b ); " + + " list.add(3); " + + " retract($b); " + "end " + "rule 'Don Bar' " + "no-loop " + "when " + - " $b : Foo( ) " + + " $b : Foo() " + "then " + - " list.add( 1 ); " + - " don( $b, Foo2.class ); " + + " list.add(1); " + + " don($b, Foo2.class); " + "end " + "rule 'Cant really shed Foo but Foo2' " + "when " + " $b : Foo2() " + "then " + - " list.add( 2 ); " + - " shed( $b, Foo.class ); " + - " insert( \"done\" );" + + " list.add(2); " + + " shed($b, Foo.class); " + + " insert(\"done\");" + "end " + ""; - KieSession ks = getSessionFromString( source ); + KieSession ks = getSessionFromString(source); KieBase kieBase = ks.getKieBase(); TraitFactoryImpl.setMode(mode, kieBase); - ArrayList list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); - ks.insert( new BarImpl() ); + ks.insert(new BarImpl()); int n = ks.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList(1, 2, 3)); + LOGGER.debug(list.toString()); + assertThat(list).containsExactly(1, 2, 3); assertThat(n).isEqualTo(3); } - @Test - public void testTraitWithNonAccessorMethodShadowing() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitWithNonAccessorMethodShadowing(VirtualPropertyMode mode) throws Exception { StandaloneTraitFactory factory = createStandaloneTraitFactory(); - try { - SomeInterface r = (SomeInterface) factory.don( new SomeClass(), SomeInterface.class ); - r.prepare(); - assertThat(r.getFoo()).isEqualTo(42); - assertThat(r.doThis("that")).isEqualTo("I did that"); - } catch ( LogicalTypeInconsistencyException e ) { - e.printStackTrace(); - fail( e.getMessage() ); - } + SomeInterface r = (SomeInterface) factory.don(new SomeClass(), SomeInterface.class); + r.prepare(); + assertThat(r.getFoo()).isEqualTo(42); + assertThat(r.doThis("that")).isEqualTo("I did that"); } - @Test() - public void testPojoExtendInterface() { + @ParameterizedTest + @MethodSource("modes") + public void testPojoExtendInterface(VirtualPropertyMode mode) { // DROOLS-697 // It is now allowed for a declared type to extend an interface // The interface itself will be added to the implements part of the generated class @@ -331,9 +313,9 @@ public void testPojoExtendInterface() { ""; KieHelper kh = new KieHelper(); - kh.addContent( s1, ResourceType.DRL ); + kh.addContent(s1, ResourceType.DRL); - assertThat(kh.verify().getMessages(Message.Level.ERROR).size()).isEqualTo(0); + assertThat(kh.verify().getMessages(Message.Level.ERROR)).isEmpty(); } } 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 f9217d22ac3..bedb76d286e 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 @@ -26,6 +26,7 @@ import org.drools.core.common.InternalFactHandle; import org.drools.base.factmodel.traits.CoreWrapper; +import org.drools.base.factmodel.traits.Thing; import org.drools.base.factmodel.traits.TraitField; import org.drools.base.factmodel.traits.Traitable; import org.drools.base.factmodel.traits.TraitableBean; @@ -66,12 +67,8 @@ public class LogicalTraitTest extends CommonTraitTest { public VirtualPropertyMode mode; @Parameterized.Parameters - public static Collection modes() { - return Arrays.asList( new VirtualPropertyMode[][] - { - { VirtualPropertyMode.MAP }, - { VirtualPropertyMode.TRIPLES } - } ); + public static Collection modes() { + return List.of(VirtualPropertyMode.MAP, VirtualPropertyMode.TRIPLES); } public LogicalTraitTest( VirtualPropertyMode m ) { @@ -80,7 +77,7 @@ public LogicalTraitTest( VirtualPropertyMode m ) { @Test - public void testShadowAlias() { + public void testShadowAlias() throws Exception { KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilderImpl.add( ResourceFactory.newClassPathResource( "org/drools/compiler/factmodel/traits/testTraitedAliasing.drl" ), ResourceType.DRL ); @@ -94,7 +91,7 @@ public void testShadowAlias() { KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList( ); + List list = new ArrayList<>( ); ks.setGlobal( "list", list ); ks.fireAllRules(); @@ -103,15 +100,11 @@ public void testShadowAlias() { LOGGER.debug( o.toString() ); } - try { - ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true ); - } catch ( Exception e ) { - fail( e.getMessage(), e ); - } + ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true ); LOGGER.debug( list.toString() ); - assertThat(list.contains(false)).isFalse(); - assertThat(list.size()).isEqualTo(8); + assertThat(list).doesNotContain(Boolean.FALSE); + assertThat(list).hasSize(8); } @@ -165,14 +158,14 @@ public void testShadowAliasTraitOnClass() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); ks.fireAllRules(); for ( Object o : ks.getObjects() ) { LOGGER.debug( o.toString() ); } - assertThat(list).isEqualTo(List.of("ok")); + assertThat(list).containsExactly("ok"); try { ks = SerializationHelper.getSerialisedStatefulKnowledgeSession( ks, true ); @@ -241,14 +234,14 @@ public void testShadowAliasClassOnTrait() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); ks.fireAllRules(); for ( Object o : ks.getObjects() ) { LOGGER.debug( o.toString() ); } - assertThat(list).isEqualTo(Arrays.asList("ok1", "ok2")); + assertThat(list).containsExactly("ok1", "ok2"); try { ks = SerializationHelper.getSerialisedStatefulKnowledgeSession( ks, true ); @@ -314,14 +307,14 @@ public void testShadowAliasTraitOnTrait() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); ks.fireAllRules(); for ( Object o : ks.getObjects() ) { LOGGER.debug( o.toString() ); } - assertThat(list).isEqualTo(List.of("ok")); + assertThat(list).containsExactly("ok"); try { ks = SerializationHelper.getSerialisedStatefulKnowledgeSession( ks, true ); @@ -391,8 +384,8 @@ public void initializationConflictManagement() { TraitFactoryImpl.setMode(mode, knowledgeBase ); KieSession knowledgeSession = knowledgeBase.newKieSession(); - ArrayList list = new ArrayList(); - ArrayList list2 = new ArrayList(); + List list = new ArrayList<>(); + List list2 = new ArrayList<>(); knowledgeSession.setGlobal( "list", list ); knowledgeSession.setGlobal( "list2", list2 ); @@ -404,8 +397,8 @@ public void initializationConflictManagement() { LOGGER.debug( list.toString() ); LOGGER.debug( list2.toString() ); - assertThat(list).isEqualTo(Arrays.asList("1", null, "xyz", "xyz", "7", "aaa")); - assertThat(list2).isEqualTo(Arrays.asList(18, null, 37, 99, 37)); + assertThat(list).containsExactly("1", null, "xyz", "xyz", "7", "aaa"); + assertThat(list2).containsExactly(18, null, 37, 99, 37); try { knowledgeSession = SerializationHelper.getSerialisedStatefulKnowledgeSession( knowledgeSession, true ); @@ -473,8 +466,8 @@ public void testInitializationConflictManagementPrimitiveTypes() { TraitFactoryImpl.setMode(mode, knowledgeBase ); KieSession knowledgeSession = knowledgeBase.newKieSession(); - ArrayList list = new ArrayList(); - ArrayList list2 = new ArrayList(); + List list = new ArrayList<>(); + List list2 = new ArrayList<>(); knowledgeSession.setGlobal( "list", list ); knowledgeSession.setGlobal( "list2", list2 ); @@ -486,8 +479,8 @@ public void testInitializationConflictManagementPrimitiveTypes() { LOGGER.debug( list.toString() ); LOGGER.debug( list2.toString() ); - assertThat(list).isEqualTo(Arrays.asList(1.0, 0.0, 16.3, 16.3, 0.0, -0.72)); - assertThat(list2).isEqualTo(Arrays.asList(18, 0, 37, 99, 0)); + assertThat(list).containsExactly(1.0, 0.0, 16.3, 16.3, 0.0, -0.72); + assertThat(list2).containsExactly(18, 0, 37, 99, 0); try { knowledgeSession = SerializationHelper.getSerialisedStatefulKnowledgeSession( knowledgeSession, true ); @@ -556,24 +549,20 @@ public void testHardGetSetOnLogicallyTraitedField() { TraitFactoryImpl.setMode(mode, knowledgeBase ); KieSession knowledgeSession = knowledgeBase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal( "list", list ); knowledgeSession.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList(42)); + assertThat(list).containsExactly(42); knowledgeSession.insert( "x" ); knowledgeSession.fireAllRules(); - boolean found = false; - for ( Object o : knowledgeSession.getObjects( new ClassObjectFilter( Qty.class ) ) ) { - assertThat(((Qty) o).getNum()).isEqualTo((Integer) 99); - assertThat(((CoreWrapper) o)._getFieldTMS().get("num", Integer.class)).isEqualTo(99); - found = true; - } - assertThat(found).isTrue(); + Object o = knowledgeSession.getObjects(new ClassObjectFilter(Qty.class)).iterator().next(); + assertThat(((Qty) o).getNum()).isEqualTo((Integer) 99); + assertThat(((CoreWrapper) o)._getFieldTMS().get("num", Integer.class)).isEqualTo(99); - assertThat(list).isEqualTo(Arrays.asList(42, 99)); + assertThat(list).containsExactly(42, 99); knowledgeSession.dispose(); } @@ -783,7 +772,7 @@ public void shadowAliasSelf() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); ks.fireAllRules(); @@ -873,7 +862,7 @@ public void traitOnSet() { KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); int n = ks.fireAllRules(); @@ -985,13 +974,13 @@ public void testShadowAliasTraitOnClassLogicalRetract() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); FactHandle handle = ks.insert( "go" ); ks.fireAllRules(); - assertThat(list).isEqualTo(List.of("ok")); + assertThat(list).containsExactly("ok"); for ( Object o : ks.getObjects() ) { LOGGER.debug( o + " >> " + ((InternalFactHandle)ks.getFactHandle( o )).getEqualityKey() ); @@ -1001,16 +990,16 @@ public void testShadowAliasTraitOnClassLogicalRetract() { ks.fireAllRules(); for ( Object o : ks.getObjects( new ClassObjectFilter( ks.getKieBase().getFactType( "org.drools.test", "Y" ).getFactClass() ) ) ) { - assertThat(o instanceof TraitableBean).isTrue(); + assertThat(o).isInstanceOf(TraitableBean.class); TraitableBean tb = (TraitableBean) o; TraitField fld = tb._getFieldTMS().getRegisteredTraitField("fld" ); Set> types = fld.getRangeTypes(); - assertThat(types.size()).isEqualTo(2); + assertThat(types).hasSize(2); TraitField fld2 = tb._getFieldTMS().getRegisteredTraitField("fld2" ); Set> types2 = fld2.getRangeTypes(); - assertThat(types2.size()).isEqualTo(1); + assertThat(types2).hasSize(1); } try { @@ -1026,7 +1015,7 @@ public void testShadowAliasTraitOnClassLogicalRetract() { LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList("ok", "ok2", "ok3")); + assertThat(list).containsExactly("ok", "ok2", "ok3"); } @@ -1109,19 +1098,19 @@ public void testShadowAliasClassOnTraitLogicalRetract() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); FactHandle handle = ks.insert( "go" ); ks.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList(1, 2)); + assertThat(list).containsExactly(1, 2); ks.retract( handle ); ks.fireAllRules(); for ( Object o : ks.getObjects( new ClassObjectFilter( ks.getKieBase().getFactType( "org.drools.test", "Y" ).getFactClass() ) ) ) { - assertThat(o instanceof TraitableBean).isTrue(); + assertThat(o).isInstanceOf(TraitableBean.class); } try { @@ -1131,7 +1120,7 @@ public void testShadowAliasClassOnTraitLogicalRetract() { } LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList(1, 2, 1, 2)); + assertThat(list).containsExactly(1, 2, 1, 2); } @@ -1177,7 +1166,7 @@ public void testSerial() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList(); ks.setGlobal( "list", list ); ks.fireAllRules(); @@ -1241,11 +1230,11 @@ public void testTraitMismatchTypes() KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size() == 1 && list.contains(null)).isTrue(); + assertThat(list).hasSize(1).containsNull(); } @Test @@ -1295,11 +1284,11 @@ public void testTraitMismatchTypes2() KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size() == 1 && list.contains(null)).isTrue(); + assertThat(list).hasSize(1).containsNull(); } @Test @@ -1349,13 +1338,13 @@ public void testTraitMismatchTypes3() KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list",list); ksession.fireAllRules(); LOGGER.debug( "list" + list ); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0).getClass().getName()).isEqualTo("org.drools.base.factmodel.traits.test.Bar"); } } diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/StandaloneTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/StandaloneTest.java index 992ccdb8907..61b4d12d593 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/StandaloneTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/StandaloneTest.java @@ -25,8 +25,8 @@ import org.drools.base.factmodel.traits.Thing; import org.drools.traits.core.util.StandaloneTraitFactory; import org.drools.wiring.api.classloader.ProjectClassLoader; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,7 +39,7 @@ public class StandaloneTest { private StandaloneTraitFactory factory; - @Before + @BeforeEach public void init() { ProjectClassLoader loader = ProjectClassLoader.createProjectClassLoader(); factory = createStandaloneTraitFactory(); @@ -100,7 +100,7 @@ public void testLegacy() throws LogicalTypeInconsistencyException { LOGGER.debug( "Is foo instance of Thing? : " + (foo instanceof Thing) ); assertThat(foo.getName()).isEqualTo("john doe"); - assertThat(foo instanceof Thing).isTrue(); + assertThat(foo).isInstanceOf(Thing.class); } 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 dbee7e2a6cc..0ecf89bd251 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 @@ -27,11 +27,10 @@ import org.drools.traits.compiler.ReviseTraitTestWithPRAlwaysCategory; import org.drools.traits.core.factmodel.TraitFactoryImpl; import org.drools.traits.core.factmodel.VirtualPropertyMode; -import org.junit.Ignore; -import org.junit.Test; import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.io.ResourceType; @@ -41,27 +40,18 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class TraitFieldsAndLegacyClassesTest extends CommonTraitTest { - public VirtualPropertyMode mode; - @Parameterized.Parameters - public static Collection modes() { - return Arrays.asList( new VirtualPropertyMode[][] - { - { VirtualPropertyMode.MAP }, - { VirtualPropertyMode.TRIPLES } - } ); + public static Collection modes() { + return List.of(VirtualPropertyMode.MAP , VirtualPropertyMode.TRIPLES ); } - public TraitFieldsAndLegacyClassesTest( VirtualPropertyMode m ) { - this.mode = m; - } - @Test - public void testTraitFieldUpdate0() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate0(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits0;\n" + @@ -114,19 +104,21 @@ public void testTraitFieldUpdate0() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate1() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate1(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits;\n" + @@ -202,18 +194,20 @@ public void testTraitFieldUpdate1() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate2() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate2(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits2;\n" + @@ -301,17 +295,18 @@ public void testTraitFieldUpdate2() { KieSession knowledgeSession = kBase.newKieSession(); TraitFactoryImpl.setMode(mode, kBase ); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate3() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate3(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits3;\n" + @@ -396,18 +391,20 @@ public void testTraitFieldUpdate3() { KieBase kBase = loadKnowledgeBaseFromString(drl); TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } @Category(ReviseTraitTestWithPRAlwaysCategory.class) - @Test - public void testTraitFieldUpdate4() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate4(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits4;\n" + @@ -475,17 +472,18 @@ public void testTraitFieldUpdate4() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate5() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate5(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits5;\n" + @@ -559,17 +557,18 @@ public void testTraitFieldUpdate5() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate6() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate6(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits6;\n" + @@ -649,20 +648,20 @@ public void testTraitFieldUpdate6() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.contains("correct2")).isTrue(); - assertThat(list.size()).isEqualTo(2); + assertThat(list).hasSize(2); + assertThat(list).contains("correct", "correct2"); } - @Test - public void testTraitFieldUpdate7() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate7(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits;\n" + @@ -733,20 +732,21 @@ public void testTraitFieldUpdate7() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate8() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate8(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits8;\n" + @@ -818,17 +818,18 @@ public void testTraitFieldUpdate8() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate9() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate9(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits9;\n" + @@ -909,17 +910,18 @@ public void testTraitFieldUpdate9() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate10() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate10(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits;\n" + @@ -1001,17 +1003,18 @@ public void testTraitFieldUpdate10() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitTwoParentOneChild() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitTwoParentOneChild(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits;\n" + @@ -1112,17 +1115,19 @@ public void testTraitTwoParentOneChild() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test @Ignore - public void testTraitWithPositionArgs(){ + @ParameterizedTest + @Disabled + @MethodSource("modes") + public void testTraitWithPositionArgs(VirtualPropertyMode mode){ String drl = "" + "package org.drools.traits.test;\n" + @@ -1245,23 +1250,24 @@ public void testTraitWithPositionArgs(){ TraitFactoryImpl.setMode(mode, kBase ); KieSession kSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); kSession.setGlobal("list", list); kSession.fireAllRules(); - assertThat(list.contains("initialized")).isTrue(); - assertThat(list.contains("student")).isTrue(); - assertThat(list.contains("IR citizen")).isTrue(); - assertThat(list.contains("US citizen")).isTrue(); - assertThat(list.contains("worker")).isTrue(); - assertThat(list.contains("You are working in US as student worker")).isTrue(); - assertThat(list.contains("You are studying and working at ASU")).isTrue(); + assertThat(list).contains("initialized"); + assertThat(list).contains("student"); + assertThat(list).contains("IR citizen"); + assertThat(list).contains("US citizen"); + assertThat(list).contains("worker"); + assertThat(list).contains("You are working in US as student worker"); + assertThat(list).contains("You are studying and working at ASU"); } - @Test - public void singlePositionTraitTest(){ + @ParameterizedTest + @MethodSource("modes") + public void singlePositionTraitTest(VirtualPropertyMode mode){ String drl = "" + 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 97f8a3ac4da..d4d9cae880c 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 @@ -29,7 +29,8 @@ import org.drools.traits.core.factmodel.TraitFactoryImpl; import org.drools.base.factmodel.traits.Traitable; import org.drools.traits.core.factmodel.VirtualPropertyMode; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.kie.api.runtime.KieSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,7 +41,8 @@ public class TraitMapCoreTest extends CommonTraitTest { private static final Logger LOGGER = LoggerFactory.getLogger(TraitMapCoreTest.class); - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void testMapCoreManyTraits( ) { String source = "package org.drools.test;\n" + "\n" + @@ -98,7 +100,8 @@ public void testMapCoreManyTraits( ) { assertThat(map.get("GPA")).isEqualTo(3.0); } - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void donMapTest() { String source = "package org.drools.traits.test; \n" + "import java.util.*\n;" + @@ -138,19 +141,19 @@ public void donMapTest() { List list = new ArrayList(); ksession.setGlobal( "list", list ); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put( "name", "john" ); map.put( "age", 18 ); ksession.insert( map ); ksession.fireAllRules(); - assertThat(map.containsKey("height")).isTrue(); - assertThat(184.0).isEqualTo(map.get("height")); + assertThat(map).containsEntry("height", 184.0); } - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void testMapCore2( ) { String source = "package org.drools.base.factmodel.traits.test;\n" + "\n" + @@ -262,7 +265,8 @@ public void testMapCore2( ) { } - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void testMapCoreAliasing( ) { String source = "package org.drools.base.factmodel.traits.test;\n" + "\n" + @@ -325,7 +329,8 @@ public void testMapCoreAliasing( ) { } - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void testMapCoreAliasingLogicalTrueWithTypeClash( ) { String source = "package org.drools.base.factmodel.traits.test;\n" + "\n" + @@ -363,7 +368,7 @@ public void testMapCoreAliasingLogicalTrueWithTypeClash( ) { KieSession ks = loadKnowledgeBaseFromString( source ).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ks.getKieBase() ); - List list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); Map map = new HashMap( ); @@ -373,7 +378,8 @@ public void testMapCoreAliasingLogicalTrueWithTypeClash( ) { ks.fireAllRules(); - assertThat(list.size() == 1 && list.get(0) == null).isTrue(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isNull(); } @Test @@ -454,13 +460,11 @@ public void testDrools216(){ KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal( "list", list ); ksession.fireAllRules(); - assertThat(list.contains("initialized")).isTrue(); - assertThat(list.contains("student is donned")).isTrue(); - assertThat(list.contains("worker is donned")).isTrue(); + assertThat(list).contains("initialized", "student is donned", "worker is donned"); } @@ -541,13 +545,11 @@ public void testDrools217(){ KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list", list); ksession.fireAllRules(); - assertThat(list.contains("initialized")).isTrue(); - assertThat(list.contains("student is donned")).isTrue(); - assertThat(list.contains("worker is donned")).isTrue(); + assertThat(list).contains("initialized", "student is donned", "worker is donned"); } @Test @@ -656,15 +658,11 @@ public void testDrools218(){ KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal( "list", list ); ksession.fireAllRules(); - assertThat(list.contains("initialized")).isTrue(); - assertThat(list.contains("student is donned")).isTrue(); - assertThat(list.contains("worker is donned")).isTrue(); - assertThat(list.contains("studentworker is donned")).isTrue(); - assertThat(list.contains("tuitionWaiver is true")).isTrue(); + assertThat(list).contains("initialized", "student is donned", "worker is donned", "studentworker is donned", "tuitionWaiver is true"); } @Test @@ -758,16 +756,12 @@ public void testDrools219(){ KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal( "list", list ); ksession.fireAllRules(); - assertThat(list.contains("initialized")).isTrue(); - assertThat(list.contains("student is donned")).isTrue(); - assertThat(list.contains("student has ID and SSN")).isTrue(); - assertThat(list.contains("student has personID and socialSecurity")).isTrue(); - assertThat(list.contains("citizen has socialSecurity")).isTrue(); - assertThat(list.contains("person has personID")).isTrue(); + assertThat(list).contains("initialized", "student is donned", "student has ID and SSN", + "student has personID and socialSecurity", "citizen has socialSecurity", "person has personID"); } @Test @@ -827,7 +821,7 @@ public void testMapTraitsMismatchTypes() ksession.insert( map ); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(2); + assertThat(list).hasSize(2); assertThat(list.get(0)).isNull(); assertThat(list.get(1)).isNotNull(); } @@ -874,18 +868,18 @@ public void testMapTraitNoType() KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list",list); Map map = new HashMap(); // map.put("name", "hulu"); ksession.insert(map); ksession.fireAllRules(); - assertThat(list.contains("correct1")).isTrue(); - assertThat(list.contains("correct2")).isTrue(); + assertThat(list).contains("correct1", "correct2"); } - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void testMapTraitMismatchTypes() { String drl = "" + @@ -930,7 +924,7 @@ public void testMapTraitMismatchTypes() ksession.insert(map); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0)).isEqualTo(null); } @@ -995,7 +989,7 @@ public void testMapTraitPossibilities1() ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0)).isNotNull(); } @@ -1064,7 +1058,7 @@ public void testMapTraitPossibilities2() ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0)).isNotNull(); } @@ -1133,7 +1127,7 @@ public void testMapTraitPossibilities3() ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0)).isNotNull(); } @@ -1205,7 +1199,7 @@ public void testMapTraitPossibilities4() ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0)).isNotNull(); } @@ -1248,18 +1242,17 @@ public void donCustomMapTest() { List list = new ArrayList(); ksession.setGlobal( "list", list ); - HashMap map = new DomainMap(); + Map map = new DomainMap(); map.put( "name", "john" ); map.put( "age", 18 ); ksession.insert( map ); ksession.fireAllRules(); - assertThat(map.containsKey("height")).isTrue(); - assertThat(184.0).isEqualTo(map.get("height")); + assertThat(map).containsEntry("height", 184.0); - assertThat(ksession.getObjects().size()).isEqualTo(2); - assertThat(ksession.getObjects(new ClassObjectFilter( DomainMap.class )).size()).isEqualTo(1); + assertThat(ksession.getObjects()).hasSize(2); + assertThat(ksession.getObjects(new ClassObjectFilter( DomainMap.class ))).hasSize(1); } 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 5b912937e0f..8c9142f1664 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 @@ -28,7 +28,6 @@ import org.drools.core.common.InternalWorkingMemory; import org.drools.core.common.ObjectTypeConfigurationRegistry; import org.drools.core.impl.InternalRuleBase; -import org.drools.core.reteoo.LeftTuple; import org.drools.core.reteoo.ObjectTypeConf; import org.drools.core.reteoo.ObjectTypeNode; import org.drools.core.reteoo.RuleTerminalNodeLeftTuple; @@ -44,7 +43,6 @@ import org.drools.traits.compiler.ReviseTraitTestWithPRAlwaysCategory; import org.drools.traits.core.factmodel.Entity; import org.drools.traits.core.factmodel.HierarchyEncoder; -import org.drools.traits.core.factmodel.LogicalTypeInconsistencyException; import org.drools.traits.core.factmodel.MapWrapper; import org.drools.traits.core.factmodel.TraitFactoryImpl; import org.drools.traits.core.factmodel.TraitProxyImpl; @@ -105,6 +103,8 @@ import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -114,43 +114,36 @@ public class TraitTest extends CommonTraitTest { private static final Logger LOGGER = LoggerFactory.getLogger(TraitTest.class); - - private static long t0; - - + public VirtualPropertyMode mode; @Parameterized.Parameters - public static Collection modes() { - return Arrays.asList( new VirtualPropertyMode[][] - { - { VirtualPropertyMode.MAP }, - { VirtualPropertyMode.TRIPLES } - } ); + public static Collection modes() { + return List.of(VirtualPropertyMode.MAP, VirtualPropertyMode.TRIPLES); } - public TraitTest( VirtualPropertyMode m ) { + public TraitTest(VirtualPropertyMode m) { this.mode = m; } - private KieSession getSession( String... ruleFiles ) { + private KieSession getSession(String... ruleFiles) { KieHelper kieHelper = new KieHelper(); for (String file : ruleFiles) { - kieHelper.kfs.write( new ClassPathResource( file ) ); + kieHelper.kfs.write(new ClassPathResource(file)); } return kieHelper.build().newKieSession(); } - private KieSession getSessionFromString( String drl ) { - return new KieHelper().addContent( drl, ResourceType.DRL ).build().newKieSession(); + private KieSession getSessionFromString(String drl) { + return new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession(); } - private KieBase getKieBaseFromString( String drl, KieBaseOption... options ) { - return new KieHelper().addContent( drl, ResourceType.DRL ).build(options); + private KieBase getKieBaseFromString(String drl, KieBaseOption... options) { + return new KieHelper().addContent(drl, ResourceType.DRL).build(options); } @Test - public void testRetract( ) { + public void testRetract() { String drl = "package org.drools.compiler.trait.test; \n" + "import org.drools.base.factmodel.traits.Traitable; \n" + "" + @@ -159,16 +152,16 @@ public void testRetract( ) { "" + "rule Init when then\n" + " Foo foo = new Foo(); \n" + - " don( foo, Bar.class ); \n" + + " don(foo, Bar.class); \n" + "end\n" + "rule Retract \n" + "when\n" + " $bar : Bar()\n" + "then\n" + - " delete( $bar ); \n" + + " delete($bar); \n" + "end\n"; - KieSession ks = getSessionFromString( drl ); + KieSession ks = getSessionFromString(drl); TraitFactoryImpl.setMode(mode, ks.getKieBase()); assertThat(ks.fireAllRules()).isEqualTo(2); @@ -177,59 +170,47 @@ public void testRetract( ) { LOGGER.debug(o.toString()); } - assertThat(ks.getObjects().size()).isEqualTo(0); + assertThat(ks.getObjects()).isEmpty(); } @Test - public void testTraitWrapGetAndSet() { + public void testTraitWrapGetAndSet() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - TraitFactoryImpl.setMode(mode, kb ); - kb.addPackages( kbuilder.getKnowledgePackages() ); + TraitFactoryImpl.setMode(mode, kb); + kb.addPackages(kbuilder.getKnowledgePackages()); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - Class trait = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ).getFactClass(); - - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + Class trait = kb.getFactType("org.drools.compiler.trait.test", "Student").getFactClass(); - Map virtualFields = imp._getDynamicProperties(); - Map wrapper = proxy.getFields(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); - wrapper.put( "name", - "john" ); + Map virtualFields = imp._getDynamicProperties(); + Map wrapper = proxy.getFields(); - wrapper.put( "virtualField", - "xyz" ); + wrapper.put("name", "john"); - wrapper.entrySet(); - assertThat(wrapper.size()).isEqualTo(4); - assertThat(virtualFields.size()).isEqualTo(2); + wrapper.put("virtualField", "xyz"); - assertThat(wrapper.get("name")).isEqualTo("john"); - assertThat(wrapper.get("virtualField")).isEqualTo("xyz"); + wrapper.entrySet(); + assertThat(wrapper).hasSize(4); + assertThat(virtualFields).hasSize(2); - assertThat(impClass.get(imp, - "name")).isEqualTo("john"); + assertThat(wrapper.get("name")).isEqualTo("john"); + assertThat(wrapper.get("virtualField")).isEqualTo("xyz"); - } catch (Exception e) { - fail( e.getMessage(), e ); - } + assertThat(impClass.get(imp, "name")).isEqualTo("john"); } @@ -237,35 +218,32 @@ public void testTraitWrapGetAndSet() { public void testTraitShed() { String source = "org/drools/compiler/factmodel/traits/testTraitShed.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); - assertThat(info.isEmpty()).isTrue(); + assertThat(info).isEmpty(); ks.fireAllRules(); - assertThat(info.contains("Student")).isTrue(); - assertThat(info.size()).isEqualTo(1); + assertThat(info).contains("Student"); + assertThat(info).hasSize(1); - ks.insert( "hire" ); + ks.insert("hire"); ks.fireAllRules(); - Collection c = ks.getObjects(); - - assertThat(info.contains("Worker")).isTrue(); - assertThat(info.size()).isEqualTo(2); + assertThat(info).contains("Worker"); + assertThat(info).hasSize(2); - ks.insert( "check" ); + ks.insert("check"); ks.fireAllRules(); - assertThat(info.size()).isEqualTo(4); - assertThat(info.contains("Conflict")).isTrue(); - assertThat(info.contains("Nothing")).isTrue(); + assertThat(info).hasSize(4); + assertThat(info).contains("Conflict"); + assertThat(info).contains("Nothing"); } @@ -273,47 +251,45 @@ public void testTraitShed() { public void testTraitDon() { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); Collection wm = ks.getObjects(); - ks.insert( "go" ); + ks.insert("go"); ks.fireAllRules(); - assertThat(info.contains("DON")).isTrue(); - assertThat(info.contains("SHED")).isTrue(); + assertThat(info).contains("DON"); + assertThat(info).contains("SHED"); - Iterator it = wm.iterator(); + Iterator it = wm.iterator(); Object x = it.next(); - if ( x instanceof String ) { + if (x instanceof String) { x = it.next(); } LOGGER.debug(x.getClass().toString()); LOGGER.debug(x.getClass().getSuperclass().toString()); - LOGGER.debug(Arrays.asList(x.getClass().getInterfaces()).toString()); + LOGGER.debug(List.of(x.getClass().getInterfaces()).toString()); } @Test public void testMixin() { String source = "org/drools/compiler/factmodel/traits/testTraitMixin.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); - assertThat(info.contains("27")).isTrue(); + assertThat(info).contains("27"); } @@ -321,19 +297,18 @@ public void testMixin() { public void traitMethodsWithObjects() { String source = "org/drools/compiler/factmodel/traits/testTraitWrapping.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List errors = new ArrayList(); - ks.setGlobal( "list", - errors ); + List errors = new ArrayList<>(); + ks.setGlobal("list", errors); ks.fireAllRules(); if (!errors.isEmpty()) { LOGGER.error(errors.toString()); } - assertThat(errors.isEmpty()).isTrue(); + assertThat(errors).isEmpty(); } @@ -342,655 +317,506 @@ public void traitMethodsWithObjects() { public void traitMethodsWithPrimitives() { String source = "org/drools/compiler/factmodel/traits/testTraitWrappingPrimitives.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List errors = new ArrayList(); - ks.setGlobal( "list", - errors ); + List errors = new ArrayList<>(); + ks.setGlobal("list", errors); ks.fireAllRules(); if (!errors.isEmpty()) { LOGGER.error(errors.toString()); } - assertThat(errors.isEmpty()).isTrue(); + assertThat(errors).isEmpty(); } @Test - public void testTraitProxy() { + public void testTraitProxy() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); - TraitFactoryImpl.setMode(mode, kb ); + kb.addPackages(kbuilder.getKnowledgePackages()); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - impClass.set( imp, - "name", - "aaa" ); - - Class trait = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ).getFactClass(); - Class trait2 = kb.getFactType( "org.drools.compiler.trait.test", - "Role" ).getFactClass(); - - assertThat(trait).isNotNull(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - proxy.getFields().put( "field", - "xyz" ); - // proxy.getFields().put("name", "aaa"); - - assertThat(proxy).isNotNull(); - - TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - assertThat(proxy).isSameAs(proxy2); - - TraitProxyImpl proxy3 = (TraitProxyImpl) tFactory.getProxy(imp, - trait2 ); - assertThat(proxy3).isNotNull(); - assertThat(proxy3.getFields().get("field")).isEqualTo("xyz"); - assertThat(proxy3.getFields().get("name")).isEqualTo("aaa"); - - TraitableBean imp2 = (TraitableBean) impClass.newInstance(); - impClass.set( imp2, - "name", - "aaa" ); - TraitProxyImpl proxy4 = (TraitProxyImpl) tFactory.getProxy(imp2, - trait ); - // proxy4.getFields().put("name", "aaa"); - proxy4.getFields().put( "field", - "xyz" ); - - assertThat(proxy4).isEqualTo(proxy2); - - } catch (InstantiationException | IllegalAccessException | LogicalTypeInconsistencyException e) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + impClass.set(imp, "name", "aaa"); + + Class trait = kb.getFactType("org.drools.compiler.trait.test", "Student").getFactClass(); + Class trait2 = kb.getFactType("org.drools.compiler.trait.test", "Role").getFactClass(); + + assertThat(trait).isNotNull(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + proxy.getFields().put("field", "xyz"); + // proxy.getFields().put("name", "aaa"); + + assertThat(proxy).isNotNull(); + + TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + assertThat(proxy).isSameAs(proxy2); + + TraitProxyImpl proxy3 = (TraitProxyImpl) tFactory.getProxy(imp, trait2, false); + assertThat(proxy3).isNotNull(); + assertThat(proxy3.getFields().get("field")).isEqualTo("xyz"); + assertThat(proxy3.getFields().get("name")).isEqualTo("aaa"); + + TraitableBean imp2 = (TraitableBean) impClass.newInstance(); + impClass.set(imp2, "name", "aaa"); + TraitProxyImpl proxy4 = (TraitProxyImpl) tFactory.getProxy(imp2, trait, false); + // proxy4.getFields().put("name", "aaa"); + proxy4.getFields().put("field", "xyz"); + + assertThat(proxy4).isEqualTo(proxy2); } @Test - public void testWrapperSize() { + public void testWrapperSize() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); + kb.addPackages(kbuilder.getKnowledgePackages()); - TraitFactoryImpl.setMode(mode, kb ); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - FactType traitClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = traitClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - - Map virtualFields = imp._getDynamicProperties(); - Map wrapper = proxy.getFields(); - assertThat(wrapper.size()).isEqualTo(3); - assertThat(virtualFields.size()).isEqualTo(1); - - impClass.set(imp, - "name", - "john"); - assertThat(wrapper.size()).isEqualTo(3); - assertThat(virtualFields.size()).isEqualTo(1); - - proxy.getFields().put( "school", - "skol" ); - assertThat(wrapper.size()).isEqualTo(3); - assertThat(virtualFields.size()).isEqualTo(1); - - proxy.getFields().put( "surname", - "xxx" ); - assertThat(wrapper.size()).isEqualTo(4); - assertThat(virtualFields.size()).isEqualTo(2); - - // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); - // TraitableBean ind = (TraitableBean) indClass.newInstance(); - TraitableBean ind = new Entity(); - - TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, - trait ); - - Map virtualFields2 = ind._getDynamicProperties(); - Map wrapper2 = proxy2.getFields(); - assertThat(wrapper2.size()).isEqualTo(3); - assertThat(virtualFields2.size()).isEqualTo(3); - - traitClass.set( proxy2, - "name", - "john" ); - assertThat(wrapper2.size()).isEqualTo(3); - assertThat(virtualFields2.size()).isEqualTo(3); - - proxy2.getFields().put( "school", - "skol" ); - assertThat(wrapper2.size()).isEqualTo(3); - assertThat(virtualFields2.size()).isEqualTo(3); - - proxy2.getFields().put( "surname", - "xxx" ); - assertThat(wrapper2.size()).isEqualTo(4); - assertThat(virtualFields2.size()).isEqualTo(4); - - FactType traitClass2 = kb.getFactType( "org.drools.compiler.trait.test", - "Role" ); - Class trait2 = traitClass2.getFactClass(); - // TraitableBean ind2 = (TraitableBean) indClass.newInstance(); - TraitableBean ind2 = new Entity(); - - TraitProxyImpl proxy99 = (TraitProxyImpl) tFactory.getProxy(ind2, - trait2 ); - - proxy99.getFields().put( "surname", - "xxx" ); - proxy99.getFields().put( "name", - "xyz" ); - proxy99.getFields().put( "school", - "skol" ); - - assertThat(proxy99.getFields().size()).isEqualTo(3); - - TraitProxyImpl proxy100 = (TraitProxyImpl) tFactory.getProxy(ind2, - trait ); - - assertThat(proxy100.getFields().size()).isEqualTo(4); - - } catch ( Exception e ) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + FactType traitClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = traitClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + + Map virtualFields = imp._getDynamicProperties(); + Map wrapper = proxy.getFields(); + assertThat(wrapper).hasSize(3); + assertThat(virtualFields).hasSize(1); + + impClass.set(imp, "name", "john"); + assertThat(wrapper).hasSize(3); + assertThat(virtualFields).hasSize(1); + + proxy.getFields().put("school", "skol"); + assertThat(wrapper).hasSize(3); + assertThat(virtualFields).hasSize(1); + + proxy.getFields().put("surname", "xxx"); + assertThat(wrapper).hasSize(4); + assertThat(virtualFields).hasSize(2); + + // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); + // TraitableBean ind = (TraitableBean) indClass.newInstance(); + TraitableBean ind = new Entity(); + + TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, trait, false); + + Map virtualFields2 = ind._getDynamicProperties(); + Map wrapper2 = proxy2.getFields(); + assertThat(wrapper2).hasSize(3); + assertThat(virtualFields2).hasSize(3); + + traitClass.set(proxy2, "name", "john"); + assertThat(wrapper2).hasSize(3); + assertThat(virtualFields2).hasSize(3); + + proxy2.getFields().put("school", "skol"); + assertThat(wrapper2).hasSize(3); + assertThat(virtualFields2).hasSize(3); + + proxy2.getFields().put("surname", "xxx"); + assertThat(wrapper2).hasSize(4); + assertThat(virtualFields2).hasSize(4); + + FactType traitClass2 = kb.getFactType("org.drools.compiler.trait.test", "Role"); + Class trait2 = traitClass2.getFactClass(); + // TraitableBean ind2 = (TraitableBean) indClass.newInstance(); + TraitableBean ind2 = new Entity(); + + TraitProxyImpl proxy99 = (TraitProxyImpl) tFactory.getProxy(ind2, trait2, false); + + proxy99.getFields().put("surname", "xxx"); + proxy99.getFields().put("name", "xyz"); + proxy99.getFields().put("school", "skol"); + + assertThat(proxy99.getFields()).hasSize(3); + + TraitProxyImpl proxy100 = (TraitProxyImpl) tFactory.getProxy(ind2, trait, false); + + assertThat(proxy100.getFields()).hasSize(4); } @Test - public void testWrapperEmpty() { + public void testWrapperEmpty() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); - TraitFactoryImpl.setMode(mode, kb ); + kb.addPackages(kbuilder.getKnowledgePackages()); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - - FactType studentClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = studentClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - - Map virtualFields = imp._getDynamicProperties(); - Map wrapper = proxy.getFields(); - assertThat(wrapper.isEmpty()).isFalse(); - - studentClass.set( proxy, - "name", - "john" ); - assertThat(wrapper.isEmpty()).isFalse(); - studentClass.set( proxy, - "name", - null ); - assertThat(wrapper.isEmpty()).isFalse(); - - studentClass.set( proxy, - "age", - 32 ); - assertThat(wrapper.isEmpty()).isFalse(); - - studentClass.set( proxy, - "age", - null ); - assertThat(wrapper.isEmpty()).isFalse(); - - // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); - TraitableBean ind = new Entity(); - - FactType RoleClass = kb.getFactType( "org.drools.compiler.trait.test", - "Role" ); - Class trait2 = RoleClass.getFactClass(); - TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, - trait2 ); - - Map wrapper2 = proxy2.getFields(); - assertThat(wrapper2.isEmpty()).isTrue(); - - proxy2.getFields().put( "name", - "john" ); - assertThat(wrapper2.isEmpty()).isFalse(); - - proxy2.getFields().put( "name", - null ); - assertThat(wrapper2.isEmpty()).isFalse(); - - } catch (Exception e) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + + FactType studentClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = studentClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + + Map wrapper = proxy.getFields(); + assertThat(wrapper).isNotEmpty(); + + studentClass.set(proxy, "name", "john"); + assertThat(wrapper).isNotEmpty(); + + studentClass.set(proxy, "name", null); + assertThat(wrapper).isNotEmpty(); + + studentClass.set(proxy, "age", 32); + assertThat(wrapper).isNotEmpty(); + + studentClass.set(proxy, "age", null); + assertThat(wrapper).isNotEmpty(); + + // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); + TraitableBean ind = new Entity(); + + FactType RoleClass = kb.getFactType("org.drools.compiler.trait.test", "Role"); + Class trait2 = RoleClass.getFactClass(); + TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, trait2, false); + + Map wrapper2 = proxy2.getFields(); + assertThat(wrapper2).isEmpty(); + + proxy2.getFields().put("name", "john"); + assertThat(wrapper2).isNotEmpty(); + + proxy2.getFields().put("name", null); + assertThat(wrapper2).isNotEmpty(); } @Test - public void testWrapperContainsKey() { + public void testWrapperContainsKey() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); + kb.addPackages(kbuilder.getKnowledgePackages()); - TraitFactoryImpl.setMode(mode, kb ); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - impClass.set( imp, - "name", - "john" ); - - FactType traitClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = traitClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - - Map virtualFields = imp._getDynamicProperties(); - Map wrapper = proxy.getFields(); - - assertThat(wrapper.containsKey("name")).isTrue(); - assertThat(wrapper.containsKey("school")).isTrue(); - assertThat(wrapper.containsKey("age")).isTrue(); - assertThat(wrapper.containsKey("surname")).isFalse(); - - proxy.getFields().put( "school", - "skol" ); - proxy.getFields().put( "surname", - "xxx" ); - assertThat(wrapper.containsKey("surname")).isTrue(); - - // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); - TraitableBean ind = new Entity(); - - TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, - trait ); - - Map virtualFields2 = ind._getDynamicProperties(); - Map wrapper2 = proxy2.getFields(); - assertThat(wrapper2.containsKey("name")).isTrue(); - assertThat(wrapper2.containsKey("school")).isTrue(); - assertThat(wrapper2.containsKey("age")).isTrue(); - assertThat(wrapper2.containsKey("surname")).isFalse(); - - traitClass.set( proxy2, - "name", - "john" ); - proxy2.getFields().put( "school", - "skol" ); - proxy2.getFields().put( "surname", - "xxx" ); - assertThat(wrapper2.containsKey("surname")).isTrue(); - - FactType traitClass2 = kb.getFactType( "org.drools.compiler.trait.test", - "Role" ); - Class trait2 = traitClass2.getFactClass(); - TraitableBean ind2 = new Entity(); - - TraitProxyImpl proxy99 = (TraitProxyImpl) tFactory.getProxy(ind2, - trait2 ); - Map wrapper99 = proxy99.getFields(); - - assertThat(wrapper99.containsKey("name")).isFalse(); - assertThat(wrapper99.containsKey("school")).isFalse(); - assertThat(wrapper99.containsKey("age")).isFalse(); - assertThat(wrapper99.containsKey("surname")).isFalse(); - - proxy99.getFields().put( "surname", - "xxx" ); - proxy99.getFields().put( "name", - "xyz" ); - proxy99.getFields().put( "school", - "skol" ); - - assertThat(wrapper99.containsKey("name")).isTrue(); - assertThat(wrapper99.containsKey("school")).isTrue(); - assertThat(wrapper99.containsKey("age")).isFalse(); - assertThat(wrapper99.containsKey("surname")).isTrue(); - assertThat(proxy99.getFields().size()).isEqualTo(3); - - TraitableBean ind0 = new Entity(); - - TraitProxyImpl proxy100 = (TraitProxyImpl) tFactory.getProxy(ind0, - trait2 ); - Map wrapper100 = proxy100.getFields(); - assertThat(wrapper100.containsKey("name")).isFalse(); - assertThat(wrapper100.containsKey("school")).isFalse(); - assertThat(wrapper100.containsKey("age")).isFalse(); - assertThat(wrapper100.containsKey("surname")).isFalse(); - - TraitProxyImpl proxy101 = (TraitProxyImpl) tFactory.getProxy(ind0, - trait ); - // object gains properties by virtue of another trait - // so new props are accessible even using the old proxy - assertThat(wrapper100.containsKey("name")).isTrue(); - assertThat(wrapper100.containsKey("school")).isTrue(); - assertThat(wrapper100.containsKey("age")).isTrue(); - assertThat(wrapper100.containsKey("surname")).isFalse(); - - } catch (Exception e) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + impClass.set(imp, "name", "john"); + + FactType traitClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = traitClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + + Map wrapper = proxy.getFields(); + + assertThat(wrapper).containsKey("name"); + assertThat(wrapper).containsKey("school"); + assertThat(wrapper).containsKey("age"); + assertThat(wrapper).doesNotContainKey("surname"); + + proxy.getFields().put("school", "skol"); + proxy.getFields().put("surname", "xxx"); + assertThat(wrapper).containsKey("surname"); + + // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); + TraitableBean ind = new Entity(); + + TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, trait, false); + + Map wrapper2 = proxy2.getFields(); + assertThat(wrapper2).containsKey("name"); + assertThat(wrapper2).containsKey("school"); + assertThat(wrapper2).containsKey("age"); + assertThat(wrapper2).doesNotContainKey("surname"); + + traitClass.set(proxy2, "name", "john"); + proxy2.getFields().put("school", "skol"); + proxy2.getFields().put("surname", "xxx"); + assertThat(wrapper2).containsKey("surname"); + + FactType traitClass2 = kb.getFactType("org.drools.compiler.trait.test", "Role"); + Class trait2 = traitClass2.getFactClass(); + TraitableBean ind2 = new Entity(); + + TraitProxyImpl proxy99 = (TraitProxyImpl) tFactory.getProxy(ind2, trait2, false); + Map wrapper99 = proxy99.getFields(); + + assertThat(wrapper99).doesNotContainKey("name"); + assertThat(wrapper99).doesNotContainKey("school"); + assertThat(wrapper99).doesNotContainKey("age"); + assertThat(wrapper99).doesNotContainKey("surname"); + + proxy99.getFields().put("surname", "xxx"); + proxy99.getFields().put("name", "xyz"); + proxy99.getFields().put("school", "skol"); + + assertThat(wrapper99).containsKey("name"); + assertThat(wrapper99).containsKey("school"); + assertThat(wrapper99).doesNotContainKey("age"); + assertThat(wrapper99).containsKey("surname"); + assertThat(proxy99.getFields()).hasSize(3); + + TraitableBean ind0 = new Entity(); + + TraitProxyImpl proxy100 = (TraitProxyImpl) tFactory.getProxy(ind0, trait2, false); + Map wrapper100 = proxy100.getFields(); + assertThat(wrapper100).doesNotContainKey("name"); + assertThat(wrapper100).doesNotContainKey("school"); + assertThat(wrapper100).doesNotContainKey("age"); + assertThat(wrapper100).doesNotContainKey("surname"); + + TraitProxyImpl proxy101 = (TraitProxyImpl) tFactory.getProxy(ind0, trait, false); + // object gains properties by virtue of another trait + // so new props are accessible even using the old proxy + assertThat(wrapper100).containsKey("name"); + assertThat(wrapper100).containsKey("school"); + assertThat(wrapper100).containsKey("age"); + assertThat(wrapper100).doesNotContainKey("surname"); } @Test - public void testInternalComponents1( ) { + public void testInternalComponents1() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); + kb.addPackages(kbuilder.getKnowledgePackages()); - TraitFactoryImpl.setMode(mode, kb ); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - FactType traitClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = traitClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - Object proxyFields = proxy.getFields(); - Object coreTraits = imp._getTraitMap(); - Object coreProperties = imp._getDynamicProperties(); - - assertThat(proxy.getObject() instanceof TraitableBean).isTrue(); - - assertThat(proxyFields).isNotNull(); - assertThat(coreTraits).isNotNull(); - assertThat(coreProperties).isNotNull(); - - if ( mode == VirtualPropertyMode.MAP ) { - assertThat(proxyFields instanceof MapWrapper).isTrue(); - assertThat(coreTraits instanceof TraitTypeMapImpl).isTrue(); - assertThat(coreProperties instanceof HashMap).isTrue(); - } else { - assertThat(proxyFields.getClass().getName()).isEqualTo("org.drools.compiler.trait.test.Student.org.drools.compiler.trait.test.Imp_ProxyWrapper"); + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + FactType traitClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = traitClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + Object proxyFields = proxy.getFields(); + Object coreTraits = imp._getTraitMap(); + Object coreProperties = imp._getDynamicProperties(); - assertThat(proxyFields instanceof TripleBasedStruct).isTrue(); - assertThat(coreTraits instanceof TraitTypeMapImpl).isTrue(); - assertThat(coreProperties instanceof TripleBasedBean).isTrue(); - } + assertThat(proxyFields).isNotNull(); + assertThat(coreTraits).isNotNull(); + assertThat(coreProperties).isNotNull(); + if (mode == VirtualPropertyMode.MAP) { + assertThat(proxyFields).isInstanceOf(MapWrapper.class); + assertThat(coreTraits).isInstanceOf(TraitTypeMapImpl.class); + assertThat(coreProperties).isInstanceOf(HashMap.class); + } else { + assertThat(proxyFields.getClass().getName()).isEqualTo("org.drools.compiler.trait.test.Student.org.drools.compiler.trait.test.Imp_ProxyWrapper"); - StudentProxyImpl2 sp2 = new StudentProxyImpl2(new Imp2(), null ); - LOGGER.debug(sp2.toString()); + assertThat(proxyFields).isInstanceOf(TripleBasedStruct.class); + assertThat(coreTraits).isInstanceOf(TraitTypeMapImpl.class); + assertThat(coreProperties).isInstanceOf(TripleBasedBean.class); + } - } catch ( Exception e ) { - fail( e.getMessage(), e ); - } + + StudentProxyImpl2 sp2 = new StudentProxyImpl2(new Imp2(), null); + LOGGER.debug(sp2.toString()); } @Test - public void testWrapperKeySetAndValues() { + public void testWrapperKeySetAndValues() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); - TraitFactoryImpl.setMode(mode, kb ); + kb.addPackages(kbuilder.getKnowledgePackages()); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - FactType traitClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = traitClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - - impClass.set( imp, - "name", - "john" ); - proxy.getFields().put( "surname", - "xxx" ); - proxy.getFields().put( "name2", - "john" ); - proxy.getFields().put( "nfield", - null ); - - Set set = new HashSet(); - set.add( "name" ); - set.add( "surname" ); - set.add( "age" ); - set.add( "school" ); - set.add( "name2" ); - set.add( "nfield" ); - - assertThat(proxy.getFields().keySet().size()).isEqualTo(6); - assertThat(proxy.getFields().keySet()).isEqualTo(set); - - Collection col1 = proxy.getFields().values(); - Collection col2 = Arrays.asList( "john", - null, - 0, - "xxx", - "john", - null ); - - Comparator comp = new Comparator() { - - public int compare( Object o1, Object o2 ) { - if (o1 == null && o2 != null) { - return 1; - } - if (o1 != null && o2 == null) { - return -1; - } - if (o1 == null && o2 == null) { - return 0; - } - return o1.toString().compareTo( o2.toString() ); - } - }; - - Collections.sort( (List) col1, - comp ); - Collections.sort( (List) col2, - comp ); - assertThat(col2).isEqualTo(col1); - - assertThat(proxy.getFields().containsValue(null)).isTrue(); - assertThat(proxy.getFields().containsValue("john")).isTrue(); - assertThat(proxy.getFields().containsValue(0)).isTrue(); - assertThat(proxy.getFields().containsValue("xxx")).isTrue(); - assertThat(proxy.getFields().containsValue("randomString")).isFalse(); - assertThat(proxy.getFields().containsValue(-96)).isFalse(); - - } catch (Exception e) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + FactType traitClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = traitClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + + impClass.set(imp, "name", "john"); + proxy.getFields().put("surname", "xxx"); + proxy.getFields().put("name2", "john"); + proxy.getFields().put("nfield", null); + + assertThat(proxy.getFields()).hasSize(6); + assertThat(proxy.getFields().keySet()).contains("name", "surname", "age", "school", "name2", "nfield"); + + List col1 = new ArrayList<>(proxy.getFields().values()); + List col2 = Arrays.asList("john", null, 0, "xxx", "john", null); + + Comparator comp = new Comparator() { + + public int compare(Object o1, Object o2) { + if (o1 == null && o2 != null) { + return 1; + } + if (o1 != null && o2 == null) { + return -1; + } + if (o1 == null && o2 == null) { + return 0; + } + return o1.toString().compareTo(o2.toString()); + } + }; + + Collections.sort(col1, comp); + Collections.sort(col2, comp); + assertThat(col2).isEqualTo(col1); + + assertThat(proxy.getFields()).containsValue(null); + assertThat(proxy.getFields()).containsValue("john"); + assertThat(proxy.getFields()).containsValue(0); + assertThat(proxy.getFields()).containsValue("xxx"); + assertThat(proxy.getFields()).doesNotContainValue("randomString"); + assertThat(proxy.getFields()).doesNotContainValue(-96); } @Test - public void testWrapperClearAndRemove() { + public void testWrapperClearAndRemove() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); - TraitFactoryImpl.setMode(mode, kb ); + kb.addPackages(kbuilder.getKnowledgePackages()); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - impClass.set( imp, - "name", - "john" ); - FactType traitClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = traitClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - - proxy.getFields().put( "surname", - "xxx" ); - proxy.getFields().put( "name2", - "john" ); - proxy.getFields().put( "nfield", - null ); - - Set set = new HashSet(); - set.add( "name" ); - set.add( "surname" ); - set.add( "age" ); - set.add( "school" ); - set.add( "name2" ); - set.add( "nfield" ); - - assertThat(proxy.getFields().keySet().size()).isEqualTo(6); - assertThat(proxy.getFields().keySet()).isEqualTo(set); - - proxy.getFields().clear(); - - Map fields = proxy.getFields(); - assertThat(fields.size()).isEqualTo(3); - assertThat(fields.containsKey("age")).isTrue(); - assertThat(fields.containsKey("school")).isTrue(); - assertThat(fields.containsKey("name")).isTrue(); - - assertThat(fields.get("age")).isEqualTo(0); - assertThat(fields.get("school")).isNull(); - assertThat(fields.get("name")).isNotNull(); - - proxy.getFields().put( "surname", - "xxx" ); - proxy.getFields().put( "name2", - "john" ); - proxy.getFields().put( "nfield", - null ); - proxy.getFields().put( "age", - 24 ); - - assertThat(proxy.getFields().get("name")).isEqualTo("john"); - assertThat(proxy.getFields().get("surname")).isEqualTo("xxx"); - assertThat(proxy.getFields().get("name2")).isEqualTo("john"); - assertThat(proxy.getFields().get("nfield")).isEqualTo(null); - assertThat(proxy.getFields().get("age")).isEqualTo(24); - assertThat(proxy.getFields().get("school")).isEqualTo(null); - - proxy.getFields().remove( "surname" ); - proxy.getFields().remove( "name2" ); - proxy.getFields().remove( "age" ); - proxy.getFields().remove( "school" ); - proxy.getFields().remove( "nfield" ); - assertThat(proxy.getFields().size()).isEqualTo(3); - - assertThat(proxy.getFields().get("age")).isEqualTo(0); - assertThat(proxy.getFields().get("school")).isEqualTo(null); - assertThat(proxy.getFields().get("name")).isEqualTo("john"); - - assertThat(proxy.getFields().get("nfield")).isEqualTo(null); - assertThat(proxy.getFields().containsKey("nfield")).isFalse(); - - assertThat(proxy.getFields().get("name2")).isEqualTo(null); - assertThat(proxy.getFields().containsKey("name2")).isFalse(); - - assertThat(proxy.getFields().get("surname")).isEqualTo(null); - assertThat(proxy.getFields().containsKey("surname")).isFalse(); - - } catch (Exception e) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + impClass.set(imp, "name", "john"); + FactType traitClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = traitClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + + proxy.getFields().put("surname", "xxx"); + proxy.getFields().put("name2", "john"); + proxy.getFields().put("nfield", null); + + Set set = new HashSet<>(); + set.add("name"); + set.add("surname"); + set.add("age"); + set.add("school"); + set.add("name2"); + set.add("nfield"); + + assertThat(proxy.getFields()).hasSize(6); + assertThat(proxy.getFields().keySet()).isEqualTo(set); + + proxy.getFields().clear(); + + Map fields = proxy.getFields(); + assertThat(fields).hasSize(3); + assertThat(fields).containsKey("age"); + assertThat(fields).containsKey("school"); + assertThat(fields).containsKey("name"); + + assertThat(fields.get("age")).isEqualTo(0); + assertThat(fields.get("school")).isNull(); + assertThat(fields.get("name")).isNotNull(); + + proxy.getFields().put("surname", "xxx"); + proxy.getFields().put("name2", "john"); + proxy.getFields().put("nfield", null); + proxy.getFields().put("age", 24); + + assertThat(proxy.getFields().get("name")).isEqualTo("john"); + assertThat(proxy.getFields().get("surname")).isEqualTo("xxx"); + assertThat(proxy.getFields().get("name2")).isEqualTo("john"); + assertThat(proxy.getFields().get("nfield")).isEqualTo(null); + assertThat(proxy.getFields().get("age")).isEqualTo(24); + assertThat(proxy.getFields().get("school")).isEqualTo(null); + + proxy.getFields().remove("surname"); + proxy.getFields().remove("name2"); + proxy.getFields().remove("age"); + proxy.getFields().remove("school"); + proxy.getFields().remove("nfield"); + assertThat(proxy.getFields()).hasSize(3); + + assertThat(proxy.getFields().get("age")).isEqualTo(0); + assertThat(proxy.getFields().get("school")).isEqualTo(null); + assertThat(proxy.getFields().get("name")).isEqualTo("john"); + + assertThat(proxy.getFields().get("nfield")).isEqualTo(null); + assertThat(proxy.getFields()).doesNotContainKey("nfield"); + + assertThat(proxy.getFields().get("name2")).isEqualTo(null); + assertThat(proxy.getFields()).doesNotContainKey("name2"); + + assertThat(proxy.getFields().get("surname")).isEqualTo(null); + assertThat(proxy.getFields()).doesNotContainKey("surname"); } @Test - public void testIsAEvaluator( ) { + public void testIsAEvaluator() { String source = "package org.drools.compiler.trait.test;\n" + "\n" + "import org.drools.base.factmodel.traits.Traitable;\n" + @@ -1020,43 +846,42 @@ public void testIsAEvaluator( ) { "rule \"Init\"\n" + "when\n" + "then\n" + - " Imp core = new Imp( \"joe\" );\n" + - " insert( core );\n" + - " don( core, Person.class );\n" + - " don( core, Worker.class );\n" + + " Imp core = new Imp(\"joe\");\n" + + " insert(core);\n" + + " don(core, Person.class);\n" + + " don(core, Worker.class);\n" + "\n" + - " Imp core2 = new Imp( \"adam\" );\n" + - " insert( core2 );\n" + - " don( core2, Worker.class );\n" + + " Imp core2 = new Imp(\"adam\");\n" + + " insert(core2);\n" + + " don(core2, Worker.class);\n" + "end\n" + "\n" + "rule \"Mod\"\n" + "when\n" + - " $p : Person( name == \"joe\" )\n" + + " $p : Person(name == \"joe\")\n" + "then\n" + - " modify ($p) { setName( \"john\" ); }\n" + + " modify ($p) { setName(\"john\"); }\n" + "end\n" + "\n" + "rule \"Worker Students v6\"\n" + "when\n" + - " $x2 := Person( name == \"john\" )\n" + - " $x1 := Worker( core != $x2.core, this not isA $x2 )\n" + + " $x2 := Person(name == \"john\")\n" + + " $x1 := Worker(core != $x2.core, this not isA $x2)\n" + "then\n" + - " list.add( \"ok\" );\n" + + " list.add(\"ok\");\n" + "end\n" + "\n" + "\n"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); LOGGER.debug(info.toString()); - assertThat(info.contains("ok")).isTrue(); + assertThat(info).contains("ok"); } @@ -1065,12 +890,11 @@ public void testIsAEvaluator( ) { public void testIsA() { String source = "org/drools/compiler/factmodel/traits/testTraitIsA.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); @@ -1078,9 +902,9 @@ public void testIsA() { int num = 10; LOGGER.debug(info.toString()); - assertThat(info.size()).isEqualTo(num); + assertThat(info).hasSize(num); for (int j = 0; j < num; j++) { - assertThat(info.contains("" + j)).isTrue(); + assertThat(info).contains("" + j); } } @@ -1091,26 +915,24 @@ public void testIsA() { public void testOverrideType() { String source = "org/drools/compiler/factmodel/traits/testTraitOverride.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); - try { - ks.fireAllRules(); - fail( "An exception was expected since a trait can't override the type of a core class field with these settings " ); - } catch ( Throwable rde ) { - assertThat(rde.getCause() instanceof UnsupportedOperationException).isTrue(); - } + assertThatException() + .as("An exception was expected since a trait can't override the type of a core class field with these settings ") + .isThrownBy(() -> ks.fireAllRules()) + .extracting(e -> e.getCause()) + .isInstanceOf(UnsupportedOperationException.class); } @Test - public void testOverrideType2( ) { + public void testOverrideType2() { String drl = "package org.drools.compiler.trait.test; \n" + "import org.drools.base.factmodel.traits.Traitable; \n" + "" + @@ -1122,24 +944,23 @@ public void testOverrideType2( ) { "" + "rule Don when then\n" + " Face face = new Face(); \n" + - " don( face, Mask.class ); \n" + + " don(face, Mask.class); \n" + "end\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - try { - ks.fireAllRules(); - fail( "An exception was expected since a trait can't override the type of a core class field with these settings " ); - } catch ( Throwable rde ) { - assertThat(rde.getCause() instanceof UnsupportedOperationException).isTrue(); - } + assertThatException() + .as("An exception was expected since a trait can't override the type of a core class field with these settings ") + .isThrownBy(() -> ks.fireAllRules()) + .extracting(e -> e.getCause()) + .isInstanceOf(UnsupportedOperationException.class); } @Test - public void testOverrideType3( ) { + public void testOverrideType3() { String drl = "package org.drools.compiler.trait.test; \n" + "import org.drools.base.factmodel.traits.Traitable; \n" + "" + @@ -1151,18 +972,18 @@ public void testOverrideType3( ) { "" + "rule Don when then\n" + " Face face = new Face(); \n" + - " don( face, Mask.class ); \n" + + " don(face, Mask.class); \n" + "end\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - try { - ks.fireAllRules(); - fail( "An exception was expected since a trait can't override the type of a core class field with these settings " ); - } catch ( Throwable rde ) { - assertThat(rde.getCause() instanceof UnsupportedOperationException).isTrue(); - } + + assertThatException() + .as("An exception was expected since a trait can't override the type of a core class field with these settings ") + .isThrownBy(() -> ks.fireAllRules()) + .extracting(e -> e.getCause()) + .isInstanceOf(UnsupportedOperationException.class); } @@ -1170,55 +991,53 @@ public void testOverrideType3( ) { public void testTraitLegacy() { String source = "org/drools/compiler/factmodel/traits/testTraitLegacyTrait.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); printDebugInfoSessionObjects(ks.getObjects(), info); - assertThat(info.size()).isEqualTo(5); - assertThat(info.contains("OK")).isTrue(); - assertThat(info.contains("OK2")).isTrue(); - assertThat(info.contains("OK3")).isTrue(); - assertThat(info.contains("OK4")).isTrue(); - assertThat(info.contains("OK5")).isTrue(); + assertThat(info).hasSize(5); + assertThat(info).contains("OK"); + assertThat(info).contains("OK2"); + assertThat(info).contains("OK3"); + assertThat(info).contains("OK4"); + assertThat(info).contains("OK5"); } - private void printDebugInfoSessionObjects(final Collection facts, final List globalList) { - LOGGER.debug( " -------------- " + facts.size() + " ---------------- " ); + private void printDebugInfoSessionObjects(final Collection facts, final List globalList) { + LOGGER.debug(" -------------- " + facts.size() + " ---------------- "); for (Object o : facts) { - LOGGER.debug( "\t\t" + o ); + LOGGER.debug("\t\t" + o); } - LOGGER.debug( " -------------- ---------------- " ); - LOGGER.debug( globalList.toString() ); - LOGGER.debug( " -------------- ---------------- " ); + LOGGER.debug(" -------------- ---------------- "); + LOGGER.debug(globalList.toString()); + LOGGER.debug(" -------------- ---------------- "); } @Test public void testTraitCollections() { String source = "org/drools/compiler/factmodel/traits/testTraitCollections.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); printDebugInfoSessionObjects(ks.getObjects(), info); - assertThat(info.size()).isEqualTo(1); - assertThat(info.contains("OK")).isTrue(); + assertThat(info).hasSize(1); + assertThat(info).contains("OK"); } @@ -1226,20 +1045,19 @@ public void testTraitCollections() { public void testTraitCore() { String source = "org/drools/compiler/factmodel/traits/testTraitLegacyCore.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); printDebugInfoSessionObjects(ks.getObjects(), info); - assertThat(info.contains("OK")).isTrue(); - assertThat(info.contains("OK2")).isTrue(); - assertThat(info.size()).isEqualTo(2); + assertThat(info).contains("OK"); + assertThat(info).contains("OK2"); + assertThat(info).hasSize(2); } @@ -1247,17 +1065,16 @@ public void testTraitCore() { public void traitWithEquality() { String source = "org/drools/compiler/factmodel/traits/testTraitWithEquality.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); - assertThat(info.contains("DON")).isTrue(); - assertThat(info.contains("EQUAL")).isTrue(); + assertThat(info).contains("DON"); + assertThat(info).contains("EQUAL"); } @@ -1267,21 +1084,19 @@ public void traitDeclared() { List trueTraits = new ArrayList(); List untrueTraits = new ArrayList(); - KieSession ks = getSession( "org/drools/compiler/factmodel/traits/testDeclaredFactTrait.drl" ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession("org/drools/compiler/factmodel/traits/testDeclaredFactTrait.drl"); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - ks.setGlobal( "trueTraits", - trueTraits ); - ks.setGlobal( "untrueTraits", - untrueTraits ); + ks.setGlobal("trueTraits", trueTraits); + ks.setGlobal("untrueTraits", untrueTraits); ks.fireAllRules(); ks.dispose(); - assertThat(trueTraits.contains(1)).isTrue(); - assertThat(trueTraits.contains(2)).isFalse(); - assertThat(untrueTraits.contains(2)).isTrue(); - assertThat(untrueTraits.contains(1)).isFalse(); + assertThat(trueTraits).contains(1); + assertThat(trueTraits).doesNotContain(2); + assertThat(untrueTraits).contains(2); + assertThat(untrueTraits).doesNotContain(1); } @Test @@ -1290,41 +1105,38 @@ public void traitPojo() { List trueTraits = new ArrayList(); List untrueTraits = new ArrayList(); - KieSession session = getSession( "org/drools/compiler/factmodel/traits/testPojoFactTrait.drl" ); - TraitFactoryImpl.setMode(mode, session.getKieBase() ); + KieSession session = getSession("org/drools/compiler/factmodel/traits/testPojoFactTrait.drl"); + TraitFactoryImpl.setMode(mode, session.getKieBase()); - session.setGlobal( "trueTraits", - trueTraits ); - session.setGlobal( "untrueTraits", - untrueTraits ); + session.setGlobal("trueTraits", trueTraits); + session.setGlobal("untrueTraits", untrueTraits); session.fireAllRules(); session.dispose(); - assertThat(trueTraits.contains(1)).isTrue(); - assertThat(trueTraits.contains(2)).isFalse(); - assertThat(untrueTraits.contains(2)).isTrue(); - assertThat(untrueTraits.contains(1)).isFalse(); + assertThat(trueTraits).contains(1); + assertThat(trueTraits).doesNotContain(2); + assertThat(untrueTraits).contains(2); + assertThat(untrueTraits).doesNotContain(1); } @Test public void testIsAOperator() { String source = "org/drools/compiler/factmodel/traits/testTraitIsA2.drl"; - KieSession ksession = getSession( source ); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + KieSession ksession = getSession(source); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - AgendaEventListener ael = mock( AgendaEventListener.class ); - ksession.addEventListener( ael ); + AgendaEventListener ael = mock(AgendaEventListener.class); + ksession.addEventListener(ael); - Person student = new Person("student", 18 ); - ksession.insert( student ); + Person student = new Person("student", 18); + ksession.insert(student); ksession.fireAllRules(); - ArgumentCaptor cap = ArgumentCaptor.forClass( AfterMatchFiredEvent.class ); - verify( ael, - times( 3 ) ).afterMatchFired( cap.capture() ); + ArgumentCaptor cap = ArgumentCaptor.forClass(AfterMatchFiredEvent.class); + verify(ael, times(3)).afterMatchFired(cap.capture()); List values = cap.getAllValues(); @@ -1351,7 +1163,7 @@ public void testManyTraits() { "" + "rule \"Nice\"\n" + "when\n" + - " $n : NiceMessage( $m : message )\n" + + " $n : NiceMessage($m : message)\n" + "then\n" + "end" + "\n" + @@ -1362,59 +1174,58 @@ public void testManyTraits() { " Message message = new Message();\n" + " message.setMessage(\"Hello World\");\n" + " insert(message);\n" + - " don( message, NiceMessage.class );\n" + + " don(message, NiceMessage.class);\n" + "\n" + " Message unreadMessage = new Message();\n" + " unreadMessage.setMessage(\"unread\");\n" + " insert(unreadMessage);\n" + - " don( unreadMessage, NiceMessage.class );\n" + + " don(unreadMessage, NiceMessage.class);\n" + "\n" + " Message oldMessage = new Message();\n" + " oldMessage.setMessage(\"old\");\n" + " insert(oldMessage);\n" + - " don( oldMessage, NiceMessage.class );" + + " don(oldMessage, NiceMessage.class);" + " list.add(\"OK\");\n" + " end"; - KieSession ksession = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + KieSession ksession = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - Person student = new Person( "student", 18 ); - ksession.insert( student ); + Person student = new Person("student", 18); + ksession.insert(student); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); - assertThat(list.contains("OK")).isTrue(); + assertThat(list).hasSize(1); + assertThat(list).contains("OK"); } @Test public void traitManyTimes() { - KieSession ksession = getSession( "org/drools/compiler/factmodel/traits/testTraitDonMultiple.drl" ); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + KieSession ksession = getSession("org/drools/compiler/factmodel/traits/testTraitDonMultiple.drl"); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { + for (Object o : ksession.getObjects()) { LOGGER.debug(o.toString()); } - Collection x = ksession.getObjects(); - assertThat(ksession.getObjects().size()).isEqualTo(2); + assertThat(ksession.getObjects()).hasSize(2); - assertThat(list.size()).isEqualTo(5); + assertThat(list).hasSize(5); assertThat(list.get(0)).isEqualTo(0); - assertThat(list.contains(1)).isTrue(); - assertThat(list.contains(2)).isTrue(); - assertThat(list.contains(3)).isTrue(); - assertThat(list.contains(4)).isTrue(); + assertThat(list).contains(1); + assertThat(list).contains(2); + assertThat(list).contains(3); + assertThat(list).contains(4); } // BZ #748752 @@ -1436,55 +1247,55 @@ public void traitsInBatchExecution() { "\n" + "rule \"create student\" \n" + " when\n" + - " $student : Person( age < 26 )\n" + + " $student : Person(age < 26)\n" + " then\n" + - " Student s = don( $student, Student.class );\n" + + " Student s = don($student, Student.class);\n" + " s.setSchool(\"Masaryk University\");\n" + "end\n" + "\n" + "rule \"print student\"\n" + " when\n" + - " student : Person( this isA Student )\n" + + " student : Person(this isA Student)\n" + " then" + - " list.add( 1 );\n" + + " list.add(1);\n" + "end\n" + "\n" + "rule \"print school\"\n" + " when\n" + - " Student( $school : school )\n" + + " Student($school : school)\n" + " then\n" + - " list.add( 2 );\n" + + " list.add(2);\n" + "end"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( str.getBytes() ), ResourceType.DRL ); + kbuilder.add(new ByteArrayResource(str.getBytes()), ResourceType.DRL); if (kbuilder.hasErrors()) { throw new RuntimeException(kbuilder.getErrors().toString()); } - List list = new ArrayList(); + List list = new ArrayList<>(); KieBase kbase = kbuilder.newKieBase(); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); StatelessKieSession ksession = kbase.newStatelessKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); List> commands = new ArrayList>(); Person student = new Person("student", 18); - commands.add( CommandFactory.newInsert( student )); + commands.add(CommandFactory.newInsert(student)); LOGGER.debug("Starting execution..."); commands.add(CommandFactory.newFireAllRules()); ksession.execute(CommandFactory.newBatchExecution(commands)); LOGGER.debug("Finished..."); - assertThat(list.size()).isEqualTo(2); - assertThat(list.contains(1)).isTrue(); - assertThat(list.contains(2)).isTrue(); + assertThat(list).hasSize(2); + assertThat(list).contains(1); + assertThat(list).contains(2); } @Test(timeout=10000) @@ -1504,7 +1315,7 @@ public void testManyTraitsStateless() { "" + "rule \"Nice\"\n" + "when\n" + - " $n : NiceMessage( $m : message )\n" + + " $n : NiceMessage($m : message)\n" + "then\n" + "end" + "\n" + @@ -1515,32 +1326,32 @@ public void testManyTraitsStateless() { " Message message = new Message();\n" + " message.setMessage(\"Hello World\");\n" + " insert(message);\n" + - " don( message, NiceMessage.class );\n" + + " don(message, NiceMessage.class);\n" + "\n" + " Message unreadMessage = new Message();\n" + " unreadMessage.setMessage(\"unread\");\n" + " insert(unreadMessage);\n" + - " don( unreadMessage, NiceMessage.class );\n" + + " don(unreadMessage, NiceMessage.class);\n" + "\n" + " Message oldMessage = new Message();\n" + " oldMessage.setMessage(\"old\");\n" + " insert(oldMessage);\n" + - " don( oldMessage, NiceMessage.class );" + + " don(oldMessage, NiceMessage.class);" + " list.add(\"OK\");\n" + " end"; - KieBase kb = getKieBaseFromString( source ); - TraitFactoryImpl.setMode(mode, kb ); + KieBase kb = getKieBaseFromString(source); + TraitFactoryImpl.setMode(mode, kb); KieSession ksession = kb.newKieSession(); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - ksession.execute( CommandFactory.newFireAllRules() ); + ksession.execute(CommandFactory.newFireAllRules()); - assertThat(list.size()).isEqualTo(1); - assertThat(list.contains("OK")).isTrue(); + assertThat(list).hasSize(1); + assertThat(list).contains("OK"); } @@ -1576,44 +1387,44 @@ public void testAliasing() { "rule \"create student\" \n" + " when\n" + " then\n" + - " Person p = new Person( \"davide\", \"UniBoh\", \"Floor84\", 1 ); \n" + - " Student s = don( p, Student.class );\n" + + " Person p = new Person(\"davide\", \"UniBoh\", \"Floor84\", 1); \n" + + " Student s = don(p, Student.class);\n" + "end\n" + "\n" + "rule \"print school\"\n" + " when\n" + - " $student : Student( $school : school == \"UniBoh\", $f : fields, fields[ \"workPlace\" ] == \"UniBoh\" )\n" + + " $student : Student($school : school == \"UniBoh\", $f : fields, fields[ \"workPlace\" ] == \"UniBoh\")\n" + " then \n " + - " $student.setRank( 99 ); \n" + - " $f.put( \"school\", \"Skool\" ); \n" + - - " list.add( $school );\n" + - " list.add( $f.get( \"school\" ) );\n" + - " list.add( $student.getSchool() );\n" + - " list.add( $f.keySet() );\n" + - " list.add( $f.entrySet() );\n" + - " list.add( $f.values() );\n" + - " list.add( $f.containsKey( \"school\" ) );\n" + - " list.add( $student.getRank() );\n" + - " list.add( $f.get( \"address\" ) );\n" + + " $student.setRank(99); \n" + + " $f.put(\"school\", \"Skool\"); \n" + + + " list.add($school);\n" + + " list.add($f.get(\"school\"));\n" + + " list.add($student.getSchool());\n" + + " list.add($f.keySet());\n" + + " list.add($f.entrySet());\n" + + " list.add($f.values());\n" + + " list.add($f.containsKey(\"school\"));\n" + + " list.add($student.getRank());\n" + + " list.add($f.get(\"address\"));\n" + "end"; - KieSession ksession = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + KieSession ksession = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(9); - assertThat(list.contains("UniBoh")).isTrue(); - assertThat(list.contains("Skool")).isTrue(); - assertThat(((Collection) list.get(3)).containsAll(Arrays.asList("workPlace", "nomen", "level"))).isTrue(); - assertThat(((Collection) list.get(5)).containsAll(Arrays.asList("davide", "Skool", 0))).isTrue(); - assertThat(list.contains(true)).isTrue(); - assertThat(list.contains("Floor84")).isTrue(); - assertThat(list.contains(99)).isTrue(); + assertThat(list).hasSize(9); + assertThat(list).contains("UniBoh"); + assertThat(list).contains("Skool"); + assertThat((Collection) list.get(3)).contains("workPlace", "nomen", "level"); + assertThat((Collection) list.get(5)).contains("davide", "Skool", 0); + assertThat(list).contains(true); + assertThat(list).contains("Floor84"); + assertThat(list).contains(99); } @@ -1644,52 +1455,52 @@ public void testTraitLogicalRemoval() { "\n" + "rule \"Don Logical\"\n" + "when\n" + - " $s : String( this == \"trigger\" )\n" + + " $s : String(this == \"trigger\")\n" + "then\n" + - " Person p = new Person( \"john\" );\n" + - " insertLogical( p ); \n" + - " don( p, Student.class, true );\n" + + " Person p = new Person(\"john\");\n" + + " insertLogical(p); \n" + + " don(p, Student.class, true);\n" + "end\n" + " " + "rule \"Don Logical 2\"\n" + "when\n" + - " $s : String( this == \"trigger2\" )\n" + - " $p : Person( name == \"john\" )" + + " $s : String(this == \"trigger2\")\n" + + " $p : Person(name == \"john\")" + "then\n" + - " don( $p, Worker.class, true );\n" + + " don($p, Worker.class, true);\n" + "end"; KieSession ksession = getSessionFromString(drl); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - FactHandle h = ksession.insert( "trigger" ); + FactHandle h = ksession.insert("trigger"); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(3); + assertThat(ksession.getObjects()).hasSize(3); - ksession.delete( h ); + ksession.delete(h); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(0); + assertThat(ksession.getObjects()).isEmpty(); - FactHandle h1 = ksession.insert( "trigger" ); - FactHandle h2 = ksession.insert( "trigger2" ); + FactHandle h1 = ksession.insert("trigger"); + FactHandle h2 = ksession.insert("trigger2"); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(5); + assertThat(ksession.getObjects()).hasSize(5); - ksession.delete( h2 ); + ksession.delete(h2); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(3); + assertThat(ksession.getObjects()).hasSize(3); - ksession.delete( h1 ); + ksession.delete(h1); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(0); + assertThat(ksession.getObjects()).isEmpty(); } @@ -1706,7 +1517,7 @@ public void testTMSConsistencyWithNonTraitableBeans() { "rule \"Init\"\n" + "when\n" + "then\n" + - " insertLogical( new Person( \"x\", 18 ) );\n" + + " insertLogical(new Person(\"x\", 18));\n" + "end\n" + "\n" + "declare trait Student\n" + @@ -1716,29 +1527,29 @@ public void testTMSConsistencyWithNonTraitableBeans() { "\n" + "rule \"Trait\"\n" + "when\n" + - " $p : Person( )\n" + + " $p : Person()\n" + "then\n" + - " don( $p, Student.class, true );\n" + + " don($p, Student.class, true);\n" + "end\n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); ksession.fireAllRules(); - FactHandle personHandle = ksession.getFactHandles( new ClassObjectFilter( Person.class ) ).iterator().next(); + FactHandle personHandle = ksession.getFactHandles(new ClassObjectFilter(Person.class)).iterator().next(); InternalFactHandle h = ((InternalFactHandle) personHandle); - ObjectTypeConfigurationRegistry reg = h.getEntryPoint(( InternalWorkingMemory ) ksession).getObjectTypeConfigurationRegistry(); - ObjectTypeConf conf = reg.getOrCreateObjectTypeConf( h.getEntryPointId(), ((InternalFactHandle) personHandle).getObject() ); + ObjectTypeConfigurationRegistry reg = h.getEntryPoint((InternalWorkingMemory) ksession).getObjectTypeConfigurationRegistry(); + ObjectTypeConf conf = reg.getOrCreateObjectTypeConf(h.getEntryPointId(), ((InternalFactHandle) personHandle).getObject()); assertThat(conf.isTMSEnabled()).isTrue(); ksession.dispose(); @@ -1752,8 +1563,8 @@ public void testTMSConsistencyWithNonTraitableBeans() { public static class TBean { private String fld; public String getFld() { return fld; } - public void setFld( String fld ) { this.fld = fld; } - public TBean( String fld ) { this.fld = fld; } + public void setFld(String fld) { this.fld = fld; } + public TBean(String fld) { this.fld = fld; } } @@ -1777,46 +1588,44 @@ public void testTraitsLegacyWrapperCoherence() { "rule Init \n" + "when \n" + "then \n" + - " insert( new TBean(\"abc\") ); \n" + + " insert(new TBean(\"abc\")); \n" + "end \n" + "" + "rule Don \n" + "no-loop \n" + "when \n" + - " $b : TBean( ) \n" + + " $b : TBean() \n" + "then \n" + - " Mask m = don( $b, Mask.class ); \n" + - " modify (m) { setXyz( 10 ); } \n" + - " list.add( m ); \n" + + " Mask m = don($b, Mask.class); \n" + + " modify (m) { setXyz(10); } \n" + + " list.add(m); \n" + "end \n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), - ResourceType.DRL ); + kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); List list = new ArrayList(); - ksession.setGlobal("list", - list); + ksession.setGlobal("list", list); ksession.fireAllRules(); - Collection yOld = ksession.getObjects(); - assertThat(yOld.size()).isEqualTo(2); + Collection yOld = ksession.getObjects(); + assertThat(yOld).hasSize(2); TraitableBean coreOld = null; - for ( Object o : yOld ) { - if ( o instanceof TraitableBean ) { + for (Object o : yOld) { + if (o instanceof TraitableBean) { coreOld = (TraitableBean) o; break; } @@ -1826,57 +1635,51 @@ public void testTraitsLegacyWrapperCoherence() { assertThat(coreOld.getClass().getSuperclass()).isSameAs(TBean.class); assertThat(((TBean) coreOld).getFld()).isEqualTo("abc"); - assertThat(coreOld._getDynamicProperties().size()).isEqualTo(1); - assertThat(coreOld._getTraitMap().size()).isEqualTo(1); + assertThat(coreOld._getDynamicProperties()).hasSize(1); + assertThat(coreOld._getTraitMap()).hasSize(1); } @Test - public void testHasTypes() { + public void testHasTypes() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); kbuilder.add(res, ResourceType.DRL); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); kb.addPackages(kbuilder.getKnowledgePackages()); TraitFactoryImpl traitBuilder = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - TraitFactoryImpl.setMode(mode, kb ); - - try { - FactType impClass = kb.getFactType("org.drools.compiler.trait.test","Imp"); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - impClass.set(imp, "name", "aaabcd"); - - Class trait = kb.getFactType("org.drools.compiler.trait.test","Student").getFactClass(); - Class trait2 = kb.getFactType("org.drools.compiler.trait.test","Role").getFactClass(); + TraitFactoryImpl.setMode(mode, kb); - assertThat(trait).isNotNull(); + FactType impClass = kb.getFactType("org.drools.compiler.trait.test","Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + impClass.set(imp, "name", "aaabcd"); - TraitProxyImpl proxy = (TraitProxyImpl) traitBuilder.getProxy(imp, trait); - Thing thing = traitBuilder.getProxy(imp, Thing.class); + Class trait = kb.getFactType("org.drools.compiler.trait.test","Student").getFactClass(); + Class trait2 = kb.getFactType("org.drools.compiler.trait.test","Role").getFactClass(); - TraitableBean core = proxy.getObject(); + assertThat(trait).isNotNull(); + TraitProxyImpl proxy = (TraitProxyImpl) traitBuilder.getProxy(imp, trait, false); + Thing thing = traitBuilder.getProxy(imp, Thing.class, false); - TraitProxyImpl proxy2 = (TraitProxyImpl) traitBuilder.getProxy(imp, trait); - Thing thing2 = traitBuilder.getProxy(imp, Thing.class); + TraitableBean core = proxy.getObject(); - assertThat(proxy2).isSameAs(proxy); - assertThat(thing2).isSameAs(thing); - assertThat(core.getTraits().size()).isEqualTo(2); + TraitProxyImpl proxy2 = (TraitProxyImpl) traitBuilder.getProxy(imp, trait, false); + Thing thing2 = traitBuilder.getProxy(imp, Thing.class, false); + assertThat(proxy2).isSameAs(proxy); + assertThat(thing2).isSameAs(thing); - } catch ( Exception e ) { - fail( e.getMessage(), e ); - } + assertThat(core.getTraits()).hasSize(2); } @Test @@ -1898,44 +1701,42 @@ public void testTraitRedundancy() { "rule \"Don\" \n" + "no-loop \n" + "when \n" + - " $p : IPerson( age < 30 ) \n" + + " $p : IPerson(age < 30) \n" + "then \n" + - " don( $p, IStudent.class );\n" + + " don($p, IStudent.class);\n" + "end \n" + "" + "rule \"Check\" \n" + "no-loop \n" + "when \n" + - " $p : IPerson( this isA IStudent ) \n" + + " $p : IPerson(this isA IStudent) \n" + "then \n" + - " modify ($p) { setAge( 37 ); } \n" + - " shed( $p, IStudent.class );\n" + + " modify ($p) { setAge(37); } \n" + + " shed($p, IStudent.class);\n" + "end \n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), - ResourceType.DRL ); + kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); List list = new ArrayList(); - ksession.setGlobal("list", - list); + ksession.setGlobal("list", list); - ksession.insert( new StudentImpl("skool", "john", 27 ) ); + ksession.insert(new StudentImpl("skool", "john", 27)); assertThat(ksession.fireAllRules()).isEqualTo(3); - for ( Object o : ksession.getObjects() ) { + for (Object o : ksession.getObjects()) { LOGGER.debug(o.toString()); } @@ -1963,34 +1764,34 @@ public void traitSimpleTypes() { " don($mark, PassMark.class);\n" + "end\n" + "" + - "rule \"Init\" when then insert( new ExamMark() ); end \n"; + "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() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - if ( o instanceof TraitableBean ) { + for (Object o : ksession.getObjects()) { + if (o instanceof TraitableBean) { TraitableBean tb = (TraitableBean) o; - assertThat(tb._getTraitMap().size()).isEqualTo(1); + assertThat(tb._getTraitMap()).hasSize(1); BitSet bs = new BitSet(); - bs.set( 0 ); + bs.set(0); assertThat(tb.getCurrentTypeCode()).isEqualTo(bs); } - if ( o instanceof TraitProxyImpl) { + if (o instanceof TraitProxyImpl) { TraitProxyImpl tp = (TraitProxyImpl) o; - assertThat(tp.listAssignedOtnTypeCodes().size()).isEqualTo(0); + assertThat(tp.listAssignedOtnTypeCodes()).isEmpty(); } } } @@ -2020,55 +1821,55 @@ public void testTraitEncoding() { "when\n" + " $x : Entity()\n" + "then\n" + - " don( $x, A.class );\n" + + " don($x, A.class);\n" + "end\n" + "" + "rule \"donManyThing\"\n" + "when\n" + - " String( this == \"y\" ) \n" + + " String(this == \"y\") \n" + " $x : Entity()\n" + "then\n" + - " don( $x, B.class );\n" + - " don( $x, D.class );\n" + - " don( $x, F.class );\n" + - " don( $x, E.class );\n" + - " don( $x, I.class );\n" + - " don( $x, K.class );\n" + - " don( $x, J.class );\n" + - " don( $x, C.class );\n" + - " don( $x, H.class );\n" + - " don( $x, G.class );\n" + - " don( $x, L.class );\n" + - " don( $x, M.class );\n" + - " don( $x, N.class );\n" + + " don($x, B.class);\n" + + " don($x, D.class);\n" + + " don($x, F.class);\n" + + " don($x, E.class);\n" + + " don($x, I.class);\n" + + " don($x, K.class);\n" + + " don($x, J.class);\n" + + " don($x, C.class);\n" + + " don($x, H.class);\n" + + " don($x, G.class);\n" + + " don($x, L.class);\n" + + " don($x, M.class);\n" + + " don($x, N.class);\n" + "end\n" ; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); TraitRegistryImpl tr = (TraitRegistryImpl) ((TraitRuntimeComponentFactory) RuntimeComponentFactory.get()).getTraitRegistry(kbase); - LOGGER.debug( tr.getHierarchy().toString() ); + LOGGER.debug(tr.getHierarchy().toString()); - Entity ent = new Entity( "x" ); + Entity ent = new Entity("x"); KieSession ksession = kbase.newKieSession(); - ksession.insert( ent ); + ksession.insert(ent); ksession.fireAllRules(); - assertThat(ent.getMostSpecificTraits().size()).isEqualTo(1); + assertThat(ent.getMostSpecificTraits()).hasSize(1); - ksession.insert( "y" ); + ksession.insert("y"); ksession.fireAllRules(); - LOGGER.debug( ent.getMostSpecificTraits().toString() ); - assertThat(ent.getMostSpecificTraits().size()).isEqualTo(2); + LOGGER.debug(ent.getMostSpecificTraits().toString()); + assertThat(ent.getMostSpecificTraits()).hasSize(2); } @@ -2076,56 +1877,56 @@ public void testTraitEncoding() { @Test public void testTraitActualTypeCodeWithEntities() { - testTraitActualTypeCodeWithEntities( "ent", mode ); + testTraitActualTypeCodeWithEntities("ent", mode); } @Test public void testTraitActualTypeCodeWithCoreMap() { - testTraitActualTypeCodeWithEntities( "kor", mode ); + testTraitActualTypeCodeWithEntities("kor", mode); } - void testTraitActualTypeCodeWithEntities( String trig, 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() ); + 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() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - ksession.insert( trig ); + ksession.insert(trig); ksession.fireAllRules(); - TraitableBean ent = (TraitableBean) ksession.getGlobal( "core" ); + TraitableBean ent = (TraitableBean) ksession.getGlobal("core"); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("1")); - ksession.insert( "b" ); + ksession.insert("b"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("11")); - ksession.insert( "c" ); + ksession.insert("c"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("1011")); - ksession.insert( "e" ); + ksession.insert("e"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("11011")); - ksession.insert( "-c" ); + ksession.insert("-c"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("11")); - ksession.insert( "dg" ); + ksession.insert("dg"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("111111")); - ksession.insert( "-f" ); + ksession.insert("-f"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("111")); @@ -2148,75 +1949,73 @@ public void testTraitModifyCore() { "rule \"Init\" " + "when " + "then " + - " Person p = new Person( \"john\" ); " + - " insert( p ); " + + " Person p = new Person(\"john\"); " + + " insert(p); " + "end " + "" + "rule \"Don\" " + "no-loop " + "when " + - " $p : Person( name == \"john\" ) " + + " $p : Person(name == \"john\") " + "then " + - " don( $p, Student.class ); " + - " don( $p, Worker.class ); " + - " don( $p, StudentWorker.class ); " + - " don( $p, Assistant.class ); " + + " don($p, Student.class); " + + " don($p, Worker.class); " + + " don($p, StudentWorker.class); " + + " don($p, Assistant.class); " + "end " + "" + "rule \"Log S\" " + "when " + - " $t : Student() @Watch( name ) " + + " $t : Student() @Watch(name) " + "then " + - " list.add( $t.getName() ); " + + " list.add($t.getName()); " + "end " + "rule \"Log W\" " + "when " + - " $t : Worker() @Watch( name ) " + + " $t : Worker() @Watch(name) " + "then " + - " list.add( $t.getName() ); " + + " list.add($t.getName()); " + "end " + "rule \"Log SW\" " + "when " + - " $t : StudentWorker() @Watch( name ) " + + " $t : StudentWorker() @Watch(name) " + "then " + - " list.add( $t.getName() ); " + + " list.add($t.getName()); " + "end " + "rule \"Log RA\" " + "when " + - " $t : Assistant() @Watch( name ) " + + " $t : Assistant() @Watch(name) " + "then " + - " list.add( $t.getName() ); " + + " list.add($t.getName()); " + "end " + "" + "rule \"Mod\" " + "salience -10 " + "when " + - " $p : Person( name == \"john\" ) " + + " $p : Person(name == \"john\") " + "then " + - " modify ( $p ) { setName( \"alan\" ); } " + + " modify ($p) { setName(\"alan\"); } " + "end " + ""; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); - + List list = new ArrayList<>(); + ksession.setGlobal("list", list); int k = ksession.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList("john", "john", "john", "john", "alan", "alan", "alan", "alan")); assertThat(k).isEqualTo(11); - + assertThat(list).containsExactly("john", "john", "john", "john", "alan", "alan", "alan", "alan"); } @@ -2237,71 +2036,71 @@ public void testTraitModifyCore2() { "rule \"Init\" " + "when " + "then " + - " Person p = new Person( \"john\" ); " + - " insert( p ); " + + " Person p = new Person(\"john\"); " + + " insert(p); " + "end " + "" + "rule \"Don\" " + "when " + - " $p : Person( name == \"john\" ) " + + " $p : Person(name == \"john\") " + "then " + - " don( $p, Worker.class ); " + - " don( $p, StudentWorker2.class ); " + - " don( $p, Assistant.class ); " + + " don($p, Worker.class); " + + " don($p, StudentWorker2.class); " + + " don($p, Assistant.class); " + "end " + "" + "rule \"Log S\" " + "when " + - " $t : Student() @watch( name ) " + + " $t : Student() @watch(name) " + "then " + "end " + "rule \"Log W\" " + "when " + - " $t : Worker() @watch( name ) " + + " $t : Worker() @watch(name) " + "then " + "end " + "rule \"Log SW\" " + "when " + - " $t : StudentWorker() @watch( name ) " + + " $t : StudentWorker() @watch(name) " + "then " + "end " + "rule \"Log RA\" " + "when " + - " $t : Assistant() @watch( name ) " + + " $t : Assistant() @watch(name) " + "then " + "end " + "rule \"Log Px\" " + "salience -1 " + "when " + - " $p : Person() @watch( name ) " + + " $p : Person() @watch(name) " + "then " + "end " + "" + "rule \"Mod\" " + "salience -10 " + "when " + - " String( this == \"go\" ) " + - " $p : Student( name == \"john\" ) " + + " String(this == \"go\") " + + " $p : Student(name == \"john\") " + "then " + - " modify ( $p ) { setName( \"alan\" ); } " + + " modify ($p) { setName(\"alan\"); } " + "end "; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + 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() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); int k = ksession.fireAllRules(); assertThat(k).isEqualTo(7); - ksession.insert( "go" ); + ksession.insert("go"); k = ksession.fireAllRules(); assertThat(k).isEqualTo(6); @@ -2324,48 +2123,48 @@ public void testTraitModifyCore2a() { "rule \"Init\" \n" + "when \n" + "then \n" + - " Person p = new Person( \"john\" ); \n" + - " insert( p ); \n" + + " Person p = new Person(\"john\"); \n" + + " insert(p); \n" + "end \n" + "" + "rule \"Don\" \n" + "when \n" + - " $p : Person( name == \"john\" ) \n" + + " $p : Person(name == \"john\") \n" + "then \n" + - " don( $p, Worker.class ); \n" + - " don( $p, StudentWorker.class ); \n" + + " don($p, Worker.class); \n" + + " don($p, StudentWorker.class); \n" + "end \n" + "" + "rule \"Log W\" \n" + "when \n" + - " $t : Worker( this isA StudentWorker ) @watch( name ) \n" + + " $t : Worker(this isA StudentWorker) @watch(name) \n" + "then \n" + - " list.add( true ); \n" + + " list.add(true); \n" + "end \n" + "rule \"Log SW\" \n" + "when \n" + - " $t : StudentWorker() @watch( name ) \n" + + " $t : StudentWorker() @watch(name) \n" + "then \n" + "end \n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + 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() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - ArrayList list = new ArrayList( ); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - int k = ksession.fireAllRules(); + ksession.fireAllRules(); - assertThat(list.contains(true)).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains(true); } @@ -2397,80 +2196,80 @@ public void testTraitModifyCore3() { "" + "rule \"Init\" when \n" + "then \n" + - " insert( new Core() );" + + " insert(new Core());" + "end \n" + "" + "rule \"donManyThing\"\n" + "when\n" + - " $x : Core( id == 0 )\n" + + " $x : Core(id == 0)\n" + "then\n" + - " don( $x, A.class );\n" + - " don( $x, B.class );\n" + - " don( $x, D.class );\n" + - " don( $x, F.class );\n" + - " don( $x, E.class );\n" + - " don( $x, I.class );\n" + - " don( $x, K.class );\n" + - " don( $x, J.class );\n" + - " don( $x, C.class );\n" + - " don( $x, H.class );\n" + - " don( $x, G.class );\n" + - " don( $x, L.class );\n" + - " don( $x, M.class );\n" + - " don( $x, N.class );\n" + + " don($x, A.class);\n" + + " don($x, B.class);\n" + + " don($x, D.class);\n" + + " don($x, F.class);\n" + + " don($x, E.class);\n" + + " don($x, I.class);\n" + + " don($x, K.class);\n" + + " don($x, J.class);\n" + + " don($x, C.class);\n" + + " don($x, H.class);\n" + + " don($x, G.class);\n" + + " don($x, L.class);\n" + + " don($x, M.class);\n" + + " don($x, N.class);\n" + "end\n" + "\n" + "\n" + "\n" + - "rule \"Log A\" when $x : A( id == 1 ) then list.add( 1 ); end \n" + - "rule \"Log B\" when $x : B( id == 1 ) then list.add( 2 ); end \n" + - "rule \"Log C\" when $x : C( id == 1 ) then list.add( 3 ); end \n" + - "rule \"Log D\" when $x : D( id == 1 ) then list.add( 4 ); end \n" + - "rule \"Log E\" when $x : E( id == 1 ) then list.add( 5 ); end \n" + - "rule \"Log F\" when $x : F( id == 1 ) then list.add( 6 ); end \n" + - "rule \"Log G\" when $x : G( id == 1 ) then list.add( 7 ); end \n" + - "rule \"Log H\" when $x : H( id == 1 ) then list.add( 8 ); end \n" + - "rule \"Log I\" when $x : I( id == 1 ) then list.add( 9 ); end \n" + - "rule \"Log J\" when $x : J( id == 1 ) then list.add( 10 ); end \n" + - "rule \"Log K\" when $x : K( id == 1 ) then list.add( 11 ); end \n" + - "rule \"Log L\" when $x : L( id == 1 ) then list.add( 12 ); end \n" + - "rule \"Log M\" when $x : M( id == 1 ) then list.add( 13 ); end \n" + - "rule \"Log N\" when $x : N( id == 1 ) then list.add( 14 ); end \n" + + "rule \"Log A\" when $x : A(id == 1) then list.add(1); end \n" + + "rule \"Log B\" when $x : B(id == 1) then list.add(2); end \n" + + "rule \"Log C\" when $x : C(id == 1) then list.add(3); end \n" + + "rule \"Log D\" when $x : D(id == 1) then list.add(4); end \n" + + "rule \"Log E\" when $x : E(id == 1) then list.add(5); end \n" + + "rule \"Log F\" when $x : F(id == 1) then list.add(6); end \n" + + "rule \"Log G\" when $x : G(id == 1) then list.add(7); end \n" + + "rule \"Log H\" when $x : H(id == 1) then list.add(8); end \n" + + "rule \"Log I\" when $x : I(id == 1) then list.add(9); end \n" + + "rule \"Log J\" when $x : J(id == 1) then list.add(10); end \n" + + "rule \"Log K\" when $x : K(id == 1) then list.add(11); end \n" + + "rule \"Log L\" when $x : L(id == 1) then list.add(12); end \n" + + "rule \"Log M\" when $x : M(id == 1) then list.add(13); end \n" + + "rule \"Log N\" when $x : N(id == 1) then list.add(14); end \n" + "" + - "rule \"Log Core\" when $x : Core( $id : id ) then end \n" + + "rule \"Log Core\" when $x : Core($id : id) then end \n" + "" + "rule \"Mod\" \n" + "salience -10 \n" + "when \n" + - " String( this == \"go\" ) \n" + - " $x : Core( id == 0 ) \n" + + " String(this == \"go\") \n" + + " $x : Core(id == 0) \n" + "then \n" + - " modify ( $x ) { setId( 1 ); }" + + " modify ($x) { setId(1); }" + "end \n" + ""; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + 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() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); - List list = new ArrayList(); + List list = new ArrayList<>(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); ksession.fireAllRules(); - ksession.insert( "go" ); + ksession.insert("go"); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(14); - for ( int j = 1; j <= 14; j++ ) { - assertThat(list.contains(j)).isTrue(); + assertThat(list).hasSize(14); + for (int j = 1; j <= 14; j++) { + assertThat(list).contains(j); } @@ -2515,77 +2314,74 @@ public void testTraitModifyCoreWithPropertyReactivity() { "rule \"Init\" \n" + "when \n" + "then \n" + - " Person p = new Person( 109.99, \"john\", 18 ); \n" + - " insert( p ); \n" + + " Person p = new Person(109.99, \"john\", 18); \n" + + " insert(p); \n" + "end \n" + "" + "rule \"Don\" \n" + "when \n" + - " $p : Person( name == \"john\" ) \n" + + " $p : Person(name == \"john\") \n" + "then \n" + - " don( $p, StudentWorker.class ); \n" + - " don( $p, Assistant.class ); \n" + + " don($p, StudentWorker.class); \n" + + " don($p, Assistant.class); \n" + "end \n" + "" + "rule \"Log S\" \n" + "when \n" + - " $t : Student( age == 44 ) \n" + + " $t : Student(age == 44) \n" + "then \n" + - " list.add( 1 );\n " + + " list.add(1);\n " + "end \n" + "rule \"Log W\" \n" + "when \n" + - " $t : Worker( name == \"alan\" ) \n" + + " $t : Worker(name == \"alan\") \n" + "then \n" + - " list.add( 2 );\n " + + " list.add(2);\n " + "end \n" + "rule \"Log SW\" \n" + "when \n" + - " $t : StudentWorker( age == 44 ) \n" + + " $t : StudentWorker(age == 44) \n" + "then \n" + - " list.add( 3 );\n " + + " list.add(3);\n " + "end \n" + "rule \"Log Pers\" \n" + "when \n" + - " $t : Person( age == 44 ) \n" + + " $t : Person(age == 44) \n" + "then \n" + - " list.add( 4 );\n " + + " list.add(4);\n " + "end \n" + "" + "rule \"Mod\" \n" + "salience -10 \n" + "when \n" + - " String( this == \"go\" ) \n" + - " $p : Student( name == \"john\" ) \n" + + " String(this == \"go\") \n" + + " $p : Student(name == \"john\") \n" + "then \n" + - " modify ( $p ) { setSchool( \"myschool\" ), setAge( 44 ), setName( \"alan\" ); } " + + " 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() ); + 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() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); List list = new ArrayList(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); int k = ksession.fireAllRules(); - ksession.insert( "go" ); + ksession.insert("go"); k = ksession.fireAllRules(); assertThat(k).isEqualTo(5); - assertThat(list.size()).isEqualTo(4); - assertThat(list.contains(1)).isTrue(); - assertThat(list.contains(2)).isTrue(); - assertThat(list.contains(3)).isTrue(); - assertThat(list.contains(4)).isTrue(); + assertThat(list).hasSize(4); + assertThat(list).contains(1, 2, 3, 4); } @@ -2609,22 +2405,22 @@ public void testTraitEncodeExtendingNonTrait() { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s2.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s2.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalRuleBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KnowledgeBuilder kbuilder2 = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder2.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder2.hasErrors() ) { - fail( kbuilder2.getErrors().toString() ); + kbuilder2.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder2.hasErrors()) { + fail(kbuilder2.getErrors().toString()); } - kbase.addPackages( kbuilder2.getKnowledgePackages() ); + kbase.addPackages(kbuilder2.getKnowledgePackages()); } @@ -2634,26 +2430,26 @@ public void testTraitEncodeExtendingNonTrait() { public void isAWithBackChaining() { String source = "org/drools/compiler/factmodel/traits/testTraitIsAWithBC.drl"; - KieSession ksession = getSession( source ); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + KieSession ksession = getSession(source); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); ksession.fireAllRules(); - ksession.insert( "Como" ); + ksession.insert("Como"); ksession.fireAllRules(); - assertThat(list.contains("Italy")).isTrue(); + assertThat(list).contains("Italy"); } @Test - public void testIsAEvaluatorOnClassification( ) { + public void testIsAEvaluatorOnClassification() { String source = "package t.x \n" + "\n" + "global java.util.List list; \n" + @@ -2674,7 +2470,7 @@ public void testIsAEvaluatorOnClassification( ) { "then\n" + " Entity o = new Entity();\n" + " insert(o);\n" + - " don( o, D.class ); \n" + + " don(o, D.class); \n" + "end\n" + "" + "rule Don when\n" + @@ -2684,35 +2480,34 @@ public void testIsAEvaluatorOnClassification( ) { "" + "rule \"Rule 0 >> http://t/x#D\"\n" + "when\n" + - " $t : org.drools.base.factmodel.traits.Thing( $c : core, this not isA t.x.E.class, this isA t.x.D.class ) " + + " $t : org.drools.base.factmodel.traits.Thing($c : core, this not isA t.x.E.class, this isA t.x.D.class) " + "then\n" + - " list.add( \"E\" ); \n" + - " don( $t, E.class ); \n" + + " list.add(\"E\"); \n" + + " don($t, E.class); \n" + "end\n" + "" + "rule React \n" + "when E() then \n" + - " list.add( \"X\" ); \n" + + " list.add(\"X\"); \n" + "end \n" ; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.size()).isEqualTo(2); - assertThat(list.contains("E")).isTrue(); - assertThat(list.contains("X")).isTrue(); + assertThat(list).hasSize(2); + assertThat(list).contains("E", "X"); } @Test - public void testShedWithTMS( ) { + public void testShedWithTMS() { String source = "package t.x \n" + "\n" + "global java.util.List list; \n" + @@ -2733,8 +2528,8 @@ public void testShedWithTMS( ) { "then\n" + " Entity o = new Entity();\n" + " insert(o);\n" + - " don( o, Thing.class ); \n" + - " don( o, D.class ); \n" + + " don(o, Thing.class); \n" + + " don(o, D.class); \n" + "end\n" + "" + "rule Don when\n" + @@ -2744,15 +2539,15 @@ public void testShedWithTMS( ) { "" + "rule \"Rule 0 >> http://t/x#D\"\n" + "when\n" + - " $t : org.drools.base.factmodel.traits.Thing( $c : core, _isTop(), this not isA t.x.E.class, this isA t.x.D.class ) " + + " $t : org.drools.base.factmodel.traits.Thing($c : core, _isTop(), this not isA t.x.E.class, this isA t.x.D.class) " + "then\n" + - " list.add( \"E\" ); \n" + - " don( $t, E.class ); \n" + + " list.add(\"E\"); \n" + + " don($t, E.class); \n" + "end\n" + "" + "rule React \n" + "when $x : E() then \n" + - " list.add( \"X\" ); \n" + + " list.add(\"X\"); \n" + "end \n" + "" + "rule Shed \n" + @@ -2760,31 +2555,30 @@ public void testShedWithTMS( ) { " $s : String() \n" + " $d : Entity() \n" + "then \n" + - " delete( $s ); \n" + - " shed( $d, D.class );\n" + + " delete($s); \n" + + " shed($d, D.class);\n" + "end \n" + "" ; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list.size()).isEqualTo(2); - assertThat(list.contains("E")).isTrue(); - assertThat(list.contains("X")).isTrue(); + LOGGER.debug(list.toString()); + assertThat(list).hasSize(2); + assertThat(list).contains("E", "X"); - ks.insert( "shed" ); + ks.insert("shed"); ks.fireAllRules(); - for ( Object o : ks.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ks.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(ks.getObjects().size()).isEqualTo(3); + assertThat(ks.getObjects()).hasSize(3); } @@ -2812,7 +2606,7 @@ public void testTraitInitialization() { "declare Bar\n" + " @Traitable()\n" + " hardList : List \n" + - " moreList : List = Arrays.asList( 1, 2, 3 ) \n" + + " moreList : List = Arrays.asList(1, 2, 3) \n" + "\n" + "end\n" + "" + @@ -2820,46 +2614,46 @@ public void testTraitInitialization() { "then\n" + " Bar o = new Bar();\n" + " insert(o);\n" + - " Thing t = don( o, Thing.class ); \n" + - " t.getFields().put( \"otraList\", Arrays.asList( 42 ) ); \n" + - " don( o, Foo.class ); \n" + + " Thing t = don(o, Thing.class); \n" + + " t.getFields().put(\"otraList\", Arrays.asList(42)); \n" + + " don(o, Foo.class); \n" + "end\n" + "" + "rule Don when\n" + - " $x : Foo( $h : hardList, $s : softList, $o : otraList, $m : moreList, $i : primFld, $d : primDbl ) \n" + + " $x : Foo($h : hardList, $s : softList, $o : otraList, $m : moreList, $i : primFld, $d : primDbl) \n" + "then \n" + - " list.add( $h ); \n" + - " list.add( $s ); \n" + - " list.add( $o ); \n" + - " list.add( $m ); \n" + - " list.add( $i ); \n" + - " list.add( $d ); \n" + + " list.add($h); \n" + + " list.add($s); \n" + + " list.add($o); \n" + + " list.add($m); \n" + + " list.add($i); \n" + + " list.add($d); \n" + "end\n" + "" ; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.size()).isEqualTo(6); - assertThat(list.contains(null)).isFalse(); + assertThat(list).hasSize(6); + assertThat(list).doesNotContainNull(); - List hard = (List) list.get( 0 ); - List soft = (List) list.get( 1 ); - List otra = (List) list.get( 2 ); - List more = (List) list.get( 3 ); + List hard = (List) list.get(0); + List soft = (List) list.get(1); + List otra = (List) list.get(2); + List more = (List) list.get(3); - assertThat(hard.isEmpty()).isTrue(); - assertThat(soft.isEmpty()).isTrue(); - assertThat(Arrays.asList(1, 2, 3)).isEqualTo(more); - assertThat(List.of(42)).isEqualTo(otra); + assertThat(hard).isEmpty(); + assertThat(soft).isEmpty(); + assertThat(more).containsExactly(1, 2, 3); + assertThat(otra).containsExactly(42); - assertThat(list.contains(3)).isTrue(); - assertThat(list.contains(0.421)).isTrue(); + assertThat(list).contains(3); + assertThat(list).contains(0.421); } @@ -2892,21 +2686,21 @@ public void testUnTraitedBean() { "end\n" + "" + "rule Check when\n" + - " $x : Bar( this not isA Foo ) \n" + + " $x : Bar(this not isA Foo) \n" + "then \n" + "end\n" + "rule Check2 when\n" + - " $x : Bar2( this not isA Foo ) \n" + + " $x : Bar2(this not isA Foo) \n" + "then \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); } @@ -2914,7 +2708,7 @@ public void testUnTraitedBean() { @Test - public void testIsAOptimization( ) { + public void testIsAOptimization() { String source = "package t.x \n" + "import java.util.*; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -2937,44 +2731,44 @@ public void testIsAOptimization( ) { "rule Init when\n" + "then\n" + " Kore k = new Kore();\n" + - " don( k, E.class ); \n" + + " don(k, E.class); \n" + "end\n" + "" + "rule Check_1 when\n" + - " $x : Kore( this isA [ B, D ] ) \n" + + " $x : Kore(this isA [ B, D ]) \n" + "then \n" + - " list.add( \" B+D \" ); \n" + + " list.add(\" B+D \"); \n" + "end\n" + "" + "rule Check_2 when\n" + - " $x : Kore( this isA [ A ] ) \n" + + " $x : Kore(this isA [ A ]) \n" + "then \n" + - " list.add( \" A \" ); \n" + + " list.add(\" A \"); \n" + "end\n" + "rule Check_3 when\n" + - " $x : Kore( this not isA [ F ] ) \n" + + " $x : Kore(this not isA [ F ]) \n" + "then \n" + - " list.add( \" F \" ); \n" + + " list.add(\" F \"); \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.size()).isEqualTo(3); + assertThat(list).hasSize(3); } @Test - public void testTypeRefractionOnInsert( ) { + public void testTypeRefractionOnInsert() { String source = "package t.x \n" + "import java.util.*; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -2997,37 +2791,37 @@ public void testTypeRefractionOnInsert( ) { "rule Init when\n" + "then\n" + " Kore k = new Kore();\n" + - " don( k, B.class ); \n" + - " don( k, C.class ); \n" + - " don( k, D.class ); \n" + - " don( k, E.class ); \n" + - " don( k, A.class ); \n" + - " don( k, F.class ); \n" + + " don(k, B.class); \n" + + " don(k, C.class); \n" + + " don(k, D.class); \n" + + " don(k, E.class); \n" + + " don(k, A.class); \n" + + " don(k, F.class); \n" + "end\n" + "" + "rule Check_1 when\n" + - " $x : A( ) \n" + + " $x : A() \n" + "then \n" + - " list.add( $x ); \n" + + " list.add($x); \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); } @Test - public void testTypeRefractionOnQuery( ) { + public void testTypeRefractionOnQuery() { String source = "declare BaseObject\n" + "@Traitable\n" + "id : String @key\n" + @@ -3057,19 +2851,19 @@ public void testTypeRefractionOnQuery( ) { "end"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); ks.fireAllRules(); - QueryResults res = ks.getQueryResults( "QueryTraitA" ); + QueryResults res = ks.getQueryResults("QueryTraitA"); - assertThat(res.size()).isEqualTo(1); + assertThat(res).hasSize(1); } @Test - public void testTypeRefractionOnQuery2( ) { + public void testTypeRefractionOnQuery2() { String source = "package t.x \n" + "import java.util.*; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -3093,43 +2887,43 @@ public void testTypeRefractionOnQuery2( ) { "rule Init when\n" + "then\n" + " Kore k = new Kore();\n" + - " don( k, C.class ); \n" + - " don( k, D.class ); \n" + - " don( k, E.class ); \n" + - " don( k, B.class ); \n" + - " don( k, A.class ); \n" + - " don( k, F.class ); \n" + - " don( k, G.class ); \n" + - " shed( k, B.class ); \n" + + " don(k, C.class); \n" + + " don(k, D.class); \n" + + " don(k, E.class); \n" + + " don(k, B.class); \n" + + " don(k, A.class); \n" + + " don(k, F.class); \n" + + " don(k, G.class); \n" + + " shed(k, B.class); \n" + "end\n" + "" + "rule RuleA\n" + "when \n" + - " $x : A( ) \n" + + " $x : A() \n" + "then \n" + "end\n" + " \n" + "query queryA1\n" + - " $x := A( ) \n" + + " $x := A() \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); QueryResults res; - res = ks.getQueryResults( "queryA1" ); - assertThat(res.size()).isEqualTo(1); + res = ks.getQueryResults("queryA1"); + assertThat(res).hasSize(1); } @Test - public void testNodePartitioningByProxies( ) { + public void testNodePartitioningByProxies() { String source = "package t.x " + "import java.util.*; " + "import org.drools.base.factmodel.traits.Thing " + @@ -3154,50 +2948,50 @@ public void testNodePartitioningByProxies( ) { "then " + " Kore k = new Kore(); " + - " don( k, C.class ); " + - " don( k, D.class ); " + - " don( k, B.class ); " + - " don( k, A.class ); " + - " don( k, F.class ); " + - " don( k, E.class ); " + - " don( k, G.class ); " + + " don(k, C.class); " + + " don(k, D.class); " + + " don(k, B.class); " + + " don(k, A.class); " + + " don(k, F.class); " + + " don(k, E.class); " + + " don(k, G.class); " + "end "; - for ( char c = 'A'; c <= 'G'; c++ ) { + for (char c = 'A'; c <= 'G'; c++) { String C = "" + c; source += "rule Rule" + C + - " when " + C + "() then list.add( '"+ C + "' ); end "; + " when " + C + "() then list.add('"+ C + "'); end "; } source += "rule RuleAll " + "when " + " A() B() C() D() E() F() G() " + "then " + - " list.add( 'Z' ); " + + " list.add('Z'); " + "end " + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'Z')); + LOGGER.debug(list.toString()); + assertThat(list).containsExactly('A', 'B', 'C', 'D', 'E', 'F', 'G', 'Z'); - for ( Object o : ks.getObjects(object -> object instanceof TraitableBean) ) { - Set otns = checkOTNPartitioning( (TraitableBean) o, ks ); - assertThat(otns.size()).isEqualTo(7); + for (Object o : ks.getObjects(object -> object instanceof TraitableBean)) { + Set otns = checkOTNPartitioning((TraitableBean) o, ks); + assertThat(otns).hasSize(7); } } @Test - public void testNodePartitioningByProxiesAfterShed( ) { + public void testNodePartitioningByProxiesAfterShed() { String source = "package t.x " + "import java.util.*; " + "import org.drools.base.factmodel.traits.Thing \n" + @@ -3222,22 +3016,22 @@ public void testNodePartitioningByProxiesAfterShed( ) { "then \n" + " Kore k = new Kore(); \n" + - " don( k, C.class ); \n" + - " don( k, D.class ); \n" + - " don( k, B.class ); \n" + - " don( k, A.class ); \n" + - " don( k, F.class ); \n" + - " don( k, E.class ); \n" + - " don( k, G.class ); \n" + - " shed( k, B.class ); \n" + + " don(k, C.class); \n" + + " don(k, D.class); \n" + + " don(k, B.class); \n" + + " don(k, A.class); \n" + + " don(k, F.class); \n" + + " don(k, E.class); \n" + + " don(k, G.class); \n" + + " shed(k, B.class); \n" + "end \n"; - for ( char c = 'A'; c <= 'G'; c++ ) { + for (char c = 'A'; c <= 'G'; c++) { String C = "" + c; source += "rule Rule" + C + " when \n" + C + "() \nthen\n" + " System.out.println(\"Rule " + C + "\");\n" + - " list.add( '"+ C + "' ); \n" + + " list.add('"+ C + "'); \n" + "end \n"; } @@ -3245,32 +3039,32 @@ public void testNodePartitioningByProxiesAfterShed( ) { "when \n" + " A() D() G() \n" + "then \n" + - " list.add( 'Z' ); \n" + + " list.add('Z'); \n" + "end \n" + ""; System.out.println(source); - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList('A', 'D', 'G', 'Z')); + LOGGER.debug(list.toString()); + assertThat(list).containsExactly('A', 'D', 'G', 'Z'); - for ( Object o : ks.getObjects(object -> object instanceof TraitableBean) ) { - Set otns = checkOTNPartitioning( (TraitableBean) o, ks ); - assertThat(otns.size()).isEqualTo(3); + for (Object o : ks.getObjects(object -> object instanceof TraitableBean)) { + Set otns = checkOTNPartitioning((TraitableBean) o, ks); + assertThat(otns).hasSize(3); } } @Test - public void testTypeRefractionOnQueryWithIsA( ) { + public void testTypeRefractionOnQueryWithIsA() { String source = "package t.x \n" + "import java.util.*; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -3293,42 +3087,42 @@ public void testTypeRefractionOnQueryWithIsA( ) { "rule Init when\n" + "then\n" + " Kore k = new Kore();\n" + - " don( k, C.class ); \n" + - " don( k, D.class ); \n" + - " don( k, E.class ); \n" + - " don( k, B.class ); \n" + - " don( k, A.class ); \n" + - " don( k, F.class ); \n" + - " shed( k, B.class ); \n" + + " don(k, C.class); \n" + + " don(k, D.class); \n" + + " don(k, E.class); \n" + + " don(k, B.class); \n" + + " don(k, A.class); \n" + + " don(k, F.class); \n" + + " shed(k, B.class); \n" + "end\n" + "" + " \n" + "query queryA\n" + - " $x := Kore( this isA A ) \n" + + " $x := Kore(this isA A) \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - QueryResults res = ks.getQueryResults( "queryA" ); + QueryResults res = ks.getQueryResults("queryA"); Iterator iter = res.iterator(); - Object a = iter.next().get( "$x" ); - assertThat(iter.hasNext()).isFalse(); + Object a = iter.next().get("$x"); + assertThat(iter).isExhausted(); - assertThat(res.size()).isEqualTo(1); + assertThat(res).hasSize(1); } @Test - public void testCoreUpdate4( ) { + public void testCoreUpdate4() { String source = "package t.x \n" + "import java.util.*; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -3350,8 +3144,8 @@ public void testCoreUpdate4( ) { "rule Init \n" + "when\n" + "then\n" + - " Kore k = new Kore( 44 );\n" + - " insert( k ); \n" + + " Kore k = new Kore(44);\n" + + " insert(k); \n" + "end\n" + "" + "" + @@ -3360,27 +3154,27 @@ public void testCoreUpdate4( ) { "when\n" + " $x : Kore() \n" + "then \n" + - " don( $x, A.class ); \n" + + " don($x, A.class); \n" + "end\n" + "rule React \n" + "salience 1" + "when\n" + - " $x : Kore( this isA A.class ) \n" + + " $x : Kore(this isA A.class) \n" + "then \n" + - " list.add( $x ); \n" + + " list.add($x); \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - for ( Object o : ks.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ks.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); } @@ -3403,118 +3197,118 @@ public void traitLogicalSupportAnddelete() { " name : String\n" + "end\n" + "\n" + - "rule Init when then insert( new Person( \"john\" ) ); end \n" + + "rule Init when then insert(new Person(\"john\")); end \n" + "" + "rule \"Don Logical\"\n" + "when\n" + - " $s : String( this == \"trigger1\" )\n" + + " $s : String(this == \"trigger1\")\n" + " $p : Person() \n" + "then\n" + - " don( $p, Student.class, true );\n" + + " don($p, Student.class, true);\n" + "end\n" + "" + "rule \"Don Logical2\"\n" + "when\n" + - " $s : String( this == \"trigger2\" )\n" + + " $s : String(this == \"trigger2\")\n" + " $p : Person() \n" + "then\n" + - " don( $p, Student.class, true );\n" + + " don($p, Student.class, true);\n" + "end\n" + "" + "rule \"Undon \"\n" + "when\n" + - " $s : String( this == \"trigger3\" )\n" + + " $s : String(this == \"trigger3\")\n" + " $p : Person() \n" + "then\n" + - " shed( $p, org.drools.base.factmodel.traits.Thing.class ); " + - " delete( $s ); \n" + + " shed($p, org.drools.base.factmodel.traits.Thing.class); " + + " delete($s); \n" + "end\n" + " " + "rule \"Don Logical3\"\n" + "when\n" + - " $s : String( this == \"trigger4\" )\n" + + " $s : String(this == \"trigger4\")\n" + " $p : Person() \n" + "then\n" + - " don( $p, Student.class, true );" + + " don($p, Student.class, true);" + "end\n" + " " + "rule \"Undon 2\"\n" + "when\n" + - " $s : String( this == \"trigger5\" )\n" + + " $s : String(this == \"trigger5\")\n" + " $p : Person() \n" + "then\n" + - " delete( $s ); \n" + - " delete( $p ); \n" + + " delete($s); \n" + + " delete($p); \n" + "end\n" + ""; KieSession ksession = getSessionFromString(drl); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); List list = new ArrayList(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); - FactHandle h1 = ksession.insert( "trigger1" ); - FactHandle h2 = ksession.insert( "trigger2" ); + FactHandle h1 = ksession.insert("trigger1"); + FactHandle h2 = ksession.insert("trigger2"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(4); + assertThat(ksession.getObjects()).hasSize(4); - ksession.delete( h1 ); + ksession.delete(h1); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(3); + assertThat(ksession.getObjects()).hasSize(3); - ksession.delete( h2 ); + ksession.delete(h2); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(1); + assertThat(ksession.getObjects()).hasSize(1); - ksession.insert( "trigger3" ); + ksession.insert("trigger3"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString()); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(1); + assertThat(ksession.getObjects()).hasSize(1); - ksession.insert( "trigger4" ); + ksession.insert("trigger4"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(3); + assertThat(ksession.getObjects()).hasSize(3); - ksession.insert( "trigger5" ); + ksession.insert("trigger5"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(1); + assertThat(ksession.getObjects()).hasSize(1); } @Test @@ -3534,18 +3328,18 @@ public void testShedThing() { "" + "rule \"Init\" when \n" + "then \n" + - " insert( new Core() );" + + " insert(new Core());" + "end \n" + "" + "rule \"donManyThing\"\n" + "when\n" + - " $x : Core( id == 0 )\n" + + " $x : Core(id == 0)\n" + "then\n" + - " don( $x, A.class );\n" + - " don( $x, B.class );\n" + - " don( $x, C.class );\n" + - " don( $x, D.class );\n" + - " don( $x, E.class );\n" + + " don($x, A.class);\n" + + " don($x, B.class);\n" + + " don($x, C.class);\n" + + " don($x, D.class);\n" + + " don($x, E.class);\n" + "end\n" + "\n" + "\n" + @@ -3553,38 +3347,38 @@ public void testShedThing() { "rule \"Mod\" \n" + "salience -10 \n" + "when \n" + - " $g : String( this == \"go\" ) \n" + - " $x : Core( id == 0 ) \n" + + " $g : String(this == \"go\") \n" + + " $x : Core(id == 0) \n" + "then \n" + - " shed( $x, Thing.class ); " + - " delete( $g ); \n\n" + + " shed($x, Thing.class); " + + " delete($g); \n\n" + "end \n" + ""; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + 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() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); List list = new ArrayList(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); ksession.fireAllRules(); - ksession.insert( "go" ); + ksession.insert("go"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(ksession.getObjects().size()).isEqualTo(1); + assertThat(ksession.getObjects()).hasSize(1); } @@ -3605,18 +3399,18 @@ public void testdeleteThings() { "" + "rule \"Init\" when \n" + "then \n" + - " insert( new Core() );" + + " insert(new Core());" + "end \n" + "" + "rule \"donManyThing\"\n" + "when\n" + - " $x : Core( id == 0 )\n" + + " $x : Core(id == 0)\n" + "then\n" + - " don( $x, A.class );\n" + - " don( $x, B.class );\n" + - " don( $x, C.class );\n" + - " don( $x, D.class );\n" + - " don( $x, E.class );\n" + + " don($x, A.class);\n" + + " don($x, B.class);\n" + + " don($x, C.class);\n" + + " don($x, D.class);\n" + + " don($x, E.class);\n" + "end\n" + "\n" + "\n" + @@ -3624,42 +3418,42 @@ public void testdeleteThings() { "rule \"Mod\" \n" + "salience -10 \n" + "when \n" + - " $g : String( this == \"go\" ) \n" + - " $x : Core( id == 0 ) \n" + + " $g : String(this == \"go\") \n" + + " $x : Core(id == 0) \n" + "then \n" + - " delete( $x ); \n\n" + - " delete( $g ); \n\n" + + " delete($x); \n\n" + + " delete($g); \n\n" + "end \n" + ""; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + 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() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); List list = new ArrayList(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); ksession.fireAllRules(); - ksession.insert( "go" ); + ksession.insert("go"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(ksession.getObjects().size()).isEqualTo(0); + assertThat(ksession.getObjects()).isEmpty(); } @Test - public void traitLogicalRemovalSimple( ) { + public void traitLogicalRemovalSimple() { String drl = "package org.drools.compiler.trait.test;\n" + "\n" + "import org.drools.base.factmodel.traits.Traitable;\n" + @@ -3685,34 +3479,34 @@ public void traitLogicalRemovalSimple( ) { "\n" + "rule \"Don Logical\"\n" + "when\n" + - " $s : String( this == \"trigger\" )\n" + + " $s : String(this == \"trigger\")\n" + "then\n" + - " Person p = new Person( \"john\" );\n" + - " insert( p ); \n" + - " don( p, Student.class, true );\n" + - " don( p, Worker.class );\n" + - " don( p, Scholar.class );\n" + + " Person p = new Person(\"john\");\n" + + " insert(p); \n" + + " don(p, Student.class, true);\n" + + " don(p, Worker.class);\n" + + " don(p, Scholar.class);\n" + "end"; KieSession ksession = getSessionFromString(drl); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - FactHandle h = ksession.insert( "trigger" ); + FactHandle h = ksession.insert("trigger"); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(5); + assertThat(ksession.getObjects()).hasSize(5); - ksession.delete( h ); + ksession.delete(h); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { + for (Object o : ksession.getObjects()) { // lose the string and the Student proxy - LOGGER.debug( o.toString() ); + LOGGER.debug(o.toString()); } - assertThat(ksession.getObjects().size()).isEqualTo(3); + assertThat(ksession.getObjects()).hasSize(3); } @@ -3723,15 +3517,15 @@ public static class TraitableFoo { private String id; - public TraitableFoo( String id, int x, Object k ) { - setId( id ); + public TraitableFoo(String id, int x, Object k) { + setId(id); } public String getId() { return id; } - public void setId( String id ) { + public void setId(String id) { this.id = id; } } @@ -3740,14 +3534,14 @@ public void setId( String id ) { public static class XYZ extends TraitableFoo { public XYZ() { - super( null, 0, null ); + super(null, 0, null); } } @Test - public void testTraitDonLegacyClassWithoutEmptyConstructor( ) { + public void testTraitDonLegacyClassWithoutEmptyConstructor() { String drl = "package org.drools.compiler.trait.test;\n" + "\n" + "import " + TraitableFoo.class.getCanonicalName() + ";" + @@ -3760,30 +3554,30 @@ public void testTraitDonLegacyClassWithoutEmptyConstructor( ) { "rule \"Don\"\n" + "no-loop \n" + "when\n" + - " $f : TraitableFoo( )\n" + + " $f : TraitableFoo()\n" + "then\n" + - " Bar b = don( $f, Bar.class );\n" + + " Bar b = don($f, Bar.class);\n" + "end"; KieSession ksession = getSessionFromString(drl); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); - ksession.addEventListener( new DebugAgendaEventListener( ) ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); + ksession.addEventListener(new DebugAgendaEventListener()); - ksession.insert( new TraitableFoo( "xx", 0, null ) ); + ksession.insert(new TraitableFoo("xx", 0, null)); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(ksession.getObjects().size()).isEqualTo(2); + assertThat(ksession.getObjects()).hasSize(2); } @Test - public void testdeleteCoreObjectChained( ) { + public void testdeleteCoreObjectChained() { String source = "package org.drools.test;\n" + "import java.util.List; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -3805,8 +3599,8 @@ public void testdeleteCoreObjectChained( ) { "when\n" + " $s : String() \n" + "then\n" + - " Kore k = new Kore( 44 );\n" + - " insertLogical( k ); \n" + + " Kore k = new Kore(44);\n" + + " insertLogical(k); \n" + "end\n" + "" + "" + @@ -3815,7 +3609,7 @@ public void testdeleteCoreObjectChained( ) { "when\n" + " $x : Kore() \n" + "then \n" + - " don( $x, A.class ); \n" + + " don($x, A.class); \n" + "end\n" + "" + "" + @@ -3824,32 +3618,32 @@ public void testdeleteCoreObjectChained( ) { "when \n" + " $x : String() \n" + "then \n" + - " delete( $x ); \n" + + " delete($x); \n" + "end \n" + "\n"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); List list = new ArrayList(); - ks.setGlobal( "list", list ); + ks.setGlobal("list", list); - ks.insert( "go" ); + ks.insert("go"); ks.fireAllRules(); - for ( Object o : ks.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ks.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(ks.getObjects().size()).isEqualTo(0); + assertThat(ks.getObjects()).isEmpty(); ks.dispose(); } @Test - public void testUpdateLegacyClass( ) { + public void testUpdateLegacyClass() { String source = "package org.drools.text;\n" + "\n" + "global java.util.List list;\n" + @@ -3866,40 +3660,40 @@ public void testUpdateLegacyClass( ) { "rule \"Init\"\n" + "salience 10 \n" + "when\n" + - " $p : Person( this not isA Student )\n" + + " $p : Person(this not isA Student)\n" + "then\n" + - " don( $p, Student.class );\n" + + " don($p, Student.class);\n" + "end\n" + "\n" + "rule \"Go\"\n" + "when\n" + - " $s : String( this == \"X\" )\n" + + " $s : String(this == \"X\")\n" + " $p : Person()\n" + "then\n" + - " delete( $s ); \n" + - " modify( $p ) { setName( $s ); }\n" + + " delete($s); \n" + + " modify($p) { setName($s); }\n" + "end\n" + "\n" + "rule \"Mod\"\n" + "when\n" + - " Student( name == \"X\" )\n" + + " Student(name == \"X\")\n" + "then\n" + - " list.add( 0 );\n" + + " list.add(0);\n" + "end"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); - ks.insert( new Person( "john", 32 ) ); - ks.insert( "X" ); + ks.insert(new Person("john", 32)); + ks.insert("X"); ks.fireAllRules(); - assertThat(list.contains(0)).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains(0); ks.dispose(); } @@ -3924,7 +3718,7 @@ public void testSoftPropertyClash() { " fld2 : int = 4 \n" + " fld3 : double = 4.0 \n" + " fld4 : String = \"hello\" \n" + - " fldZ : String = \"hello\" @Alias( \"fld5\" )\n" + + " fldZ : String = \"hello\" @Alias(\"fld5\")\n" + "end\n" + "declare trait Worker\n" + " @propertyReactive \n" + @@ -3932,11 +3726,11 @@ public void testSoftPropertyClash() { " fld2 : String = \"b\" \n " + " fld3 : int = 11 \n " + " fld4 : Class = Object.class \n " + - " fldY : int = 42 @Alias( \"fld5\" )\n" + + " fldY : int = 42 @Alias(\"fld5\")\n" + "end\n" + "" + "rule \"Init\" when then \n" + - " insert( new Person() ); \n" + + " insert(new Person()); \n" + "end \n" + "" + "\n" + @@ -3944,45 +3738,45 @@ public void testSoftPropertyClash() { "when\n" + " $p : Person() \n" + "then\n" + - " Student $s = (Student) don( $p, Student.class );\n" + - " modify ( $s ) { setId( \"xyz\" ); } " + + " Student $s = (Student) don($p, Student.class);\n" + + " modify ($s) { setId(\"xyz\"); } " + " " + - " Worker $w = don( $p, Worker.class );\n" + - " modify ( $w ) { setId( 99 ); } " + + " Worker $w = don($p, Worker.class);\n" + + " modify ($w) { setId(99); } " + "end\n" + "\n" + "rule \"Stud\"\n" + "when\n" + - " $s : Student( $sid : id == \"xyz\", $f2 : fld2, $f3 : fld3, $f4 : fld4, $f5 : fldZ )\n" + + " $s : Student($sid : id == \"xyz\", $f2 : fld2, $f3 : fld3, $f4 : fld4, $f5 : fldZ)\n" + "then\n" + - " list.add( $sid ); \n" + - " list.add( $f2 ); \n" + - " list.add( $f3 ); \n" + - " list.add( $f4 ); \n" + - " list.add( $f5 ); \n" + + " list.add($sid); \n" + + " list.add($f2); \n" + + " list.add($f3); \n" + + " list.add($f4); \n" + + " list.add($f5); \n" + "end\n" + "\n" + "rule \"Mod\"\n" + "when\n" + - " $w : Worker( $wid : id == 99, $f2 : fld2, $f3 : fld3, $f4 : fld4, $f5 : fldY )\n" + + " $w : Worker($wid : id == 99, $f2 : fld2, $f3 : fld3, $f4 : fld4, $f5 : fldY)\n" + "then\n" + - " list.add( $wid ); \n" + - " list.add( $f2 ); \n" + - " list.add( $f3 ); \n" + - " list.add( $f4 ); \n" + - " list.add( $f5 ); \n" + + " list.add($wid); \n" + + " list.add($f2); \n" + + " list.add($f3); \n" + + " list.add($f4); \n" + + " list.add($f5); \n" + "end"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.size()).isEqualTo(5); - assertThat(list).isEqualTo(Arrays.asList(99, "b", 11, Object.class, 42)); + assertThat(list).hasSize(5); + assertThat(list).containsExactly(99, "b", 11, Object.class, 42); ks.dispose(); } @@ -4035,40 +3829,40 @@ public void testMultipleModifications() { "rule \"init\"\n" + "when\n" + "then\n" + - " insert( new Person(\"1234\",\"IR\",true,true) );\n" + + " insert(new Person(\"1234\",\"IR\",true,true));\n" + "end\n" + "\n" + "rule \"check for being student\"\n" + "when\n" + - " $p : Person( $ssn : ssn, $pob : pob, isStudent == true )\n" + + " $p : Person($ssn : ssn, $pob : pob, isStudent == true)\n" + "then\n" + - " Student st = (Student) don( $p , Student.class );\n" + - " modify( st ){\n" + - " setStudyingCountry( \"US\" );\n" + + " Student st = (Student) don($p , Student.class);\n" + + " modify(st){\n" + + " setStudyingCountry(\"US\");\n" + " }\n" + "end\n" + "\n" + "rule \"check for IR\"\n" + "when\n" + - " $p : Person( pob == \"IR\" )\n" + + " $p : Person(pob == \"IR\")\n" + "then\n" + - " don( $p , IRCitizen.class );\n" + + " don($p , IRCitizen.class);\n" + "end\n" + "\n" + "rule \"check for being US citizen\"\n" + "when\n" + - " $s : Student( studyingCountry == \"US\" )\n" + + " $s : Student(studyingCountry == \"US\")\n" + "then\n" + - " don( $s , USCitizen.class );\n" + + " don($s , USCitizen.class);\n" + "end\n" + "\n" + "rule \"check for being worker\"\n" + "when\n" + - " $p : Student( hasAssistantship == true, $sc : studyingCountry )\n" + + " $p : Student(hasAssistantship == true, $sc : studyingCountry)\n" + "then\n" + - " Worker wr = (Worker) don( $p , Worker.class );\n" + - " modify( wr ){\n" + - " setWorkingCountry( $sc );\n" + + " Worker wr = (Worker) don($p , Worker.class);\n" + + " modify(wr){\n" + + " setWorkingCountry($sc);\n" + " }\n" + "\n" + "end\n" + @@ -4076,27 +3870,26 @@ public void testMultipleModifications() { "rule \"Join Full\"\n" + "salience -1\n" + "when\n" + - " Student( ) // $sc := studyingCountry )\n" + - " USCitizen( )\n" + - " IRCitizen( ) // $pob := pob )\n" + - " Worker( ) // pob == $pob , workingCountry == $sc )\n" + + " Student() // $sc := studyingCountry)\n" + + " USCitizen()\n" + + " IRCitizen() // $pob := pob)\n" + + " Worker() // pob == $pob , workingCountry == $sc)\n" + "then\n" + - " list.add( 1 ); " + + " list.add(1); " + "end\n" + "\n" + "\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); - HashMap map; ks.fireAllRules(); - assertThat(list.contains(1)).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).contains(1); + assertThat(list).hasSize(1); ks.dispose(); @@ -4122,71 +3915,51 @@ public void testPropagation() { "declare trait I extends E,H @propertyReactive end\n" + "declare trait J extends I @propertyReactive end\n" + "" + - "rule Init when then X x = new X(); insert( x ); don( x, F.class); end \n"+ - "rule Go when String( this == \"go\" ) $x : X() then don( $x, H.class); end \n" + - "rule Go2 when String( this == \"go2\" ) $x : X() then don( $x, D.class); end \n" + + "rule Init when then X x = new X(); insert(x); don(x, F.class); end \n"+ + "rule Go when String(this == \"go\") $x : X() then don($x, H.class); end \n" + + "rule Go2 when String(this == \"go2\") $x : X() then don($x, D.class); end \n" + ""; - for ( int j = 'A'; j <= 'J'; j ++ ) { + for (int j = 'A'; j <= 'J'; j ++) { String x = "" + (char) j; - drl += "rule \"Log " + x + "\" when " + x + "() then list.add( \"" + x + "\" ); end \n"; + drl += "rule \"Log " + x + "\" when " + x + "() then list.add(\"" + x + "\"); end \n"; - drl += "rule \"Log II" + x + "\" salience -1 when " + x + "( "; + drl += "rule \"Log II" + x + "\" salience -1 when " + x + "("; drl += "this isA H"; - drl += " ) then list.add( \"H" + x + "\" ); end \n"; + drl += ") then list.add(\"H" + x + "\"); end \n"; } - KieSession ks = new KieHelper().addContent( drl, ResourceType.DRL ).build().newKieSession(); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession(); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.contains("A")).isTrue(); - assertThat(list.contains("B")).isTrue(); - assertThat(list.contains("C")).isTrue(); - assertThat(list.contains("E")).isTrue(); - assertThat(list.contains("F")).isTrue(); - assertThat(list.size()).isEqualTo(5); + assertThat(list).hasSize(5); + assertThat(list).contains("A", "B", "C", "E", "F"); list.clear(); - LOGGER.debug( "---------------------------------------" ); + LOGGER.debug("---------------------------------------"); - ks.insert( "go" ); + ks.insert("go"); ks.fireAllRules(); - assertThat(list.contains("H")).isTrue(); - assertThat(list.contains("G")).isTrue(); - assertThat(list.contains("HA")).isTrue(); - assertThat(list.contains("HB")).isTrue(); - assertThat(list.contains("HC")).isTrue(); - assertThat(list.contains("HE")).isTrue(); - assertThat(list.contains("HF")).isTrue(); - assertThat(list.contains("HG")).isTrue(); - assertThat(list.contains("HH")).isTrue(); - LOGGER.debug( list.toString() ); - assertThat(list.size()).isEqualTo(9); + assertThat(list).hasSize(9); + assertThat(list).contains("H", "G", "HA", "HB", "HC", "HE", "HF", "HG", "HH"); + LOGGER.debug(list.toString()); + list.clear(); - LOGGER.debug( "---------------------------------------" ); + LOGGER.debug("---------------------------------------"); - ks.insert( "go2" ); + ks.insert("go2"); ks.fireAllRules(); - assertThat(list.contains("D")).isTrue(); - assertThat(list.contains("HA")).isTrue(); - assertThat(list.contains("HB")).isTrue(); - assertThat(list.contains("HC")).isTrue(); - assertThat(list.contains("HE")).isTrue(); - assertThat(list.contains("HF")).isTrue(); - assertThat(list.contains("HG")).isTrue(); - assertThat(list.contains("HH")).isTrue(); - assertThat(list.contains("HH")).isTrue(); - assertThat(list.contains("HD")).isTrue(); - assertThat(list.size()).isEqualTo(9); + assertThat(list).hasSize(9); + assertThat(list).contains("D", "HA", "HB", "HC", "HE", "HF", "HG", "HH", "HH", "HD"); ks.dispose(); @@ -4205,25 +3978,25 @@ public void testParentBlockers() { "declare trait B @propertyReactive end\n" + "declare trait C extends A, B @propertyReactive end \n" + "" + - "rule Init when then X x = new X(); insert( x ); don( x, A.class); don( x, B.class); end \n"+ - "rule Go when String( this == \"go\" ) $x : X() then don( $x, C.class); end \n" + - "rule Go2 when String( this == \"go2\" ) $x : C() then end \n"; + "rule Init when then X x = new X(); insert(x); don(x, A.class); don(x, B.class); end \n"+ + "rule Go when String(this == \"go\") $x : X() then don($x, C.class); end \n" + + "rule Go2 when String(this == \"go2\") $x : C() then end \n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - ks.insert( "go" ); + ks.insert("go"); ks.fireAllRules(); - ks.insert( "go2" ); + ks.insert("go2"); ks.fireAllRules(); - LOGGER.debug( "---------------------------------------" ); + LOGGER.debug("---------------------------------------"); ks.dispose(); @@ -4241,39 +4014,39 @@ public void testTraitLogicalTMS() { "declare trait A @propertyReactive end\n" + "declare trait B @propertyReactive end\n" + "" + - "rule Init when then X x = new X(); insert( x ); end \n"+ - "rule Go when String( this == \"go\" ) $x : X() then don( $x, A.class, true ); don( $x, B.class, true ); end \n" + - "rule Go2 when String( this == \"go2\" ) $x : X() then don( $x, A.class ); end \n" + - "rule Go3 when String( this == \"go3\" ) $x : A() not B() then list.add( 100 ); end \n" + + "rule Init when then X x = new X(); insert(x); end \n"+ + "rule Go when String(this == \"go\") $x : X() then don($x, A.class, true); don($x, B.class, true); end \n" + + "rule Go2 when String(this == \"go2\") $x : X() then don($x, A.class); end \n" + + "rule Go3 when String(this == \"go3\") $x : A() not B() then list.add(100); end \n" + ""; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - FactHandle handle = ks.insert( "go" ); + FactHandle handle = ks.insert("go"); ks.fireAllRules(); - ks.insert( "go2" ); + ks.insert("go2"); ks.fireAllRules(); - ks.delete( handle ); + ks.delete(handle); ks.fireAllRules(); - LOGGER.debug( "---------------------------------------" ); + LOGGER.debug("---------------------------------------"); - for ( Object o : ks.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ks.getObjects()) { + LOGGER.debug(o.toString()); } - ks.insert( "go3" ); + ks.insert("go3"); ks.fireAllRules(); - assertThat(list).isEqualTo(List.of(100)); + assertThat(list).containsExactly(100); ks.dispose(); } @@ -4294,7 +4067,7 @@ public void testTraitNoType() { "\n" + "\n" + "declare Parent\n" + - "@Traitable( logical = true )" + + "@Traitable(logical = true)" + "@propertyReactive\n" + "end\n" + "\n" + @@ -4310,15 +4083,15 @@ public void testTraitNoType() { "then\n" + " Parent p = new Parent();" + " insert(p);\n" + - " ChildTrait ct = don( p , ChildTrait.class );\n" + + " ChildTrait ct = don(p , ChildTrait.class);\n" + " list.add(\"correct1\");\n" + "end\n" + "\n" + "rule \"check\"\n" + "no-loop\n" + "when\n" + - " $c : ChildTrait($n : naam == \"kudak\", id == 1020 )\n" + - " $p : Thing( core == $c.core, fields[\"naam\"] == $n )\n" + + " $c : ChildTrait($n : naam == \"kudak\", id == 1020)\n" + + " $p : Thing(core == $c.core, fields[\"naam\"] == $n)\n" + "then\n" + " list.add(\"correct2\");\n" + "end"; @@ -4326,12 +4099,11 @@ public void testTraitNoType() { KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.contains("correct1")).isTrue(); - assertThat(list.contains("correct2")).isTrue(); + assertThat(list).contains("correct1", "correct2"); } @@ -4354,37 +4126,37 @@ public void testTraitdeleteOrder() { "when \n" + " $e : Entity() \n" + "then\n" + - " don( $e, A.class ); \n" + - " don( $e, C.class ); \n" + - " don( $e, B.class ); \n" + + " don($e, A.class); \n" + + " don($e, C.class); \n" + + " don($e, B.class); \n" + "end\n" + ""; KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - FactHandle handle = ksession.insert( new Entity( ) ); + FactHandle handle = ksession.insert(new Entity()); ksession.fireAllRules(); - final ArrayList list = new ArrayList(); + final List list = new ArrayList<>(); - ksession.addEventListener( new RuleRuntimeEventListener() { - public void objectInserted( org.kie.api.event.rule.ObjectInsertedEvent objectInsertedEvent ) { } - public void objectUpdated( org.kie.api.event.rule.ObjectUpdatedEvent objectUpdatedEvent ) { } - public void objectDeleted( org.kie.api.event.rule.ObjectDeletedEvent objectRetractedEvent ) { + ksession.addEventListener(new RuleRuntimeEventListener() { + public void objectInserted(org.kie.api.event.rule.ObjectInsertedEvent objectInsertedEvent) { } + public void objectUpdated(org.kie.api.event.rule.ObjectUpdatedEvent objectUpdatedEvent) { } + public void objectDeleted(org.kie.api.event.rule.ObjectDeletedEvent objectRetractedEvent) { Object o = objectRetractedEvent.getOldObject(); - if ( o instanceof TraitProxyImpl) { - String traitName = ( (TraitProxyImpl) o )._getTraitName(); - list.add( traitName.substring( traitName.lastIndexOf( "." ) + 1 ) ); + if (o instanceof TraitProxyImpl) { + String traitName = ((TraitProxyImpl) o)._getTraitName(); + list.add(traitName.substring(traitName.lastIndexOf(".") + 1)); } } - } ); + }); - ksession.delete( handle ); + ksession.delete(handle); ksession.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList("B", "C", "A")); + LOGGER.debug(list.toString()); + assertThat(list).containsExactly("B", "C", "A"); } @@ -4399,7 +4171,7 @@ public void testTraitWithManySoftFields() { "\n" + "declare trait Tx \n"; - for ( int j = 0; j < 150; j ++ ) { + for (int j = 0; j < 150; j ++) { drl += " fld" + j + " : String \n"; } @@ -4411,17 +4183,17 @@ public void testTraitWithManySoftFields() { "rule \"don\"\n" + "when \n" + "then\n" + - " don( new TBean(), Tx.class ); \n" + + " don(new TBean(), Tx.class); \n" + "end\n" + "" + ""; KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(2); + assertThat(ksession.getObjects()).hasSize(2); } @@ -4446,21 +4218,21 @@ public int getdeletes() { } @Override - public void objectInserted( org.kie.api.event.rule.ObjectInsertedEvent event ) { - if ( ! ( event.getObject() instanceof String ) ) { + public void objectInserted(org.kie.api.event.rule.ObjectInsertedEvent event) { + if (! (event.getObject() instanceof String)) { inserts++; } } @Override - public void objectUpdated( org.kie.api.event.rule.ObjectUpdatedEvent event ) { - if ( ! ( event.getObject() instanceof String ) ) { + public void objectUpdated(org.kie.api.event.rule.ObjectUpdatedEvent event) { + if (! (event.getObject() instanceof String)) { updates++; } } - public void objectDeleted( org.kie.api.event.rule.ObjectDeletedEvent objectdeleteedEvent ) { - if ( ! ( objectdeleteedEvent.getOldObject() instanceof String ) ) { + public void objectDeleted(org.kie.api.event.rule.ObjectDeletedEvent objectdeleteedEvent) { + if (! (objectdeleteedEvent.getOldObject() instanceof String)) { deletes++; } } @@ -4497,54 +4269,54 @@ public void testDonManyTraitsAtOnce() { "when \n" + "then\n" + " TBean t = new TBean(); \n" + - " don( t, A.class ); \n" + - " don( t, B.class ); \n" + + " don(t, A.class); \n" + + " don(t, B.class); \n" + "end\n" + "" + "rule \"Don 2\" " + "when \n" + - " $s : String( this == \"go\" ) \n" + + " $s : String(this == \"go\") \n" + " $t : TBean() \n" + "then \n" + - " list.add( 0 ); \n" + - " don( $t, Arrays.asList( C.class, D.class, E.class, F.class ), true ); \n" + + " list.add(0); \n" + + " don($t, Arrays.asList(C.class, D.class, E.class, F.class), true); \n" + "end \n" + "" + "rule Clear \n" + "when \n" + - " $s : String( this == \"undo\" ) \n" + + " $s : String(this == \"undo\") \n" + " $t : TBean() \n" + "then \n" + - " delete( $s ); \n" + - " delete( $t ); \n" + + " delete($s); \n" + + " delete($t); \n" + "end \n" + "" + "rule C \n" + "when\n" + - " B( this isA C ) \n" + + " B(this isA C) \n" + "then \n" + - " list.add( 1 ); \n" + + " list.add(1); \n" + "end \n" + "rule D \n" + "when\n" + - " D( this isA A, this isA C ) \n" + + " D(this isA A, this isA C) \n" + "then \n" + - " list.add( 2 ); \n" + + " list.add(2); \n" + "end \n"+ "rule E \n" + "when\n" + - " D( this isA A, this isA E ) \n" + + " D(this isA A, this isA E) \n" + "then \n" + - " list.add( 3 ); \n" + + " list.add(3); \n" + "end \n"; KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); - ArrayList list = new ArrayList(); - ksession.setGlobal( "list", list ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); CountingWorkingMemoryEventListener cwm = new CountingWorkingMemoryEventListener(); - ksession.addEventListener( cwm ); + ksession.addEventListener(cwm); ksession.fireAllRules(); @@ -4555,7 +4327,7 @@ public void testDonManyTraitsAtOnce() { assertThat(cwm.getUpdates()).isEqualTo(1); cwm.reset(); - FactHandle handle = ksession.insert( "go" ); + FactHandle handle = ksession.insert("go"); ksession.fireAllRules(); // don C, D, E, F at once : 4 inserts @@ -4565,7 +4337,7 @@ public void testDonManyTraitsAtOnce() { assertThat(cwm.getUpdates()).isEqualTo(3); cwm.reset(); - ksession.delete( handle ); + ksession.delete(handle); ksession.fireAllRules(); // logically asserted C, D, E, F are deleteed @@ -4575,11 +4347,11 @@ public void testDonManyTraitsAtOnce() { assertThat(cwm.getUpdates()).isEqualTo(0); cwm.reset(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - ksession.insert( "undo" ); + ksession.insert("undo"); ksession.fireAllRules(); // deleteing the core bean @@ -4590,8 +4362,8 @@ public void testDonManyTraitsAtOnce() { cwm.reset(); - assertThat(list.size()).isEqualTo(4); - assertThat(list.containsAll(Arrays.asList(0, 1, 2, 3))).isTrue(); + assertThat(list).hasSize(4); + assertThat(list).contains(0, 1, 2, 3); } @Test @@ -4614,28 +4386,28 @@ public void testDonManyTraitsAtOnce2() { "when \n" + "then\n" + " TBean t = new TBean(); \n" + - " don( t, A.class ); \n" + - " don( t, B.class ); \n" + + " don(t, A.class); \n" + + " don(t, B.class); \n" + "end\n" + "" + "rule \"Test Don A,B\" " + "when \n" + " A(this isA B) \n" + "then \n" + - " list.add( 0 ); \n" + + " list.add(0); \n" + "end \n"; KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); - ArrayList list = new ArrayList(); - ksession.setGlobal( "list", list ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); CountingWorkingMemoryEventListener cwm = new CountingWorkingMemoryEventListener(); - ksession.addEventListener( cwm ); + ksession.addEventListener(cwm); ksession.fireAllRules(); - assertThat(list).isEqualTo(List.of(0)); + assertThat(list).containsExactly(0); assertThat(cwm.getdeletes()).isEqualTo(0); assertThat(cwm.getInserts()).isEqualTo(3); @@ -4693,14 +4465,14 @@ public void testMultithreadingTraits() throws InterruptedException { " no-loop true\n" + " when\n" + " $p : Item ()\n" + - " not ItemStyle ( id == $p.id )\n" + + " not ItemStyle (id == $p.id)\n" + " then\n" + " don($p, ItemStyle.class);\n" + "end\n" + "rule \"Item Style - Adjustable\"" + " no-loop true" + " when" + - " $style : ItemStyle ( !adjustable )" + + " $style : ItemStyle (!adjustable)" + " Item (" + " id == $style.id " + " )" + @@ -4710,14 +4482,14 @@ public void testMultithreadingTraits() throws InterruptedException { " };" + "end"; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); // might need to tweak these numbers. often works with 7-10,100,60, but often fails 15-20,100,60 int MAX_THREADS = 20; int MAX_REPETITIONS = 100; int MAX_WAIT_SECONDS = 60; - final ExecutorService executorService = Executors.newFixedThreadPool( MAX_THREADS ); + final ExecutorService executorService = Executors.newFixedThreadPool(MAX_THREADS); try { for (int threadIndex = 0; threadIndex < MAX_THREADS; threadIndex++) { executorService.execute(new TraitRulesThread(threadIndex, MAX_REPETITIONS, kbase.newKieSession())); @@ -4727,7 +4499,7 @@ public void testMultithreadingTraits() throws InterruptedException { executorService.awaitTermination(MAX_WAIT_SECONDS, TimeUnit.SECONDS); final List queuedTasks = executorService.shutdownNow(); - assertThat(queuedTasks.size()).isEqualTo(0); + assertThat(queuedTasks).isEmpty(); assertThat(executorService.isTerminated()).isEqualTo(true); } } @@ -4747,7 +4519,7 @@ public void testShedOneLastTrait() throws InterruptedException { "rule \"Don ItemStyle\"\n" + " when\n" + " then\n" + - " don( new Core(), Mask.class );\n" + + " don(new Core(), Mask.class);\n" + "end\n" + "" + "rule \"React\" \n" + @@ -4755,34 +4527,34 @@ public void testShedOneLastTrait() throws InterruptedException { " $s : String() \n" + " $m : Mask() \n" + "then \n" + - " delete( $s ); \n" + - " shed( $m, Mask.class ); \n" + + " delete($s); \n" + + " shed($m, Mask.class); \n" + "end\n" + "" + "rule Log \n" + "when \n" + " $t : Thing() \n" + "then \n" + - " list.add( $t.getClass().getName() ); \n" + + " list.add($t.getClass().getName()); \n" + "end \n"; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); - assertThat(list).isEqualTo(List.of("test.Mask.test.Core_Proxy")); + assertThat(list).hasSize(1); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy"); - knowledgeSession.insert( "shed" ); + knowledgeSession.insert("shed"); knowledgeSession.fireAllRules(); - assertThat(list.size()).isEqualTo(2); - assertThat(list).isEqualTo(Arrays.asList("test.Mask.test.Core_Proxy", "org.drools.base.factmodel.traits.Thing.test.Core_Proxy")); + assertThat(list).hasSize(2); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy", "org.drools.base.factmodel.traits.Thing.test.Core_Proxy"); } @@ -4800,37 +4572,37 @@ public void testShedThingCompletelyThenDonAgain() throws InterruptedException { "" + "rule \"Don ItemStyle\"\n" + " when\n" + - " $s : String( this == \"don1\" ) \n" + + " $s : String(this == \"don1\") \n" + " then\n" + - " delete( $s ); \n" + - " don( new Core(), Mask.class );\n" + + " delete($s); \n" + + " don(new Core(), Mask.class);\n" + "end\n" + "" + "rule \"Clear\" \n" + " when \n" + - " $s : String( this == \"shed1\" ) \n" + + " $s : String(this == \"shed1\") \n" + " $m : Mask() \n" + "then \n" + - " delete( $s ); \n" + - " shed( $m, Thing.class ); \n" + + " delete($s); \n" + + " shed($m, Thing.class); \n" + "end\n" + "" + "rule \"Add\" \n" + " when \n" + - " $s : String( this == \"don2\" ) \n" + + " $s : String(this == \"don2\") \n" + " $c : Core() \n" + "then \n" + - " delete( $s ); \n" + - " don( $c, Mask2.class ); \n" + + " delete($s); \n" + + " don($c, Mask2.class); \n" + "end\n" + "" + "rule \"Clear Again\" \n" + " when \n" + - " $s : String( this == \"shed2\" ) \n" + + " $s : String(this == \"shed2\") \n" + " $m : Mask2() \n" + "then \n" + - " delete( $s ); \n" + - " shed( $m, Mask2.class ); \n" + + " delete($s); \n" + + " shed($m, Mask2.class); \n" + "end\n" + "" + "" + @@ -4838,40 +4610,40 @@ public void testShedThingCompletelyThenDonAgain() throws InterruptedException { "when \n" + " $t : Thing() \n" + "then \n" + - " list.add( $t.getClass().getName() ); \n" + + " list.add($t.getClass().getName()); \n" + "end \n"; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); - knowledgeSession.insert( "don1" ); + knowledgeSession.insert("don1"); knowledgeSession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); - assertThat(list).isEqualTo(List.of("test.Mask.test.Core_Proxy")); + assertThat(list).hasSize(1); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy"); - knowledgeSession.insert( "shed1" ); + knowledgeSession.insert("shed1"); knowledgeSession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); - assertThat(list).isEqualTo(List.of("test.Mask.test.Core_Proxy")); + assertThat(list).hasSize(1); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy"); - knowledgeSession.insert( "don2" ); + knowledgeSession.insert("don2"); knowledgeSession.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list.size()).isEqualTo(2); - assertThat(list).isEqualTo(Arrays.asList("test.Mask.test.Core_Proxy", "test.Mask2.test.Core_Proxy")); + LOGGER.debug(list.toString()); + assertThat(list).hasSize(2); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy", "test.Mask2.test.Core_Proxy"); - knowledgeSession.insert( "shed2" ); + knowledgeSession.insert("shed2"); knowledgeSession.fireAllRules(); - assertThat(list.size()).isEqualTo(3); - assertThat(list).isEqualTo(Arrays.asList("test.Mask.test.Core_Proxy", "test.Mask2.test.Core_Proxy", "org.drools.base.factmodel.traits.Thing.test.Core_Proxy")); + assertThat(list).hasSize(3); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy", "test.Mask2.test.Core_Proxy", "org.drools.base.factmodel.traits.Thing.test.Core_Proxy"); } @@ -4889,23 +4661,23 @@ public void testTraitImplicitInsertionExceptionOnNonTraitable() throws Interrupt "rule \"Don ItemStyle\"\n" + " when\n" + " then\n" + - " don( new Core(), Mask.class );\n" + + " don(new Core(), Mask.class);\n" + "end\n" + "" + ""; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); ArrayList list = new ArrayList(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); try { knowledgeSession.fireAllRules(); - fail( "Core is not declared @Traitable, this test should have thrown an exception" ); - } catch ( Exception csq ) { - assertThat(csq.getCause() instanceof IllegalStateException).isTrue(); + fail("Core is not declared @Traitable, this test should have thrown an exception"); + } catch (Exception csq) { + assertThat(csq.getCause()).isInstanceOf(IllegalStateException.class); } } @@ -4914,7 +4686,7 @@ public void testTraitImplicitInsertionExceptionOnNonTraitable() throws Interrupt @Trait public static interface SomeTrait extends Thing { public String getFoo(); - public void setFoo( String foo ); + public void setFoo(String foo); } @Test @@ -4929,19 +4701,19 @@ public void testTraitLegacyTraitableWithLegacyTrait() { "rule \"Don ItemStyle\"\n" + " when\n" + " then\n" + - " don( new StudentImpl(), SomeTrait.class );\n" + + " don(new StudentImpl(), SomeTrait.class);\n" + "end\n"; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); ArrayList list = new ArrayList(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(knowledgeSession.getObjects().size()).isEqualTo(2); + assertThat(knowledgeSession.getObjects()).hasSize(2); } @Test @@ -4958,28 +4730,28 @@ public void testIsALegacyTrait() { "rule \"Don ItemStyle\"\n" + " when\n" + " then\n" + - " insert( new StudentImpl() );\n" + - " don( new Entity(), IStudent.class );\n" + + " insert(new StudentImpl());\n" + + " don(new Entity(), IStudent.class);\n" + "end\n" + "" + "rule Check " + " when " + " $s : StudentImpl() " + - " $e : Entity( this isA $s ) " + + " $e : Entity(this isA $s) " + " then " + - " list.add( 1 ); " + + " list.add(1); " + " end "; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list).isEqualTo(List.of(1)); + assertThat(list).containsExactly(1); } @Category(ReviseTraitTestWithPRAlwaysCategory.class) @@ -5001,43 +4773,43 @@ public void testClassLiteralsWithOr() { "when " + "then " + " Foo f = new Foo(); " + - " insert( f ); " + + " insert(f); " + "end " + "rule One " + "when " + - " $f : Foo( this not isA A ) " + + " $f : Foo(this not isA A) " + "then " + - " don( $f, A.class ); " + + " don($f, A.class); " + "end " + "rule Two " + "when " + - " $f : Foo( this not isA B ) " + + " $f : Foo(this not isA B) " + "then " + - " don( $f, B.class ); " + + " don($f, B.class); " + "end " + "rule Check " + "when " + - " $f : Foo( this isA B || this isA A ) " + + " $f : Foo(this isA B || this isA A) " + "then " + - " list.add( 1 ); " + + " list.add(1); " + "end " + ""; - KieBase kbase = new KieHelper(PropertySpecificOption.ALLOWED).addContent( drl, ResourceType.DRL ).build(); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + KieBase kbase = new KieHelper(PropertySpecificOption.ALLOWED).addContent(drl, ResourceType.DRL).build(); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); ksession.fireAllRules(); - assertThat(list).isEqualTo(List.of(1)); + assertThat(list).containsExactly(1); } @@ -5067,41 +4839,40 @@ public void testIsASwappedArg() { "rule Init " + "when " + "then " + - " Foo f = new Foo( new StudentImpl() ); " + - " don( f, IStudent.class ); " + + " Foo f = new Foo(new StudentImpl()); " + + " don(f, IStudent.class); " + "end " + "rule Match1 " + "when " + - " $f : Foo( $x : object ) " + - " $p : StudentImpl( this isA $f ) from $x " + + " $f : Foo($x : object) " + + " $p : StudentImpl(this isA $f) from $x " + "then " + - " list.add( 1 ); " + + " list.add(1); " + "end " + "rule Match2 " + "when " + - " $f : Foo( $x : object ) " + - " $p : StudentImpl( $f isA this ) from $x " + + " $f : Foo($x : object) " + + " $p : StudentImpl($f isA this) from $x " + "then " + - " list.add( 2 ); " + + " list.add(2); " + "end " + ""; - KieBase kbase = loadKnowledgeBaseFromString( drl ); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + KieBase kbase = loadKnowledgeBaseFromString(drl); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(2); - assertThat(list.contains(1)).isTrue(); - assertThat(list.contains(2)).isTrue(); + assertThat(list).hasSize(2); + assertThat(list).contains(1, 2); } @@ -5126,23 +4897,23 @@ public void testHierarchyEncodeOnPackageMerge() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) knowledgeBase); KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kb.add( new ByteArrayResource( drl0.getBytes() ), ResourceType.DRL ); + kb.add(new ByteArrayResource(drl0.getBytes()), ResourceType.DRL); assertThat(kb.hasErrors()).isFalse(); - knowledgeBase.addPackages( kb.getKnowledgePackages() ); + knowledgeBase.addPackages(kb.getKnowledgePackages()); KnowledgeBuilder kb2 = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kb2.add( new ByteArrayResource( drl1.getBytes() ), ResourceType.DRL ); - LOGGER.debug( kb2.getErrors().toString() ); + kb2.add(new ByteArrayResource(drl1.getBytes()), ResourceType.DRL); + LOGGER.debug(kb2.getErrors().toString()); assertThat(kb2.hasErrors()).isFalse(); - knowledgeBase.addPackages( kb2.getKnowledgePackages() ); + knowledgeBase.addPackages(kb2.getKnowledgePackages()); HierarchyEncoder hier = ((TraitRuntimeComponentFactory) RuntimeComponentFactory.get()).getTraitRegistry(knowledgeBase).getHierarchy(); - BitSet b = (BitSet) hier.getCode( "org.drools.test.B" ).clone(); - BitSet c = (BitSet) hier.getCode( "org.drools.test.C" ).clone(); + BitSet b = (BitSet) hier.getCode("org.drools.test.B").clone(); + BitSet c = (BitSet) hier.getCode("org.drools.test.C").clone(); - c.and( b ); + c.and(b); assertThat(c).isEqualTo(b); } @@ -5168,9 +4939,9 @@ public void testDonThenReinsert() throws InterruptedException { "" + "rule 'Don ItemStyle' " + " when\n" + - " $e : TBean( ) " + + " $e : TBean() " + " then " + - " don( $e, Mask.class );\n" + + " don($e, Mask.class);\n" + "end\n" + "" + "rule \"React\" \n" + @@ -5183,29 +4954,29 @@ public void testDonThenReinsert() throws InterruptedException { KieBase kbase = getKieBaseFromString(s1, EqualityBehaviorOption.IDENTITY); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); ArrayList list = new ArrayList(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); - TBean e = new TBean( "aaa" ); + knowledgeSession.setGlobal("list", list); + TBean e = new TBean("aaa"); int n = knowledgeSession.fireAllRules(); assertThat(n).isEqualTo(1); - knowledgeSession.insert( e ); + knowledgeSession.insert(e); n = knowledgeSession.fireAllRules(); assertThat(n).isEqualTo(2); - knowledgeSession.insert( e ); + knowledgeSession.insert(e); n = knowledgeSession.fireAllRules(); assertThat(n).isEqualTo(0); - knowledgeSession.delete( knowledgeSession.getFactHandle( e ) ); + knowledgeSession.delete(knowledgeSession.getFactHandle(e)); n = knowledgeSession.fireAllRules(); assertThat(n).isEqualTo(1); - assertThat(knowledgeSession.getObjects().size()).isEqualTo(0); + assertThat(knowledgeSession.getObjects()).isEmpty(); } @@ -5236,30 +5007,30 @@ public void testCastOnTheFly() throws InterruptedException { " dialect 'mvel' " + " when " + " then " + - " Foo o = insert( new Foo( 42 ) ).as( Foo.class ); " + - " list.add( o.getId() ); " + + " Foo o = insert(new Foo(42)).as(Foo.class); " + + " list.add(o.getId()); " + "end " + "rule Don " + " when " + " $f : Foo() " + " then " + - " Lower l = don( $f, Lower.class ); " + - " Upper u = bolster( $f ).as( Upper.class ); " + - " list.add( u.getId() + 1 ); " + + " Lower l = don($f, Lower.class); " + + " Upper u = bolster($f).as(Upper.class); " + + " list.add(u.getId() + 1); " + " end "; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList(42, 43)); + assertThat(list).containsExactly(42, 43); } @@ -5283,24 +5054,24 @@ public void testDonModify() { "when\n" + "then\n" + " Entity core = new Entity();\n" + - " insert( core );\n" + + " insert(core);\n" + "end\n" + "rule Trait when\n" + - " $core: Entity( )\n" + + " $core: Entity()\n" + "then\n" + - " IPerson x = don( $core, IPerson.class, true );\n" + - " IStudent s = don( $core, IStudent.class, true );\n" + - " Person p = don( $core, Person.class, true );\n" + + " IPerson x = don($core, IPerson.class, true);\n" + + " IStudent s = don($core, IStudent.class, true);\n" + + " Person p = don($core, Person.class, true);\n" + "end\n" + "rule R2 when\n" + - " $p: IPerson( name == null )\n" + + " $p: IPerson(name == null)\n" + "then\n" + "end\n"; - KieBase kbase = getKieBaseFromString( drl ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl); + TraitFactoryImpl.setMode(mode, kbase); KieSession kSession = kbase.newKieSession(); assertThat(kSession.fireAllRules()).isEqualTo(3); @@ -5319,28 +5090,28 @@ public void testAlphaNodeSharing() { "rule Init " + "when " + "then " + - " don( new Entity(), Person.class ); " + + " don(new Entity(), Person.class); " + "end\n" + "rule One when" + - " $core: Entity( this isA Person ) " + + " $core: Entity(this isA Person) " + "then " + "end " + "rule Two when" + - " $core: Entity( this isA Person ) " + + " $core: Entity(this isA Person) " + "then " + "end " + "\n"; - final KieBase kbase = getKieBaseFromString( drl ); - TraitFactoryImpl.setMode(mode, kbase ); + final KieBase kbase = getKieBaseFromString(drl); + TraitFactoryImpl.setMode(mode, kbase); KieSession kSession = kbase.newKieSession(); assertThat(kSession.fireAllRules()).isEqualTo(3); - NamedEntryPoint nep = ( (NamedEntryPoint) kSession.getEntryPoint( EntryPointId.DEFAULT.getEntryPointId() ) ); - ObjectTypeNode otn = nep.getEntryPointNode().getObjectTypeNodes().get( new ClassObjectType( Entity.class ) ); + NamedEntryPoint nep = ((NamedEntryPoint) kSession.getEntryPoint(EntryPointId.DEFAULT.getEntryPointId())); + ObjectTypeNode otn = nep.getEntryPointNode().getObjectTypeNodes().get(new ClassObjectType(Entity.class)); assertThat(otn).isNotNull(); assertThat(otn.getObjectSinkPropagator().getSinks().length).isEqualTo(1); } @@ -5356,45 +5127,45 @@ public void testPartitionWithSiblingsOnDelete() { "declare trait C extends A @propertyReactive end " + "rule Trait when " + - " $core: Entity( ) " + + " $core: Entity() " + "then " + - " don( $core, A.class ); " + - " don( $core, B.class ); " + - " don( $core, C.class ); " + + " don($core, A.class); " + + " don($core, B.class); " + + " don($core, C.class); " + "end " + "rule Shed when " + " $s: String() " + " $core : Entity() " + "then " + - " shed( $core, C.class ); " + + " shed($core, C.class); " + "end " + - "rule RA when A() then list.add( 'A' ); end " + - "rule RB when B() then list.add( 'B' ); end " + - "rule RC when C() then list.add( 'C' ); end " + + "rule RA when A() then list.add('A'); end " + + "rule RB when B() then list.add('B'); end " + + "rule RC when C() then list.add('C'); end " + " "; - KieBase kbase = new KieHelper().addContent( drl, ResourceType.DRL ).build(); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = new KieHelper().addContent(drl, ResourceType.DRL).build(); + TraitFactoryImpl.setMode(mode, kbase); KieSession ksession = kbase.newKieSession(); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); Entity e = new Entity(); - ksession.insert( e ); + ksession.insert(e); ksession.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList('A', 'B', 'C')); + assertThat(list).containsExactly('A', 'B', 'C'); - ksession.insert( "go" ); + ksession.insert("go"); ksession.fireAllRules(); - Set s = checkOTNPartitioning( e, ksession ); - assertThat(s.size()).isEqualTo(2); + Set s = checkOTNPartitioning(e, ksession); + assertThat(s).hasSize(2); - assertThat(list).isEqualTo(Arrays.asList('A', 'B', 'C')); + assertThat(list).containsExactly('A', 'B', 'C'); } @@ -5407,46 +5178,46 @@ public void testTupleIntegrityOnModification() { "declare trait A @propertyReactive value : int end " + "rule Trait when " + - " $core: Entity( ) " + + " $core: Entity() " + "then " + - " A o = don( $core, A.class ); " + + " A o = don($core, A.class); " + "end " + "rule Test when " + - " $x: A( value == 0 ) " + + " $x: A(value == 0) " + "then " + - " list.add( 0 ); " + + " list.add(0); " + "end " + "rule Check when " + - " $x: A( value == 42 ) " + + " $x: A(value == 42) " + "then " + - " list.add( 42 ); " + + " list.add(42); " + "end " + "rule Mood when " + - " $x : A( value != 42 ) " + + " $x : A(value != 42) " + "then " + - " modify ( $x ) { setValue( 42 ); } " + + " modify ($x) { setValue(42); } " + "end "; - KieBase kbase = getKieBaseFromString( drl ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl); + TraitFactoryImpl.setMode(mode, kbase); KieSession ksession = kbase.newKieSession(); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - ksession.insert( new Entity() ); + ksession.insert(new Entity()); ksession.fireAllRules(); - for ( final Object o : ksession.getObjects(object -> object.getClass().getName().contains( "test.A" )) ) { - InternalFactHandle handle = (InternalFactHandle) ksession.getFactHandle( o ); + for (final Object o : ksession.getObjects(object -> object.getClass().getName().contains("test.A"))) { + InternalFactHandle handle = (InternalFactHandle) ksession.getFactHandle(o); TupleImpl first = handle.getFirstLeftTuple(); - assertThat(first instanceof RuleTerminalNodeLeftTuple).isTrue(); + assertThat(first).isInstanceOf(RuleTerminalNodeLeftTuple.class); assertThat(((RuleTerminalNodeLeftTuple) first).getRule().getName()).isEqualTo("Check"); } - assertThat(list).isEqualTo(Arrays.asList(0, 42)); + assertThat(list).containsExactly(0, 42); } @Test @@ -5462,9 +5233,9 @@ public void testShedVacancy() { "rule Trait when " + "then " + - " Entity e = new Entity( 'x1' ); " + - " don( e, C.class ); " + - " don( e, D.class ); " + + " Entity e = new Entity('x1'); " + + " don(e, C.class); " + + " don(e, D.class); " + "end " + "rule Mood when " + @@ -5476,63 +5247,63 @@ public void testShedVacancy() { " $s : String() " + " $x : Entity() " + "then " + - " delete( $s ); " + - " shed( $x, A.class ); " + + " delete($s); " + + " shed($x, A.class); " + "end " + ""; - KieBase kbase = getKieBaseFromString( drl ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl); + TraitFactoryImpl.setMode(mode, kbase); KieSession ksession = kbase.newKieSession(); List list = new ArrayList(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); HierarchyEncoder hier = ((TraitRuntimeComponentFactory) RuntimeComponentFactory.get()).getTraitRegistry(((InternalKnowledgeBase) kbase)).getHierarchy(); - BitSet a = (BitSet) hier.getCode( "org.drools.test.A" ).clone(); - BitSet b = (BitSet) hier.getCode( "org.drools.test.B" ).clone(); - BitSet c = (BitSet) hier.getCode( "org.drools.test.C" ).clone(); - BitSet d = (BitSet) hier.getCode( "org.drools.test.D" ).clone(); + BitSet a = (BitSet) hier.getCode("org.drools.test.A").clone(); + BitSet b = (BitSet) hier.getCode("org.drools.test.B").clone(); + BitSet c = (BitSet) hier.getCode("org.drools.test.C").clone(); + BitSet d = (BitSet) hier.getCode("org.drools.test.D").clone(); int n = ksession.fireAllRules(); assertThat(n).isEqualTo(2); - LOGGER.debug( "---------------------------------------------------------------\n\n\n " ); + LOGGER.debug("---------------------------------------------------------------\n\n\n "); int counter = 0; - for ( Object o : ksession.getObjects() ) { - if ( o instanceof TraitProxyImpl) { + for (Object o : ksession.getObjects()) { + if (o instanceof TraitProxyImpl) { TraitProxyImpl tp = (TraitProxyImpl) o; - if ( tp._getTypeCode().equals( c ) ) { - assertThat(tp.listAssignedOtnTypeCodes().size()).isEqualTo(1); - assertThat(tp.listAssignedOtnTypeCodes().contains(b)).isTrue(); + if (tp._getTypeCode().equals(c)) { + assertThat(tp.listAssignedOtnTypeCodes()).hasSize(1); + assertThat(tp.listAssignedOtnTypeCodes()).contains(b); counter++; - } else if ( tp._getTypeCode().equals( d ) ) { - assertThat(tp.listAssignedOtnTypeCodes().isEmpty()).isTrue(); + } else if (tp._getTypeCode().equals(d)) { + assertThat(tp.listAssignedOtnTypeCodes()).isEmpty(); counter++; } - } else if ( o instanceof TraitableBean ) { + } else if (o instanceof TraitableBean) { TraitableBean tb = (TraitableBean) o; - LOGGER.debug( tb.getCurrentTypeCode().toString() ); + LOGGER.debug(tb.getCurrentTypeCode().toString()); counter++; } } assertThat(counter).isEqualTo(3); - ksession.insert( "go" ); + ksession.insert("go"); ksession.fireAllRules(); - LOGGER.debug( "---------------------------------------------------------------\n\n\n " ); + LOGGER.debug("---------------------------------------------------------------\n\n\n "); int counter2 = 0; - for ( Object o : ksession.getObjects() ) { - if ( o instanceof TraitProxyImpl) { + for (Object o : ksession.getObjects()) { + if (o instanceof TraitProxyImpl) { TraitProxyImpl tp = (TraitProxyImpl) o; assertThat(tp._getTypeCode()).isEqualTo(d); - assertThat(tp.listAssignedOtnTypeCodes().size()).isEqualTo(1); - assertThat(tp.listAssignedOtnTypeCodes().contains(b)).isTrue(); + assertThat(tp.listAssignedOtnTypeCodes()).hasSize(1); + assertThat(tp.listAssignedOtnTypeCodes()).contains(b); counter2++; - } else if ( o instanceof TraitableBean ) { + } else if (o instanceof TraitableBean) { TraitableBean tb = (TraitableBean) o; assertThat(tb.getCurrentTypeCode()).isEqualTo(d); counter2++; @@ -5554,32 +5325,32 @@ public void testExternalUpdateWithProxyRefreshInEqualityMode() { "end " + "rule Don when " + - " $x : ExtEntity( $id : id ) " + + " $x : ExtEntity($id : id) " + "then " + - " list.add( $id ); " + - " don( $x, Mask.class ); " + + " list.add($id); " + + " don($x, Mask.class); " + "end " + "rule Test when " + - " Mask( $n : num ) " + + " Mask($n : num) " + "then " + - " list.add( $n ); " + + " list.add($n); " + "end "; - KieBase kbase = getKieBaseFromString( drl, EqualityBehaviorOption.EQUALITY ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl, EqualityBehaviorOption.EQUALITY); + TraitFactoryImpl.setMode(mode, kbase); KieSession ksession = kbase.newKieSession(); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - FactHandle handle = ksession.insert( new ExtEntity( "x1", 42 ) ); + FactHandle handle = ksession.insert(new ExtEntity("x1", 42)); ksession.fireAllRules(); - ksession.update( handle, new ExtEntity( "x1", 35 ) ); + ksession.update(handle, new ExtEntity("x1", 35)); ksession.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList("x1", 42, "x1", 42)); + assertThat(list).containsExactly("x1", 42, "x1", 42); } @@ -5593,26 +5364,26 @@ public void testIsAInstanceOf() { "rule Test1 " + "when " + - " StudentImpl( this isA IStudent.class ) " + - "then list.add( 1 ); end " + + " StudentImpl(this isA IStudent.class) " + + "then list.add(1); end " + "rule Test2 " + "when " + - " IStudent( this isA StudentImpl.class ) " + - "then list.add( 2 ); end " + + " IStudent(this isA StudentImpl.class) " + + "then list.add(2); end " + ""; - KieBase kbase = getKieBaseFromString( drl ); - List list = new ArrayList( ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl); + List list = new ArrayList<>(); + TraitFactoryImpl.setMode(mode, kbase); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); - knowledgeSession.insert( new StudentImpl( ) ); + knowledgeSession.setGlobal("list", list); + knowledgeSession.insert(new StudentImpl()); assertThat(knowledgeSession.fireAllRules()).isEqualTo(2); - assertThat(list).isEqualTo(Arrays.asList(1, 2)); + assertThat(list).containsExactly(1, 2); } @@ -5624,21 +5395,21 @@ public void testIsAInstanceOfNonTraitable() { "rule Test1 " + "when " + - " Object( this isA String.class ) " + - "then list.add( 1 ); end " + + " Object(this isA String.class) " + + "then list.add(1); end " + ""; - KieBase kbase = getKieBaseFromString( drl ); - List list = new ArrayList( ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl); + List list = new ArrayList<>(); + TraitFactoryImpl.setMode(mode, kbase); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); - knowledgeSession.insert( "hello" ); + knowledgeSession.setGlobal("list", list); + knowledgeSession.insert("hello"); assertThat(knowledgeSession.fireAllRules()).isEqualTo(1); - assertThat(list).isEqualTo(List.of(1)); + assertThat(list).containsExactly(1); } @@ -5652,26 +5423,26 @@ public int getNum() { return num; } - public void setNum( int num ) { + public void setNum(int num) { this.num = num; } - public ExtEntity( String id, int num ) { - super( id ); + public ExtEntity(String id, int num) { + super(id); this.num = num; } } - protected Set checkOTNPartitioning( TraitableBean core, KieSession wm ) { + protected Set checkOTNPartitioning(TraitableBean core, KieSession wm) { Set otns = new HashSet(); - for ( Object o : core._getTraitMap().values() ) { + for (Object o : core._getTraitMap().values()) { TraitProxyImpl tp = (TraitProxyImpl) o; Set localNodes = tp.listAssignedOtnTypeCodes(); - for ( BitSet code : localNodes ) { - assertThat(otns.contains(code)).isFalse(); - otns.add( code ); + for (BitSet code : localNodes) { + assertThat(otns).doesNotContain(code); + otns.add(code); } } @@ -5688,27 +5459,27 @@ public void testSerializeKieBaseWithTraits() { "rule Test1 " + "when " + - " StudentImpl( this isA IStudent.class ) " + - "then list.add( 1 ); end " + + " StudentImpl(this isA IStudent.class) " + + "then list.add(1); end " + "rule Test2 " + "when " + - " IStudent( this isA StudentImpl.class ) " + - "then list.add( 2 ); end " + + " IStudent(this isA StudentImpl.class) " + + "then list.add(2); end " + ""; - KieBase kbase = getKieBaseFromString( drl ); + KieBase kbase = getKieBaseFromString(drl); - List list = new ArrayList( ); - TraitFactoryImpl.setMode(mode, kbase ); + List list = new ArrayList<>(); + TraitFactoryImpl.setMode(mode, kbase); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); - knowledgeSession.insert( new StudentImpl( ) ); + knowledgeSession.setGlobal("list", list); + knowledgeSession.insert(new StudentImpl()); assertThat(knowledgeSession.fireAllRules()).isEqualTo(2); - assertThat(list).isEqualTo(Arrays.asList(1, 2)); + assertThat(list).containsExactly(1, 2); } @Test @@ -5739,27 +5510,27 @@ public void testMixin2() { "rule \"Zero\"\n" + "when\n" + "then\n" + - " insert( new Person() );\n" + + " insert(new Person());\n" + "end\n" + "\n" + "\n" + "rule \"Student\"\n" + "no-loop\n" + "when\n" + - " $p : Person( $name : name, $age : age < 25, $weight : weight )\n" + + " $p : Person($name : name, $age : age < 25, $weight : weight)\n" + "then\n" + - " Student s = don( $p, Student.class );\n" + - " s.setSchool( \"SomeSchool\" );\n" + - " s.learn( \" AI \" );\n" + + " Student s = don($p, Student.class);\n" + + " s.setSchool(\"SomeSchool\");\n" + + " s.learn(\" AI \");\n" + "end\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); ks.fireAllRules(); } - @Trait( impl = ScholarImpl.class ) + @Trait(impl = ScholarImpl.class) public interface Scholar { void learn(String subject); } @@ -5772,16 +5543,16 @@ public static class ScholarImpl implements Scholar { public ScholarImpl() { } - public ScholarImpl( Thing arg ) { + public ScholarImpl(Thing arg) { this.core = arg; } - public void learn( String subject ) { - LOGGER.debug( "I " + core.getFields().get( "name" ) + ", now know everything about " + subject ); + public void learn(String subject) { + LOGGER.debug("I " + core.getFields().get("name") + ", now know everything about " + subject); } } - @Trait( impl = YImpl.class ) + @Trait(impl = YImpl.class) public interface Y { String getShared(); String getYValue(); @@ -5800,7 +5571,7 @@ public String getYValue() { } } - @Trait( impl = ZImpl.class ) + @Trait(impl = ZImpl.class) public interface Z { String getShared(); String getZValue(); @@ -5839,27 +5610,27 @@ private void checkMixinResolutionUsesOrder(String interfaces, String first) { "end\n" + "\n" + "\n" + - "declare X extends " + interfaces + " @Trait( mixinSolveConflicts = Trait.MixinConflictResolutionStrategy.DECLARATION_ORDER ) end\n" + + "declare X extends " + interfaces + " @Trait(mixinSolveConflicts = Trait.MixinConflictResolutionStrategy.DECLARATION_ORDER) end\n" + "\n" + "rule Init when\n" + "then\n" + - " insert( new Bean() );\n" + + " insert(new Bean());\n" + "end\n" + "\n" + "rule Exec no-loop when\n" + " $b : Bean()\n" + "then\n" + - " X x = don( $b, X.class );\n" + - " list.add( x.getYValue() );\n" + - " list.add( x.getZValue() );\n" + - " list.add( x.getShared() );\n" + + " X x = don($b, X.class);\n" + + " list.add(x.getYValue());\n" + + " list.add(x.getZValue());\n" + + " list.add(x.getShared());\n" + "end\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); List list = new ArrayList(); - ks.setGlobal( "list", list ); + ks.setGlobal("list", list); ks.fireAllRules(); @@ -5884,32 +5655,29 @@ public void testMixinWithConflictsThrowingError() { "end\n" + "\n" + "\n" + - "declare X extends Y,Z @Trait( mixinSolveConflicts = Trait.MixinConflictResolutionStrategy.ERROR_ON_CONFLICT ) end\n" + + "declare X extends Y,Z @Trait(mixinSolveConflicts = Trait.MixinConflictResolutionStrategy.ERROR_ON_CONFLICT) end\n" + "\n" + "rule Init when\n" + "then\n" + - " insert( new Bean() );\n" + + " insert(new Bean());\n" + "end\n" + "\n" + "rule Exec no-loop when\n" + " $b : Bean()\n" + "then\n" + - " X x = don( $b, X.class );\n" + - " list.add( x.getYValue() );\n" + - " list.add( x.getZValue() );\n" + - " list.add( x.getShared() );\n" + + " X x = don($b, X.class);\n" + + " list.add(x.getYValue());\n" + + " list.add(x.getZValue());\n" + + " list.add(x.getShared());\n" + "end\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); List list = new ArrayList(); - ks.setGlobal( "list", list ); + ks.setGlobal("list", list); - try { - ks.fireAllRules(); - fail("don should fail due to the conflict in getShared() method"); - } catch (Exception e) { } + assertThatException().as("don should fail due to the conflict in getShared() method").isThrownBy(() -> ks.fireAllRules()); } @Test @@ -5934,58 +5702,58 @@ public void testPreserveAllSetBitMask() { "" + "rule Init when\n" + "then " + - " Entity e1 = new Entity( \"X\" ); " + - " insert( e1 ); " + - " Entity e2 = new Entity( \"Y\" ); " + - " insert( e2 ); " + + " Entity e1 = new Entity(\"X\"); " + + " insert(e1); " + + " Entity e2 = new Entity(\"Y\"); " + + " insert(e2); " + " " + - " D d1 = don( e1, D.class, true ); " + - " F f2 = don( e2, F.class, true ); " + + " D d1 = don(e1, D.class, true); " + + " F f2 = don(e2, F.class, true); " + " " + - " modify ( d1 ) { getObjProp().add( f2.getCore() ); } " + - " modify ( f2.getCore() ) {} " + + " modify (d1) { getObjProp().add(f2.getCore()); } " + + " modify (f2.getCore()) {} " + "end " + "" + "rule Rec no-loop when\n" + - " MyThing( $x_0 := core, this isA D.class, $p : this#RootThing.objProp ) " + - " exists MyThing( $x_1 := core , core memberOf $p, this isA F.class ) " + + " MyThing($x_0 := core, this isA D.class, $p : this#RootThing.objProp) " + + " exists MyThing($x_1 := core , core memberOf $p, this isA F.class) " + "then " + - " don( $x_0, E.class, true ); " + + " don($x_0, E.class, true); " + "end " + "" + "rule Shed_2 when\n" + - " $s : String( this == \"go2\") " + - " $x : E( $objs : objProp ) " + - " $y : F( $z : core memberOf $objs ) " + + " $s : String(this == \"go2\") " + + " $x : E($objs : objProp) " + + " $y : F($z : core memberOf $objs) " + "then " + - " retract( $s ); " + - " modify ( $x ) { getObjProp().remove( $z ); } " + - " modify ( $y ) {} " + + " retract($s); " + + " modify ($x) { getObjProp().remove($z); } " + + " modify ($y) {} " + "end "; KieHelper helper = new KieHelper(); - KieBase kieBase = helper.addContent( drl, ResourceType.DRL ).getKieContainer().getKieBase(); - TraitFactoryImpl.setMode(mode, kieBase ); + KieBase kieBase = helper.addContent(drl, ResourceType.DRL).getKieContainer().getKieBase(); + TraitFactoryImpl.setMode(mode, kieBase); KieSession kSession = kieBase.newKieSession(); kSession.fireAllRules(); - kSession.insert( "go2" ); + kSession.insert("go2"); kSession.fireAllRules(); - for ( Object o : kSession.getObjects( new ClassObjectFilter( Entity.class ) ) ) { + for (Object o : kSession.getObjects(new ClassObjectFilter(Entity.class))) { Entity e = (Entity) o; - if ( e.getId().equals( "X" ) ) { + if (e.getId().equals("X")) { assertThat(e.hasTrait("t.x.D")).isTrue(); assertThat(e.hasTrait("t.x.E")).isFalse(); assertThat(e.hasTrait("t.x.F")).isFalse(); - assertThat(((List) e._getDynamicProperties().get("objProp")).size()).isEqualTo(0); - } else if ( e.getId().equals( "Y" ) ) { + assertThat(((List) e._getDynamicProperties().get("objProp"))).isEmpty(); + } else if (e.getId().equals("Y")) { assertThat(e.hasTrait("t.x.F")).isTrue(); assertThat(e.hasTrait("t.x.D")).isFalse(); assertThat(e.hasTrait("t.x.E")).isFalse(); } else { - fail( "Unrecognized entity in WM" ); + fail("Unrecognized entity in WM"); } } } 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 b4f647b526c..51d42a2f5c4 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 @@ -30,7 +30,7 @@ import org.drools.traits.compiler.CommonTraitTest; import org.drools.traits.compiler.Person; import org.drools.traits.core.factmodel.Entity; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; @@ -82,7 +82,7 @@ public void setB(final int b) { } } - @Test(timeout=10000) + @Test public void testWithDeclaredTypeAndTraitInDifferentPackages() { // DROOLS-91 final String str1 = @@ -194,7 +194,7 @@ public void testIsAWith2KContainers() { KieBuilder kbuilder = ks.newKieBuilder(kfs ); kbuilder.buildAll(); - assertThat(kbuilder.getResults().getMessages().size()).isEqualTo(0); + assertThat(kbuilder.getResults().getMessages()).isEmpty(); ks.newKieContainer( kbuilder.getKieModule().getReleaseId() ).getKieBase(); @@ -205,7 +205,7 @@ public void testIsAWith2KContainers() { ksession.setGlobal( "students", students ); ksession.insert( new Person("tom", 20 ) ); ksession.fireAllRules(); - assertThat(students.size()).isEqualTo(1); + assertThat(students).hasSize(1); } public static interface FooIntf { @@ -347,7 +347,7 @@ public void testRedeclareClassAsTrait() { KieHelper kh = new KieHelper(); kh.addContent( s1, ResourceType.DRL ); - assertThat(kh.verify().getMessages(Message.Level.ERROR).size()).isEqualTo(1); + assertThat(kh.verify().getMessages(Message.Level.ERROR)).hasSize(1); } public static class SomeClass {} @@ -381,7 +381,7 @@ public void testMultipleInheritanceWithPosition1() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(5); + assertThat(sw.getFields()).hasSize(5); assertThat(sw.getFields().get(0).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field1"); assertThat(sw.getFields().get(2).getName()).isEqualTo("mfield1"); @@ -417,7 +417,7 @@ public void testMultipleInheritanceWithPosition2() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(5); + assertThat(sw.getFields()).hasSize(5); assertThat(sw.getFields().get(0).getName()).isEqualTo("mfield0"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(2).getName()).isEqualTo("mfield1"); @@ -453,7 +453,7 @@ public void testMultipleInheritanceWithPosition3() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(5); + assertThat(sw.getFields()).hasSize(5); assertThat(sw.getFields().get(0).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field2"); assertThat(sw.getFields().get(2).getName()).isEqualTo("field1"); @@ -489,7 +489,7 @@ public void testMultipleInheritanceWithPosition4() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(5); + assertThat(sw.getFields()).hasSize(5); assertThat(sw.getFields().get(0).getName()).isEqualTo("field1"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field2"); assertThat(sw.getFields().get(2).getName()).isEqualTo("mfield0"); @@ -525,7 +525,7 @@ public void testMultipleInheritanceWithPosition5() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(5); + assertThat(sw.getFields()).hasSize(5); assertThat(sw.getFields().get(0).getName()).isEqualTo("field1"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(2).getName()).isEqualTo("mfield1"); @@ -567,7 +567,7 @@ public void testMultipleInheritanceWithPosition6() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(6); + assertThat(sw.getFields()).hasSize(6); assertThat(sw.getFields().get(0).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field1"); assertThat(sw.getFields().get(2).getName()).isEqualTo("field2"); @@ -610,7 +610,7 @@ public void testMultipleInheritanceWithPosition7() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(6); + assertThat(sw.getFields()).hasSize(6); assertThat(sw.getFields().get(0).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field2"); assertThat(sw.getFields().get(2).getName()).isEqualTo("mfield0"); diff --git a/drools-traits/src/test/java/org/drools/traits/core/factmodel/ClassBuilderTest.java b/drools-traits/src/test/java/org/drools/traits/core/factmodel/ClassBuilderTest.java index 1440cdd373b..10f6dffe16f 100755 --- a/drools-traits/src/test/java/org/drools/traits/core/factmodel/ClassBuilderTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/factmodel/ClassBuilderTest.java @@ -9,8 +9,7 @@ * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations @@ -34,9 +33,9 @@ import org.drools.base.factmodel.FieldDefinition; import org.drools.core.rule.JavaDialectRuntimeData; import org.drools.wiring.dynamic.PackageClassLoader; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.drools.wiring.api.classloader.ProjectClassLoader; -import org.junit.Before; -import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; @@ -48,7 +47,7 @@ public class ClassBuilderTest { ClassLoader classLoader; JavaDialectRuntimeData data; - @Before + @BeforeEach public void setUp() throws Exception { data = new JavaDialectRuntimeData(); } @@ -75,54 +74,40 @@ private Class build(ClassBuilder builder, ClassDefinition classDef) throws Excep * Test method for 'org.drools.core.common.asm.ClassBuilder.buildClass(ClassDefinition)' */ @Test - public void testBuildClass() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass1", - null, - new String[]{"java.io.Serializable"} ); - FieldDefinition intDef = new FieldDefinition("intAttr", - "int" ); - - FieldDefinition stringDef = new FieldDefinition( "stringAttr", - "java.lang.String" );//"java.lang.String" ); - classDef.addField( intDef ); - classDef.addField( stringDef ); - - Class clazz = build(builder, classDef); - - - - intDef.setReadWriteAccessor( store.getAccessor( clazz, - intDef.getName() ) ); - stringDef.setReadWriteAccessor( store.getAccessor( clazz, - stringDef.getName() ) ); - - byte[] d = builder.buildClass( classDef, classLoader ); - - assertThat(clazz).as("Returned class should be the same").isSameAs(classDef.getDefinedClass()); - assertThat(clazz.getName()).as("Class name should be equal").isEqualTo(classDef.getClassName()); - - Serializable instance = (Serializable) clazz.newInstance(); - - String stringValue = "Atributo String ok"; - stringDef.setValue( instance, - stringValue ); - assertThat(stringDef.getValue(instance)).as("Attribute should have been correctly set").isEqualTo(stringValue); - - int intValue = 50; - intDef.setValue( instance, - new Integer( intValue ) ); - assertThat(((Integer) intDef.getValue(instance)).intValue()).as("Attribute should have been correctly set").isEqualTo(intValue); - - // testing class rebuilding - clazz = build(builder, classDef); - - } catch ( Exception e ) { - e.printStackTrace(); - fail( "Error creating class" ); - } + public void testBuildClass() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass1", null, new String[]{"java.io.Serializable"} ); + FieldDefinition intDef = new FieldDefinition("intAttr", "int" ); + + FieldDefinition stringDef = new FieldDefinition( "stringAttr", "java.lang.String" );//"java.lang.String" ); + classDef.addField( intDef ); + classDef.addField( stringDef ); + + Class clazz = build(builder, classDef); + + + + intDef.setReadWriteAccessor( store.getAccessor( clazz, intDef.getName() ) ); + stringDef.setReadWriteAccessor( store.getAccessor( clazz, stringDef.getName() ) ); + + byte[] d = builder.buildClass( classDef, classLoader ); + + assertThat(clazz).as("Returned class should be the same").isSameAs(classDef.getDefinedClass()); + assertThat(clazz.getName()).as("Class name should be equal").isEqualTo(classDef.getClassName()); + + Serializable instance = (Serializable) clazz.newInstance(); + + String stringValue = "Atributo String ok"; + stringDef.setValue( instance, stringValue ); + assertThat(stringDef.getValue(instance)).as("Attribute should have been correctly set").isEqualTo(stringValue); + + int intValue = 50; + intDef.setValue( instance, new Integer( intValue ) ); + assertThat(((Integer) intDef.getValue(instance)).intValue()).as("Attribute should have been correctly set").isEqualTo(intValue); + + // testing class rebuilding + clazz = build(builder, classDef); } /** @@ -131,8 +116,7 @@ public void testBuildClass() { * @throws FileNotFoundException * @throws IOException */ - private void writeJar(byte[] data) throws FileNotFoundException, - IOException { + private void writeJar(byte[] data) throws FileNotFoundException, IOException { FileOutputStream out = new FileOutputStream("/Users/michaelneale/edson.jar"); JarOutputStream jout = new JarOutputStream( out ); JarEntry je = new JarEntry( "br/com/auster/TestClass1.class" ); @@ -143,363 +127,236 @@ private void writeJar(byte[] data) throws FileNotFoundException, } @Test - public void testEquals() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass2", - null, - new String[]{} ); - FieldDefinition long1Def = new FieldDefinition( "longAttr1", - "long", - true ); - FieldDefinition long2Def = new FieldDefinition( "longAttr2", - "long", - true ); - FieldDefinition doubleDef = new FieldDefinition( "doubleAttr", - "double", - true ); - FieldDefinition intDef = new FieldDefinition( "intAttr", - "int", - true ); - FieldDefinition strDef = new FieldDefinition( "stringAttr", - "java.lang.String", - true ); - FieldDefinition dateDef = new FieldDefinition( "dateAttr", - "java.util.Date", - true ); - FieldDefinition str2Def = new FieldDefinition( "stringAttr2", - "java.lang.String" ); - classDef.addField( long1Def ); - classDef.addField( long2Def ); - classDef.addField( doubleDef ); - classDef.addField( intDef ); - classDef.addField( strDef ); - classDef.addField( dateDef ); - classDef.addField( str2Def ); - - Class clazz = build(builder, classDef); - long1Def.setReadWriteAccessor( store.getAccessor( clazz, - long1Def.getName() ) ); - long2Def.setReadWriteAccessor( store.getAccessor( clazz, - long2Def.getName() ) ); - doubleDef.setReadWriteAccessor( store.getAccessor( clazz, - doubleDef.getName() ) ); - intDef.setReadWriteAccessor( store.getAccessor( clazz, - intDef.getName() ) ); - strDef.setReadWriteAccessor( store.getAccessor( clazz, - strDef.getName( ) ) ); - dateDef.setReadWriteAccessor( store.getAccessor( clazz, - dateDef.getName() ) ); - str2Def.setReadWriteAccessor( store.getAccessor( clazz, - str2Def.getName() ) ); - - Object x = clazz.newInstance(); - Object y = clazz.newInstance(); - - long1Def.setValue( x, - Long.valueOf( 20 ) ); - long2Def.setValue( x, - Long.valueOf( 30 ) ); - doubleDef.setValue( x, - Double.valueOf( 50.0 ) ); - intDef.setValue( x, - Integer.valueOf( 10 ) ); - strDef.setValue( x, - "abc" ); - dateDef.setValue( x, - new Date( 1000 ) ); - str2Def.setValue( x, - "instance1" ); - - long1Def.setValue( y, - Long.valueOf( 20 ) ); - long2Def.setValue( y, - Long.valueOf( 30 ) ); - doubleDef.setValue( y, - Double.valueOf( 50.0 ) ); - intDef.setValue( y, - Integer.valueOf( 10 ) ); - strDef.setValue( y, - "abc" ); - dateDef.setValue( y, - new Date( 1000 ) ); - str2Def.setValue( y, - "instance2" ); - - Object o = new Object(); - - assertThat(x.equals(x)).isTrue(); - - assertThat(x.equals(o)).isFalse(); - - assertThat(x.equals(y)).isTrue(); - - intDef.setValue( y, - Integer.valueOf( 1 ) ); - assertThat(x.equals(y)).isFalse(); - - intDef.setValue( y, - Integer.valueOf( 10 ) ); - strDef.setValue( y, - "xyz" ); - assertThat(x.equals(y)).isFalse(); - - strDef.setValue( y, - null ); - assertThat(x.equals(y)).isFalse(); - - strDef.setValue( y, - "abc" ); - dateDef.setValue( y, - new Date( 1 ) ); - assertThat(x.equals(y)).isFalse(); - - dateDef.setValue( y, - null ); - assertThat(x.equals(y)).isFalse(); - - } catch ( Exception e ) { - e.printStackTrace(); - fail( "Exception not expected" ); - } + public void testEquals() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass2", null, new String[]{} ); + FieldDefinition long1Def = new FieldDefinition( "longAttr1", "long", true ); + FieldDefinition long2Def = new FieldDefinition( "longAttr2", "long", true ); + FieldDefinition doubleDef = new FieldDefinition( "doubleAttr", "double", true ); + FieldDefinition intDef = new FieldDefinition( "intAttr", "int", true ); + FieldDefinition strDef = new FieldDefinition( "stringAttr", "java.lang.String", true ); + FieldDefinition dateDef = new FieldDefinition( "dateAttr", "java.util.Date", true ); + FieldDefinition str2Def = new FieldDefinition( "stringAttr2", "java.lang.String" ); + classDef.addField( long1Def ); + classDef.addField( long2Def ); + classDef.addField( doubleDef ); + classDef.addField( intDef ); + classDef.addField( strDef ); + classDef.addField( dateDef ); + classDef.addField( str2Def ); + + Class clazz = build(builder, classDef); + long1Def.setReadWriteAccessor( store.getAccessor( clazz, long1Def.getName() ) ); + long2Def.setReadWriteAccessor( store.getAccessor( clazz, long2Def.getName() ) ); + doubleDef.setReadWriteAccessor( store.getAccessor( clazz, doubleDef.getName() ) ); + intDef.setReadWriteAccessor( store.getAccessor( clazz, intDef.getName() ) ); + strDef.setReadWriteAccessor( store.getAccessor( clazz, strDef.getName( ) ) ); + dateDef.setReadWriteAccessor( store.getAccessor( clazz, dateDef.getName() ) ); + str2Def.setReadWriteAccessor( store.getAccessor( clazz, str2Def.getName() ) ); + + Object x = clazz.newInstance(); + Object y = clazz.newInstance(); + + long1Def.setValue( x, Long.valueOf( 20 ) ); + long2Def.setValue( x, Long.valueOf( 30 ) ); + doubleDef.setValue( x, Double.valueOf( 50.0 ) ); + intDef.setValue( x, Integer.valueOf( 10 ) ); + strDef.setValue( x, "abc" ); + dateDef.setValue( x, new Date( 1000 ) ); + str2Def.setValue( x, "instance1" ); + + long1Def.setValue( y, Long.valueOf( 20 ) ); + long2Def.setValue( y, Long.valueOf( 30 ) ); + doubleDef.setValue( y, Double.valueOf( 50.0 ) ); + intDef.setValue( y, Integer.valueOf( 10 ) ); + strDef.setValue( y, "abc" ); + dateDef.setValue( y, new Date( 1000 ) ); + str2Def.setValue( y, "instance2" ); + + Object o = new Object(); + + assertThat(x).isEqualTo(x);; + + assertThat(x).isNotEqualTo(o); + + assertThat(x).isEqualTo(y);; + + intDef.setValue( y, Integer.valueOf( 1 ) ); + assertThat(x).isNotEqualTo(y); + + intDef.setValue( y, Integer.valueOf( 10 ) ); + strDef.setValue( y, "xyz" ); + assertThat(x).isNotEqualTo(y); + + strDef.setValue( y, null ); + assertThat(x).isNotEqualTo(y); + + strDef.setValue( y, "abc" ); + dateDef.setValue( y, new Date( 1 ) ); + assertThat(x).isNotEqualTo(y); + + dateDef.setValue( y, null ); + assertThat(x).isNotEqualTo(y); } @Test - public void testHashCode() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass3", - null, - new String[]{} ); - FieldDefinition intDef = new FieldDefinition( "intAttr", - "int", - true ); - FieldDefinition strDef = new FieldDefinition( "stringAttr", - "java.lang.String", - false ); - classDef.addField( intDef ); - classDef.addField( strDef ); - - Class clazz = build(builder, classDef); - intDef.setReadWriteAccessor( store.getAccessor( clazz, - intDef.getName() ) ); - strDef.setReadWriteAccessor( store.getAccessor( clazz, - strDef.getName() ) ); - - Object x = clazz.newInstance(); - - intDef.setValue( x, - new Integer( 10 ) ); - strDef.setValue( x, - "abc" ); - - assertThat(x.hashCode()).as("Wrong hashcode calculation").isEqualTo(31 + 10); - assertThat(x.hashCode()).as("Wrong hashcode calculation").isEqualTo(x.hashCode()); - - } catch ( Exception e ) { - e.printStackTrace(); - fail( "Exception not expected" ); - } + public void testHashCode() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass3", null, new String[]{} ); + FieldDefinition intDef = new FieldDefinition( "intAttr", "int", true ); + FieldDefinition strDef = new FieldDefinition( "stringAttr", "java.lang.String", false ); + classDef.addField( intDef ); + classDef.addField( strDef ); + + Class clazz = build(builder, classDef); + intDef.setReadWriteAccessor( store.getAccessor( clazz, intDef.getName() ) ); + strDef.setReadWriteAccessor( store.getAccessor( clazz, strDef.getName() ) ); + + Object x = clazz.newInstance(); + + intDef.setValue( x, new Integer( 10 ) ); + strDef.setValue( x, "abc" ); + + assertThat(x.hashCode()).as("Wrong hashcode calculation").isEqualTo(31 + 10); + assertThat(x.hashCode()).as("Wrong hashcode calculation").isEqualTo(x.hashCode()); } @Test - public void testToString() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass4", - null, - new String[]{} ); - FieldDefinition long1Def = new FieldDefinition( "longAttr1", - "long", - true ); - FieldDefinition long2Def = new FieldDefinition( "longAttr2", - "long", - true ); - FieldDefinition doubleDef = new FieldDefinition( "doubleAttr", - "double", - true ); - FieldDefinition intDef = new FieldDefinition( "intAttr", - "int", - true ); - FieldDefinition strDef = new FieldDefinition( "stringAttr", - "java.lang.String", - true ); - FieldDefinition dateDef = new FieldDefinition( "dateAttr", - "java.util.Date", - true ); - FieldDefinition str2Def = new FieldDefinition( "stringAttr2", - "java.lang.String" ); - classDef.addField( long1Def ); - classDef.addField( long2Def ); - classDef.addField( doubleDef ); - classDef.addField( intDef ); - classDef.addField( strDef ); - classDef.addField( dateDef ); - classDef.addField( str2Def ); - - Class clazz = build(builder, classDef); - long1Def.setReadWriteAccessor( store.getAccessor( clazz, - long1Def.getName() ) ); - long2Def.setReadWriteAccessor( store.getAccessor( clazz, - long2Def.getName() ) ); - doubleDef.setReadWriteAccessor( store.getAccessor( clazz, - doubleDef.getName() ) ); - intDef.setReadWriteAccessor( store.getAccessor( clazz, - intDef.getName() ) ); - strDef.setReadWriteAccessor( store.getAccessor( clazz, - strDef.getName() ) ); - dateDef.setReadWriteAccessor( store.getAccessor( clazz, - dateDef.getName() ) ); - str2Def.setReadWriteAccessor( store.getAccessor( clazz, - str2Def.getName() ) ); - - Object x = clazz.newInstance(); - - long1Def.setValue( x, - new Long( 20 ) ); - long2Def.setValue( x, - new Long( 30 ) ); - doubleDef.setValue( x, - new Double( 50.0 ) ); - intDef.setValue( x, - new Integer( 10 ) ); - strDef.setValue( x, - "abc" ); - dateDef.setValue( x, - new Date( 1000 ) ); - str2Def.setValue( x, - "instance1" ); - - String result = x.toString(); - - assertThat(result.contains(long1Def.getName())).isTrue(); - assertThat(result.contains(long2Def.getName())).isTrue(); - assertThat(result.contains(doubleDef.getName())).isTrue(); - assertThat(result.contains(intDef.getName())).isTrue(); - assertThat(result.contains(strDef.getName())).isTrue(); - assertThat(result.contains(dateDef.getName())).isTrue(); - assertThat(result.contains(str2Def.getName())).isTrue(); - - } catch ( Exception e ) { - e.printStackTrace(); - fail( "Exception not expected" ); - } + public void testToString() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass4", null, new String[]{} ); + FieldDefinition long1Def = new FieldDefinition( "longAttr1", "long", true ); + FieldDefinition long2Def = new FieldDefinition( "longAttr2", "long", true ); + FieldDefinition doubleDef = new FieldDefinition( "doubleAttr", "double", true ); + FieldDefinition intDef = new FieldDefinition( "intAttr", "int", true ); + FieldDefinition strDef = new FieldDefinition( "stringAttr", "java.lang.String", true ); + FieldDefinition dateDef = new FieldDefinition( "dateAttr", "java.util.Date", true ); + FieldDefinition str2Def = new FieldDefinition( "stringAttr2", "java.lang.String" ); + classDef.addField( long1Def ); + classDef.addField( long2Def ); + classDef.addField( doubleDef ); + classDef.addField( intDef ); + classDef.addField( strDef ); + classDef.addField( dateDef ); + classDef.addField( str2Def ); + + Class clazz = build(builder, classDef); + long1Def.setReadWriteAccessor( store.getAccessor( clazz, long1Def.getName() ) ); + long2Def.setReadWriteAccessor( store.getAccessor( clazz, long2Def.getName() ) ); + doubleDef.setReadWriteAccessor( store.getAccessor( clazz, doubleDef.getName() ) ); + intDef.setReadWriteAccessor( store.getAccessor( clazz, intDef.getName() ) ); + strDef.setReadWriteAccessor( store.getAccessor( clazz, strDef.getName() ) ); + dateDef.setReadWriteAccessor( store.getAccessor( clazz, dateDef.getName() ) ); + str2Def.setReadWriteAccessor( store.getAccessor( clazz, str2Def.getName() ) ); + + Object x = clazz.newInstance(); + + long1Def.setValue( x, new Long( 20 ) ); + long2Def.setValue( x, new Long( 30 ) ); + doubleDef.setValue( x, new Double( 50.0 ) ); + intDef.setValue( x, new Integer( 10 ) ); + strDef.setValue( x, "abc" ); + dateDef.setValue( x, new Date( 1000 ) ); + str2Def.setValue( x, "instance1" ); + + String result = x.toString(); + + assertThat(result).contains(long1Def.getName()); + assertThat(result).contains(long2Def.getName()); + assertThat(result).contains(doubleDef.getName()); + assertThat(result).contains(intDef.getName()); + assertThat(result).contains(strDef.getName()); + assertThat(result).contains(dateDef.getName()); + assertThat(result).contains(str2Def.getName()); } @Test - public void testConstructorWithFields() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass5", - null, - new String[]{} ); - - String[] types = new String[]{"byte", "short", "int", "long", "float", "double", "char", "java.lang.String", "boolean"}; - FieldDefinition[] fields = new FieldDefinition[types.length]; - for ( int i = 0; i < types.length; i++ ) { - String attrName = types[i].substring( types[i].lastIndexOf( '.' ) + 1 ); - attrName = attrName.substring( 0, - 1 ).toLowerCase() + attrName.substring( 1 ) + "Attr"; - fields[i] = new FieldDefinition( attrName, // attr name - types[i], // attr type - i % 2 == 0 ); // half of them are key - classDef.addField( fields[i] ); - } - - Class clazz = build(builder, classDef); - - for ( FieldDefinition field : fields ) { - field.setReadWriteAccessor( store.getAccessor( clazz, - field.getName() ) ); - } - - Constructor< ? >[] cons = clazz.getConstructors(); - - assertThat(cons.length).isEqualTo(3); - for ( Constructor< ? > c : cons ) { - Class< ? >[] ptypes = c.getParameterTypes(); - if ( ptypes.length == 0 ) { - // default constructor - } else if ( ptypes.length == fields.length ) { - // constructor with fields - for ( int i = 0; i < ptypes.length; i++ ) { - if ( !ptypes[i].equals( fields[i].getType() ) ) { - fail( "Wrong parameter in constructor. index=" + i + " expected=" + fields[i].getType() + " found=" + ptypes[i] ); - } - } - - // test actual invocation - Object instance = c.newInstance( (byte) 1, - (short) 2, - 3, - 4l, - 5.0f, - 6.0d, - 'a', - "xyz", - true ); - - assertThat(fields[0].getValue(instance)).isEqualTo((byte) 1); - assertThat(fields[1].getValue(instance)).isEqualTo((short) 2); - assertThat(fields[2].getValue(instance)).isEqualTo(3); - assertThat(fields[3].getValue(instance)).isEqualTo(4l); - assertThat(fields[4].getValue(instance)).isEqualTo(5.0f); - assertThat(fields[5].getValue(instance)).isEqualTo(6.0d); - assertThat(fields[6].getValue(instance)).isEqualTo('a'); - assertThat(fields[7].getValue(instance)).isEqualTo("xyz"); - assertThat(fields[8].getValue(instance)).isEqualTo(true); - } else if ( ptypes.length == ( fields.length / 2 +1 ) ) { // as defined in the beginning of the test - // constructor with key fields - int i = 0; - for ( FieldDefinition field : fields ) { - if ( field.isKey() && !ptypes[i++].equals( field.getType() ) ) { - fail( "Wrong parameter in constructor. index=" + i + " expected=" + field.getType() + " found=" + ptypes[i] ); - } - } - // test actual invocation - Object instance = c.newInstance( (byte) 1, - 3, - 5.0f, - 'a', - true ); - - assertThat(fields[0].getValue(instance)).isEqualTo((byte) 1); - assertThat(fields[2].getValue(instance)).isEqualTo(3); - assertThat(fields[4].getValue(instance)).isEqualTo(5.0f); - assertThat(fields[6].getValue(instance)).isEqualTo('a'); - assertThat(fields[8].getValue(instance)).isEqualTo(true); - - } else { - fail( "Unexpected constructor: " + c.toString() ); - } - } - - } catch ( Exception e ) { - e.printStackTrace(); - fail( "Unexpected Exception: " + e.getMessage() ); - } + public void testConstructorWithFields() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass5", null, new String[]{} ); + + String[] types = new String[]{"byte", "short", "int", "long", "float", "double", "char", "java.lang.String", "boolean"}; + FieldDefinition[] fields = new FieldDefinition[types.length]; + for ( int i = 0; i < types.length; i++ ) { + String attrName = types[i].substring( types[i].lastIndexOf( '.' ) + 1 ); + attrName = attrName.substring( 0, 1 ).toLowerCase() + attrName.substring( 1 ) + "Attr"; + fields[i] = new FieldDefinition( attrName, // attr name + types[i], // attr type + i % 2 == 0 ); // half of them are key + classDef.addField( fields[i] ); + } + + Class clazz = build(builder, classDef); + + for ( FieldDefinition field : fields ) { + field.setReadWriteAccessor( store.getAccessor( clazz, field.getName() ) ); + } + + Constructor< ? >[] cons = clazz.getConstructors(); + + assertThat(cons.length).isEqualTo(3); + for ( Constructor< ? > c : cons ) { + Class< ? >[] ptypes = c.getParameterTypes(); + if ( ptypes.length == 0 ) { + // default constructor + } else if ( ptypes.length == fields.length ) { + // constructor with fields + for ( int i = 0; i < ptypes.length; i++ ) { + if ( !ptypes[i].equals( fields[i].getType() ) ) { + fail( "Wrong parameter in constructor. index=" + i + " expected=" + fields[i].getType() + " found=" + ptypes[i] ); + } + } + + // test actual invocation + Object instance = c.newInstance( (byte) 1, (short) 2, 3, 4l, 5.0f, 6.0d, 'a', "xyz", true ); + + assertThat(fields[0].getValue(instance)).isEqualTo((byte) 1); + assertThat(fields[1].getValue(instance)).isEqualTo((short) 2); + assertThat(fields[2].getValue(instance)).isEqualTo(3); + assertThat(fields[3].getValue(instance)).isEqualTo(4l); + assertThat(fields[4].getValue(instance)).isEqualTo(5.0f); + assertThat(fields[5].getValue(instance)).isEqualTo(6.0d); + assertThat(fields[6].getValue(instance)).isEqualTo('a'); + assertThat(fields[7].getValue(instance)).isEqualTo("xyz"); + assertThat(fields[8].getValue(instance)).isEqualTo(true); + } else if ( ptypes.length == ( fields.length / 2 +1 ) ) { // as defined in the beginning of the test + // constructor with key fields + int i = 0; + for ( FieldDefinition field : fields ) { + if ( field.isKey() && !ptypes[i++].equals( field.getType() ) ) { + fail( "Wrong parameter in constructor. index=" + i + " expected=" + field.getType() + " found=" + ptypes[i] ); + } + } + // test actual invocation + Object instance = c.newInstance( (byte) 1, 3, 5.0f, 'a', true ); + + assertThat(fields[0].getValue(instance)).isEqualTo((byte) 1); + assertThat(fields[2].getValue(instance)).isEqualTo(3); + assertThat(fields[4].getValue(instance)).isEqualTo(5.0f); + assertThat(fields[6].getValue(instance)).isEqualTo('a'); + assertThat(fields[8].getValue(instance)).isEqualTo(true); + + } else { + fail( "Unexpected constructor: " + c.toString() ); + } + } } @Test - public void testGetResourcesJBRULES3122() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition("org.drools.TestClass4", null, new String[] {}); - Class clazz = build(builder, classDef); - ClassLoader cl = clazz.getClassLoader(); - - // We expect normal classloader stuff to work - assertThat(cl.getResources("not-there.txt").hasMoreElements()).isFalse(); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception not expected: " + e.getMessage()); - } + public void testGetResourcesJBRULES3122() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition("org.drools.TestClass4", null, new String[] {}); + Class clazz = build(builder, classDef); + ClassLoader cl = clazz.getClassLoader(); + + // We expect normal classloader stuff to work + assertThat(cl.getResources("not-there.txt").hasMoreElements()).isFalse(); } } diff --git a/drools-traits/src/test/java/org/drools/traits/core/factmodel/InstancesHashcodedTest.java b/drools-traits/src/test/java/org/drools/traits/core/factmodel/InstancesHashcodedTest.java index 7e04e9e46a4..c33ad8e600c 100755 --- a/drools-traits/src/test/java/org/drools/traits/core/factmodel/InstancesHashcodedTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/factmodel/InstancesHashcodedTest.java @@ -28,8 +28,8 @@ import org.drools.base.factmodel.FieldDefinition; import org.drools.core.rule.JavaDialectRuntimeData; import org.drools.wiring.dynamic.PackageClassLoader; +import org.junit.jupiter.api.Test; import org.drools.wiring.api.classloader.ProjectClassLoader; -import org.junit.Test; import static org.drools.util.ClassUtils.convertClassToResourcePath; diff --git a/drools-traits/src/test/java/org/drools/traits/core/factmodel/JeneratorTest.java b/drools-traits/src/test/java/org/drools/traits/core/factmodel/JeneratorTest.java index fd656cfb569..134ad78c190 100644 --- a/drools-traits/src/test/java/org/drools/traits/core/factmodel/JeneratorTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/factmodel/JeneratorTest.java @@ -22,7 +22,7 @@ import java.util.jar.JarEntry; import java.util.jar.JarInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/drools-traits/src/test/java/org/drools/traits/core/factmodel/TripleStoreTest.java b/drools-traits/src/test/java/org/drools/traits/core/factmodel/TripleStoreTest.java index 6626e0771f6..288f463b008 100644 --- a/drools-traits/src/test/java/org/drools/traits/core/factmodel/TripleStoreTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/factmodel/TripleStoreTest.java @@ -23,7 +23,7 @@ import java.util.Collection; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.runtime.rule.Variable; import static org.assertj.core.api.Assertions.assertThat; @@ -183,31 +183,30 @@ public void testQueryVariable() { tKey = new TripleImpl( V, "hasCity", V ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(t3, t4))).isTrue(); - assertThat(coll.size()).isEqualTo(2); - + assertThat(coll).hasSize(2); + assertThat(coll).containsExactlyInAnyOrder(t3, t4); tKey = new TripleImpl( ind, V, V ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(t1, t2, t3))).isTrue(); - assertThat(coll.size()).isEqualTo(3); + assertThat(coll).hasSize(3); + assertThat(coll).containsExactlyInAnyOrder(t1, t2, t3); tKey = new TripleImpl( ind2, V, "lancia" ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(t5, t6))).isTrue(); - assertThat(coll.size()).isEqualTo(2); + assertThat(coll).hasSize(2); + assertThat(coll).containsExactlyInAnyOrder(t5, t6); tKey = new TripleImpl( V, V, "lancia" ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(t5, t6))).isTrue(); - assertThat(coll.size()).isEqualTo(2); + assertThat(coll).hasSize(2); + assertThat(coll).containsExactlyInAnyOrder(t5, t6); tKey = new TripleImpl( V, V, V ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(t1, t2, t3, t4, t5, t6))).isTrue(); - assertThat(coll.size()).isEqualTo(6); + assertThat(coll).hasSize(6); + assertThat(coll).containsExactlyInAnyOrder(t1, t2, t3, t4, t5, t6); } @@ -245,14 +244,13 @@ public void testAddNary() { Triple tKey; - Triple t; Collection coll; tKey = new TripleImpl( ind, "hasName", V ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(new TripleImpl(ind, "hasName", "oscar"), + assertThat(coll).containsExactlyInAnyOrder(new TripleImpl(ind, "hasName", "oscar"), new TripleImpl(ind, "hasName", "mark"), - new TripleImpl(ind, "hasName", "daniel")))).isTrue(); + new TripleImpl(ind, "hasName", "daniel")); assertThat(store.contains(new TripleImpl(ind, "hasName", "marc"))).isFalse(); assertThat(store.contains(new TripleImpl(ind, "hasName", "mark"))).isTrue(); @@ -265,20 +263,20 @@ public void testAddNary() { tKey = new TripleImpl( ind, "hasCar", V ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(new TripleImpl(ind, "hasCar", "mini"), - new TripleImpl(ind, "hasCar", "ferrari")))).isTrue(); + assertThat(coll).containsExactlyInAnyOrder(new TripleImpl(ind, "hasCar", "mini"), + new TripleImpl(ind, "hasCar", "ferrari")); store.remove( new TripleImpl(ind, "hasCar", "mini") ); tKey = new TripleImpl( ind, "hasCar", V ); coll = store.getAll(tKey); - assertThat(coll.size()).isEqualTo(1); + assertThat(coll).hasSize(1); store.remove( new TripleImpl(ind, "hasCar", "ferrari") ); tKey = new TripleImpl( ind, "hasCar", V ); coll = store.getAll(tKey); - assertThat(coll.size()).isEqualTo(0); + assertThat(coll).isEmpty(); } diff --git a/drools-traits/src/test/java/org/drools/traits/core/meta/org/MetadataTest.java b/drools-traits/src/test/java/org/drools/traits/core/meta/org/MetadataTest.java index 6a40cc460c5..4f454dd3283 100644 --- a/drools-traits/src/test/java/org/drools/traits/core/meta/org/MetadataTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/meta/org/MetadataTest.java @@ -40,7 +40,7 @@ import org.drools.traits.core.metadata.Lit; import org.drools.traits.core.metadata.MetadataContainer; import org.drools.traits.core.metadata.With; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -103,7 +103,7 @@ public void testKlassAndSubKlassWithInterfaces() { assertThat(sk.prop.get(ski)).isEqualTo("bye"); LOGGER.debug( ski.map.toString()); - Map tgt = new HashMap(); + Map tgt = new HashMap<>(); tgt.put( "prop", "bye" ); tgt.put( "subProp", -99 ); assertThat(ski.map).isEqualTo(tgt); @@ -183,7 +183,7 @@ public void testURIs() { assertThat(AnotherKlass_.modify(aki).num(33).getUri()).isEqualTo(URI.create(uri.toString() + "/modify?num")); - assertThat(uri.toString().startsWith(aki.get_().getMetaClassInfo().getUri().toString())).isTrue(); + assertThat(uri.toString()).startsWith(aki.get_().getMetaClassInfo().getUri().toString()); assertThat(SubKlass_.newSubKlass(URI.create("http://www.test.org#SubKlass/123")).getUri()).isEqualTo(URI.create("http://www.test.org#SubKlass/123?create")); @@ -195,7 +195,7 @@ public void testURIs() { public void testNewInstance() { Klass klass = Klass_.newKlass( URI.create( "test" ) ).call(); assertThat(klass).isNotNull(); - assertThat(klass instanceof KlassImpl).isTrue(); + assertThat(klass).isInstanceOf(KlassImpl.class); SubKlass klass2 = SubKlass_.newSubKlass( URI.create( "test2" ) ).subProp( 42 ).prop( "hello" ).call(); @@ -215,7 +215,7 @@ public void testURIsOnLegacyClasses() { @Test public void testDon() { Entity entity = new Entity( "123" ); - entity._setDynamicProperties( new HashMap( ) ); + entity._setDynamicProperties( new HashMap<>( ) ); entity._getDynamicProperties().put( "prop", "hello" ); Klass klass = Klass_.donKlass( entity ) @@ -229,7 +229,7 @@ public void testDon() { @Test public void testDonWithAttributes() { Entity entity = new Entity( "123" ); - entity._setDynamicProperties( new HashMap() ); + entity._setDynamicProperties( new HashMap<>() ); SubKlass klass = SubKlass_.donSubKlass(entity ) .setTraitFactory(createStandaloneTraitFactory()) @@ -259,7 +259,7 @@ public void testCollectionOrientedProperties() { AnotherKlass aki3 = AnotherKlass_.newAnotherKlass( "003" ).call(); AnotherKlass aki4 = AnotherKlass_.newAnotherKlass( "004" ).call(); - ArrayList initial = new ArrayList( Arrays.asList( aki0, aki1 ) ); + List initial = new ArrayList<>( List.of( aki0, aki1 ) ); SubKlass ski = SubKlass_.newSubKlass( URI.create( "123" ) ) .links( initial, Lit.SET ) .links( aki1, Lit.REMOVE ) @@ -311,14 +311,13 @@ public void testOneToManyProperty() { assertThat(klass1.getOneAnother()).isSameAs(aki2); assertThat(klass2.getOneAnother()).isSameAs(aki); - assertThat(aki.getManyKlasses().contains(klass1)).isFalse(); - assertThat(aki2.getManyKlasses().contains(klass1)).isTrue(); - assertThat(aki.getManyKlasses().contains(klass2)).isTrue(); + assertThat(aki.getManyKlasses()).doesNotContain(klass1); + assertThat(aki2.getManyKlasses()).contains(klass1).doesNotContain(klass2); AnotherKlass_.modify( aki2 ).manyKlasses( klass1, Lit.REMOVE ).call(); assertThat(klass1.getOneAnother()).isNull(); - assertThat(aki2.getManyKlasses().contains(klass1)).isFalse(); + assertThat(aki2.getManyKlasses()).doesNotContain(klass1); } @@ -362,51 +361,35 @@ public void testManyToManyProperty() { AnotherKlass_.modify( aki2 ).manyMoreKlasses( klass2, Lit.ADD ).call(); AnotherKlass_.modify( aki1 ).manyMoreKlasses( klass2, Lit.ADD ).call(); - assertThat(klass1.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass1.getManyAnothers().contains(aki2)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki2)).isTrue(); + assertThat(klass1.getManyAnothers()).contains(aki1, aki2); + assertThat(klass2.getManyAnothers()).contains(aki1, aki2); - assertThat(aki1.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki1.getManyMoreKlasses().contains(klass2)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass2)).isTrue(); + assertThat(aki1.getManyMoreKlasses()).contains(klass1, klass2); + assertThat(aki2.getManyMoreKlasses()).contains(klass1, klass2); AnotherKlass_.modify( aki2 ).manyMoreKlasses( klass2, Lit.REMOVE ).call(); - assertThat(klass1.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass1.getManyAnothers().contains(aki2)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki2)).isFalse(); + assertThat(klass1.getManyAnothers()).contains(aki1, aki2); + assertThat(klass2.getManyAnothers()).contains(aki1).doesNotContain(aki2); - assertThat(aki1.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki1.getManyMoreKlasses().contains(klass2)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass2)).isFalse(); + assertThat(aki1.getManyMoreKlasses()).contains(klass1, klass2); + assertThat(aki2.getManyMoreKlasses()).contains(klass1).doesNotContain(klass2); AnotherKlass_.modify( aki2 ).manyMoreKlasses( klass2, Lit.ADD ).call(); - assertThat(klass1.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass1.getManyAnothers().contains(aki2)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki2)).isTrue(); + assertThat(klass1.getManyAnothers()).contains(aki1, aki2); + assertThat(klass2.getManyAnothers()).contains(aki1, aki2); - assertThat(aki1.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki1.getManyMoreKlasses().contains(klass2)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass2)).isTrue(); + assertThat(aki1.getManyMoreKlasses()).contains(klass1, klass2); + assertThat(aki2.getManyMoreKlasses()).contains(klass1, klass2); AnotherKlass_.modify( aki2 ).manyMoreKlasses( klass2, Lit.SET ).call(); - assertThat(klass1.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass1.getManyAnothers().contains(aki2)).isFalse(); - assertThat(klass2.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki2)).isTrue(); + assertThat(klass1.getManyAnothers()).contains(aki1).doesNotContain(aki2); + assertThat(klass2.getManyAnothers()).contains(aki1, aki2); - assertThat(aki1.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki1.getManyMoreKlasses().contains(klass2)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass1)).isFalse(); - assertThat(aki2.getManyMoreKlasses().contains(klass2)).isTrue(); + assertThat(aki1.getManyMoreKlasses()).contains(klass1, klass2); + assertThat(aki2.getManyMoreKlasses()).doesNotContain(klass1).contains(klass2); } diff --git a/drools-traits/src/test/java/org/drools/traits/core/util/HierarchyTest.java b/drools-traits/src/test/java/org/drools/traits/core/util/HierarchyTest.java index d460cfd45d5..94c7d520aea 100644 --- a/drools-traits/src/test/java/org/drools/traits/core/util/HierarchyTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/util/HierarchyTest.java @@ -21,7 +21,7 @@ import org.drools.traits.core.factmodel.CodedHierarchy; import org.drools.traits.core.factmodel.HierarchyEncoder; import org.drools.traits.core.factmodel.IndexedTypeHierarchy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,9 +41,9 @@ public class HierarchyTest { @Test public void testHierEncoderTrivial() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("B")); encoder.encode( "D", Arrays.asList( "B", "C" ) ); @@ -58,13 +58,13 @@ public void testHierEncoderTrivial() { @Test public void testHierManyRoots() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); - encoder.encode( "B", Collections.EMPTY_LIST ); - encoder.encode( "C", Collections.EMPTY_LIST ); - encoder.encode( "D", Collections.EMPTY_LIST ); - encoder.encode( "E", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); + encoder.encode( "B", Collections.emptyList()); + encoder.encode( "C", Collections.emptyList()); + encoder.encode( "D", Collections.emptyList()); + encoder.encode( "E", Collections.emptyList()); LOGGER.debug( encoder.toString() ); @@ -75,21 +75,21 @@ public void testHierManyRoots() { assertThat(encoder.getCode("E")).isEqualTo(parseBitSet("10000")); assertThat(encoder.size()).isEqualTo(5); - assertThat(encoder.getSortedMembers().size()).isEqualTo(5); - assertThat(encoder.getSortedMap().size()).isEqualTo(5); + assertThat(encoder.getSortedMembers()).hasSize(5); + assertThat(encoder.getSortedMap()).hasSize(5); } @Test public void testHierManyRootsPropagation() { - HierarchyEncoderImpl encoder = new HierarchyEncoderImpl(); + HierarchyEncoderImpl encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("A")); encoder.encode( "D", Arrays.asList( "B", "C" ) ); - encoder.encode( "E", Collections.EMPTY_LIST ); + encoder.encode( "E", Collections.emptyList()); LOGGER.debug( encoder.toString() ); @@ -99,27 +99,27 @@ public void testHierManyRootsPropagation() { BitSet d = encoder.getCode( "D" ); BitSet e = encoder.getCode( "E" ); - assertThat(encoder.superset(b, a) > 0).isTrue(); - assertThat(encoder.superset(c, a) > 0).isTrue(); - assertThat(encoder.superset(d, a) > 0).isTrue(); - assertThat(encoder.superset(d, b) > 0).isTrue(); - assertThat(encoder.superset(d, c) > 0).isTrue(); + assertThat(encoder.superset(b, a)).isGreaterThan(0); + assertThat(encoder.superset(c, a)).isGreaterThan(0); + assertThat(encoder.superset(d, a)).isGreaterThan(0); + assertThat(encoder.superset(d, b)).isGreaterThan(0); + assertThat(encoder.superset(d, c)).isGreaterThan(0); - assertThat(encoder.superset(e, a) < 0).isTrue(); - assertThat(encoder.superset(e, b) < 0).isTrue(); - assertThat(encoder.superset(e, c) < 0).isTrue(); - assertThat(encoder.superset(e, d) < 0).isTrue(); - assertThat(encoder.superset(e, e) == 0).isTrue(); + assertThat(encoder.superset(e, a)).isLessThan(0); + assertThat(encoder.superset(e, b)).isLessThan(0); + assertThat(encoder.superset(e, c)).isLessThan(0); + assertThat(encoder.superset(e, d)).isLessThan(0); + assertThat(encoder.superset(e, e)).isEqualTo(0); } @Test public void testHierALotOfClasses() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); int N = 1194; - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); for ( int j = 1; j < N; j++ ) { encoder.encode( "X" + j, List.of("A")); } @@ -134,9 +134,9 @@ public void testHierALotOfClasses() { @Test public void testHierEncoderSimpleInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("A")); encoder.encode("D", List.of("B")); @@ -160,9 +160,9 @@ public void testHierEncoderSimpleInheritance() { @Test public void testHierEncoderAnotherSimpleInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("A1", List.of("R")); encoder.encode("A2", List.of("R")); encoder.encode("A3", List.of("R")); @@ -193,9 +193,9 @@ public void testHierEncoderAnotherSimpleInheritance() { @Test public void testHierEncoderAnotherSimpleInheritanceChangeOrder() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("B1", List.of("R")); encoder.encode("B2", List.of("R")); @@ -233,9 +233,9 @@ public void testHierEncoderAnotherSimpleInheritanceChangeOrder() { @Test public void testHierEncoderBipartiteInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("A1", List.of("R")); encoder.encode("A2", List.of("R")); encoder.encode("A3", List.of("R")); @@ -263,9 +263,9 @@ public void testHierEncoderBipartiteInheritance() { @Test public void testHierEncoderBipartiteInheritanceDiffOrder() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("B1", List.of("R")); encoder.encode("B2", List.of("R")); @@ -296,9 +296,9 @@ public void testHierEncoderBipartiteInheritanceDiffOrder() { @Test public void testSquare() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "T", Collections.EMPTY_LIST ); + encoder.encode( "T", Collections.emptyList()); encoder.encode("A", List.of("T")); encoder.encode("B", List.of("T")); encoder.encode( "C", Arrays.asList( "A", "B" ) ); @@ -319,9 +319,9 @@ public void testSquare() { @Test public void testConflictArising() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("A")); encoder.encode("D", List.of("B")); @@ -362,9 +362,9 @@ public void testConflictArising() { @Test public void testConflictArising2() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("A")); encoder.encode("D", List.of("B")); @@ -391,9 +391,9 @@ public void testConflictArising2() { @Test public void testHierEncoderBipartiteStarInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("B1", List.of("R")); encoder.encode("B2", List.of("R")); @@ -434,9 +434,9 @@ public void testHierEncoderBipartiteStarInheritance() { @Test public void testHierEncoderBipartiteStarInheritanceDiffOrder() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("A1", List.of("R")); encoder.encode("A2", List.of("R")); @@ -491,9 +491,9 @@ private BitSet parseBitSet( String s ) { @Test public void testHierEncoderComplexInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); checkHier( encoder, 'A' ); encoder.encode("B", List.of("A")); @@ -547,7 +547,7 @@ public void testHierEncoderComplexInheritance() { BitSet ns = iter.next(); Long next = toLong( ns ); LOGGER.debug( next.toString() ); - assertThat(next > last).isTrue(); + assertThat(next).isGreaterThan(last); last = next; } } @@ -562,12 +562,12 @@ private Long toLong( BitSet ns ) { return l; } - private void checkHier( HierarchyEncoder encoder, char fin ) { + private void checkHier( HierarchyEncoder encoder, char fin ) { List[] sups = new ArrayList[ fin - 'A' + 1 ]; for ( int j = 'A'; j <= fin; j++ ) { - sups[ j - 'A' ] = ((HierarchyEncoderImpl) encoder).ancestorValues( "" + (char) j ); + sups[ j - 'A' ] = ((HierarchyEncoderImpl) encoder).ancestorValues( "" + (char) j ); }; for ( int j = 'A' ; j < 'A' + sups.length ; j++ ) { @@ -577,7 +577,7 @@ private void checkHier( HierarchyEncoder encoder, char fin ) { BitSet xcode = encoder.getCode( x ); BitSet ycode = encoder.getCode( y ); - int subOf = ((HierarchyEncoderImpl) encoder).superset(xcode, ycode); + int subOf = ((HierarchyEncoderImpl) encoder).superset(xcode, ycode); if ( x.equals( y ) ) { assertThat(subOf).as(x + " vs " + y).isEqualTo(0); @@ -600,9 +600,9 @@ private void checkHier( HierarchyEncoder encoder, char fin ) { @Test public void testHierEncoderMoreInheritance() { - HierarchyEncoderImpl encoder = new HierarchyEncoderImpl(); + HierarchyEncoderImpl encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("A")); encoder.encode("D", List.of("A")); @@ -656,9 +656,9 @@ public void testHierEncoderMoreInheritance() { @Test public void testSecondOrderInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "T", Collections.EMPTY_LIST ); + encoder.encode( "T", Collections.emptyList()); encoder.encode("A", List.of("T")); encoder.encode("B", List.of("T")); encoder.encode("C", List.of("T")); @@ -672,8 +672,8 @@ public void testSecondOrderInheritance() { LOGGER.debug( encoder.toString() ); - assertThat(((HierarchyEncoderImpl) encoder).superset(encoder.getCode("Z"), encoder.getCode("F")) < 0).isTrue() ; - assertThat(((HierarchyEncoderImpl) encoder).superset(encoder.getCode("F"), encoder.getCode("Z")) < 0).isTrue() ; + assertThat(((HierarchyEncoderImpl) encoder).superset(encoder.getCode("Z"), encoder.getCode("F"))).isLessThan(0); + assertThat(((HierarchyEncoderImpl) encoder).superset(encoder.getCode("F"), encoder.getCode("Z"))).isLessThan(0); } @@ -682,9 +682,9 @@ public void testSecondOrderInheritance() { @Test public void testDecoderAncestors() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "Thing", Collections.EMPTY_LIST ); + encoder.encode( "Thing", Collections.emptyList()); encoder.encode("A", List.of("Thing")); encoder.encode("Z", List.of("Thing")); encoder.encode( "B", Arrays.asList( "A", "Z" ) ); @@ -701,96 +701,96 @@ public void testDecoderAncestors() { LOGGER.debug( encoder.toString() ); BitSet b; - Collection x; + Collection x; b = parseBitSet( "1100111" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("Q")).isTrue(); - assertThat(x.contains("T")).isTrue(); - assertThat(x.contains("R")).isTrue(); - assertThat(x.contains("S")).isTrue(); - assertThat(x.contains("M")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); - assertThat(x.size()).isEqualTo(9); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); + assertThat(x).contains("C"); + assertThat(x).contains("Q"); + assertThat(x).contains("T"); + assertThat(x).contains("R"); + assertThat(x).contains("S"); + assertThat(x).contains("M"); + assertThat(x).contains("Thing"); + assertThat(x).hasSize(9); b = parseBitSet( "100000" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("Q")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("Q"); + assertThat(x).contains("Thing"); b = parseBitSet( "1111" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(6); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("B")).isTrue(); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("N")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(6); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); + assertThat(x).contains("B"); + assertThat(x).contains("C"); + assertThat(x).contains("N"); + assertThat(x).contains("Thing"); b = parseBitSet( "111" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(4); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(4); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); + assertThat(x).contains("C"); + assertThat(x).contains("Thing"); b = parseBitSet( "1" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("A"); + assertThat(x).contains("Thing"); b = parseBitSet( "10" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("Z"); + assertThat(x).contains("Thing"); b = parseBitSet( "0" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("Thing"); b = parseBitSet( "1011" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(4); - assertThat(x.contains("Thing")).isTrue(); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("B")).isTrue(); - assertThat(x.contains("Z")).isTrue(); + assertThat(x).hasSize(4); + assertThat(x).contains("Thing"); + assertThat(x).contains("A"); + assertThat(x).contains("B"); + assertThat(x).contains("Z"); } @Test public void testDecoderDescendants() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "Thing", Collections.EMPTY_LIST ); + encoder.encode( "Thing", Collections.emptyList()); encoder.encode("A", List.of("Thing")); encoder.encode("Z", List.of("Thing")); encoder.encode( "B", Arrays.asList( "A", "Z" ) ); @@ -806,40 +806,37 @@ public void testDecoderDescendants() { LOGGER.debug( encoder.toString() ); - BitSet b; - Collection x; - - b = parseBitSet( "111" ); - x = encoder.lowerDescendants(b); + BitSet b = parseBitSet( "111" ); + Collection x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(3); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("N")).isTrue(); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(3); + assertThat(x).contains("C"); + assertThat(x).contains("N"); + assertThat(x).contains("T"); b = parseBitSet( "10" ); x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(5); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("N")).isTrue(); - assertThat(x.contains("T")).isTrue(); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("B")).isTrue(); + assertThat(x).hasSize(5); + assertThat(x).contains("C"); + assertThat(x).contains("N"); + assertThat(x).contains("T"); + assertThat(x).contains("Z"); + assertThat(x).contains("B"); b = parseBitSet( "100000" ); x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(4); - assertThat(x.contains("Q")).isTrue(); - assertThat(x.contains("T")).isTrue(); - assertThat(x.contains("M")).isTrue(); - assertThat(x.contains("O")).isTrue(); + assertThat(x).hasSize(4); + assertThat(x).contains("Q"); + assertThat(x).contains("T"); + assertThat(x).contains("M"); + assertThat(x).contains("O"); @@ -848,45 +845,45 @@ public void testDecoderDescendants() { x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("T"); b = parseBitSet( "1111" ); x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("N")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("N"); b = parseBitSet( "1" ); x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(5); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("B")).isTrue(); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("N")).isTrue(); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(5); + assertThat(x).contains("A"); + assertThat(x).contains("B"); + assertThat(x).contains("C"); + assertThat(x).contains("N"); + assertThat(x).contains("T"); LOGGER.debug(" +*******************************+ "); x = encoder.lowerDescendants(new BitSet()); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(13); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(13); + assertThat(x).contains("Z"); + assertThat(x).contains("Thing"); } @Test public void testHierEncoderDecoderLower() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "Thing", Collections.EMPTY_LIST ); + encoder.encode( "Thing", Collections.emptyList()); encoder.encode("A", List.of("Thing")); encoder.encode("Z", List.of("Thing")); encoder.encode( "B", Arrays.asList( "A", "Z" ) ); @@ -902,31 +899,31 @@ public void testHierEncoderDecoderLower() { LOGGER.debug( encoder.toString() ); - Collection x; + Collection x; x = encoder.lowerBorder( encoder.metMembersCode(List.of("B"))); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("B")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("B"); x = encoder.immediateChildren( encoder.metMembersCode(List.of("B"))); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("N")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("N"); x = encoder.lowerBorder( encoder.metMembersCode( Arrays.asList( "Z", "Q" ) ) ); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("T"); x = encoder.immediateChildren( encoder.metMembersCode( Arrays.asList( "Z", "Q" ) ) ); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("T"); @@ -934,16 +931,16 @@ public void testHierEncoderDecoderLower() { x = encoder.lowerBorder( encoder.metMembersCode( Arrays.asList( "A", "Z" ) ) ); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("B")).isTrue(); - assertThat(x.contains("C")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("B"); + assertThat(x).contains("C"); x = encoder.immediateChildren( encoder.metMembersCode( Arrays.asList( "A", "Z" ) ) ); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("B")).isTrue(); - assertThat(x.contains("C")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("B"); + assertThat(x).contains("C"); @@ -951,18 +948,18 @@ public void testHierEncoderDecoderLower() { x = encoder.lowerBorder( encoder.metMembersCode(List.of("Thing"))); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("Thing"); x = encoder.immediateChildren( encoder.metMembersCode(List.of("Thing"))); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(5); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("P")).isTrue(); - assertThat(x.contains("Q")).isTrue(); - assertThat(x.contains("R")).isTrue(); + assertThat(x).hasSize(5); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); + assertThat(x).contains("P"); + assertThat(x).contains("Q"); + assertThat(x).contains("R"); } @@ -970,9 +967,9 @@ public void testHierEncoderDecoderLower() { @Test public void testHierEncoderDecoderUpper() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "Thing", Collections.EMPTY_LIST ); + encoder.encode( "Thing", Collections.emptyList()); encoder.encode("A", List.of("Thing")); encoder.encode("Z", List.of("Thing")); encoder.encode( "B", Arrays.asList( "A", "Z" ) ); @@ -988,62 +985,60 @@ public void testHierEncoderDecoderUpper() { LOGGER.debug( encoder.toString() ); - Collection x; - - x = encoder.upperBorder( encoder.metMembersCode(List.of("B"))); + Collection x = encoder.upperBorder( encoder.metMembersCode(List.of("B"))); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("B")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("B"); x = encoder.immediateParents( encoder.metMembersCode(List.of("B"))); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); x = encoder.upperBorder( encoder.jointMembersCode( Arrays.asList( "Z", "Q" ) ) ); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("Thing"); x = encoder.immediateParents( encoder.jointMembersCode( Arrays.asList( "Z", "Q" ) ) ); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("Thing"); x = encoder.upperBorder( encoder.jointMembersCode( Arrays.asList( "B", "C" ) ) ); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); x = encoder.immediateParents( encoder.jointMembersCode( Arrays.asList( "B", "C" ) ) ); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); x = encoder.upperBorder( encoder.jointMembersCode(List.of("T"))); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("T"); x = encoder.immediateParents( encoder.jointMembersCode(List.of("T"))); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("Q")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("C"); + assertThat(x).contains("Q"); } @@ -1057,7 +1052,7 @@ public void testHierEncoderDecoderUpper() { public void testClassInstanceHierarchies() { HierarchyEncoder encoder = new HierarchyEncoderImpl(); - BitSet ak = encoder.encode( "A", Collections.EMPTY_LIST ); + BitSet ak = encoder.encode( "A", Collections.emptyList()); BitSet bk = encoder.encode("B", List.of("A")); BitSet ck = encoder.encode("C", List.of("A")); BitSet dk = encoder.encode("D", List.of("B")); @@ -1139,7 +1134,7 @@ public void testClassInstanceHierarchies() { public void testUnwantedCodeOverriding() { HierarchyEncoder encoder = new HierarchyEncoderImpl(); - BitSet ak = encoder.encode( "A", Collections.EMPTY_LIST ); + BitSet ak = encoder.encode( "A", Collections.emptyList()); BitSet ck = encoder.encode("C", List.of("A")); BitSet dk = encoder.encode("D", List.of("A")); BitSet gk = encoder.encode( "G", Arrays.asList( "C", "D" ) ); @@ -1186,7 +1181,7 @@ public void testUnwantedCodeOverriding() { public void testDeepTree() { HierarchyEncoder encoder = new HierarchyEncoderImpl(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); @@ -1219,7 +1214,7 @@ public void testDeepTree() { public void testNestedTree() { HierarchyEncoder encoder = new HierarchyEncoderImpl(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("B")); encoder.encode("D", List.of("B")); From d577bd6cebff69a8f0d6cdb45c9db6c315188de2 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 14 Feb 2024 20:41:03 +0900 Subject: [PATCH 004/141] =?UTF-8?q?[DROOLS-7591]=20Experiment=20branch=20:?= =?UTF-8?q?=20migrate=20a=20new=20drools-lsp=20parser=20int=E2=80=A6=20(#5?= =?UTF-8?q?682)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * add antlr4 based drl parser * bump to drools 8.16.0.Beta * improve node position discovery * first c3 integration * Module reorganization (#2) * WIP * Ignore directories * Add debug. Minor modifications * WIP * Fix tests - add comments * manage null ast nodes and fix failing test * improve drl parser * Fix basic completion (#4) * Add Java grammar, fix DRL grammar, simplify token index calculation, remove template code * Add ignored tokens to completion Co-authored-by: livio * add constraints parsing * - Added DRLParserWrapper to store errors using DRLErrorListener (#5) - Added MiscDRLParserTest which is being ported from RuleParserTest to enhance coverage. * Enhance test/grammar coverage. function import, global, exists, not (#6) * Enhance test/grammar coverage. and, or, listExpression (#7) * Enhance test/grammar coverage. matches, single quoted string, escape (#9) - Introduced drlExpression, drlPrimary, drlLiteral, DRL_STRING_LITERAL * Enhance test/grammar coverage. dialect, invalid lhs (#10) * Enhance test/grammar coverage. keyword collision (#11) - Add "DRL_" prefix for DRL keywords for clarification * Enhance test/grammar coverage. function, attributes, consequence (#12) * Enhance test/grammar coverage. function, attributes, consequence - better getText preserving whitespaces - resolving WARNs because of overlapping keywords * - No need to declare duplicate keywords * Enhance test/grammar coverage. OR, inline map (#13) * OpenRewrite applied for junit5 and assertj (#14) * Enhance test/grammar coverage. label, consequenceLocation, test refac… (#15) * Enhance test/grammar coverage. label, consequenceLocation, test refactoring, assertj best practice * - better test method names * [DROOLS-7253] Review and improve drools-lsp parser Visitor design (#16) * [DROOLS-7253] Review and improve drools-lsp parser Visitor design - Remove currentConstructStack. Utilize return object instead. * - Remove instance fields. Utilize return objects instead. * [DROOLS-7270] Enhance test/grammar coverage : andRestriction, orRestriction (#4) - Removed some unused cast * [DROOLS-7271] Fully port RuleParserTest as MiscDRLParserTest with @Disabled and priority comment (#10) * [DROOLS-7285] Failed to parse and/or with parentheses in LHS (#15) * [DROOLS-7286] Failed to parse binding with || (#21) * [DROOLS-7287] Failed to parse comments in RHS (#23) * [DROOLS-7287] Failed to parse comments in RHS * - add rhs string check * [DROOLS-7515] Parser : Accept plain text in RHS (#26) * [DROOLS-7515] Parser : Accept plain text in RHS * - Handle keyword token in RHS * - Removed sysout * - Revert statementKeywords. Instead, define DRL_END with newline or EOF * - fix method name * [DROOLS-7288] Failed to parse complex parentheses (#27) * [DROOLS-7288] Failed to parse complex parentheses - bump to 8.43.0.Final * additional tests * [DROOLS-7289] Implement accumulate (#28) * [DROOLS-7296] Implement from entry-point (#30) * [DROOLS-7297] Implement import accumulate (#29) * [DROOLS-7290] Implement BigInteger literal, BigDecimal literal (#31) * [DROOLS-7292] Implement eval (#32) * [DROOLS-7293] Implement extends (#33) * [DROOLS-7294] Implement forall (#34) * [DROOLS-7298] Implement memberOf (#35) * [DROOLS-7300] Implement positional constraint (#36) * [DROOLS-7304] Implement temporal operators (#38) - Also covers [DROOLS-7303] Implement sliding window * [DROOLS-7301] Implement query (#37) - Also partially fixes [DROOLS-7302] Implement semicolon delimiter * [DROOLS-7295] Implement from collect (#39) * [DROOLS-7305] Implement type declaration (#40) - also covers [DROOLS-7291] Implement entry-point declaration - also covers window declaration * [DROOLS-7306] Implement unification (#41) * [DROOLS-7306] Implement unification - Also [DROOLS-7307] Parse attribute agenda-group * [DROOLS-7308] Parse attribute without value - Also [DROOLS-7309] Parse attribute with parentheses * [DROOLS-7310] parse nested parentheses (#42) * [DROOLS-7310] parse nested parentheses * - Adding code commentes and explanations - Adding more nested level tests * [DROOLS-7577] drools-lsp : Add comments and explanations for drools-p… (#43) * [DROOLS-7577] drools-lsp : Add comments and explanations for drools-parser * removed syntax examples * [DROOLS-7591] Experiment branch : migrate a new drools-lsp parser into drools (#44) - Add some methods to call from drools code base * Move necessary files without any additional modifications * Update DRL6Expressions.g4 to ANTLR 4 (#47) * Add DescrDumperTest and fix the expression parser grammar (#48) * Add DescrDumperTest * Fix it * [DROOLS-7591] Experiment branch : migrate a new drools-lsp parser into drools - New parser is migrated in drools-drl/drools-drl-parser with org.drools.drl10.parser package - To enable the new parser, run `mvn test -PDRL10` - At the moment, we get lots of test failures especially in drools-model/drools-model-codegen and drools-test-coverage/test-compiler-integration * - License header - Revert an inappropriate test edit - Removed unnecessary profile - Clarify unsupported methods - Removed unnecessary bom dependency --------- Co-authored-by: mariofusco Co-authored-by: Gabriele Cardosi Co-authored-by: Livio Benčik Co-authored-by: livio Co-authored-by: Jiří Locker --- ...nowledgeBuilderRulesConfigurationImpl.java | 1 - .../org/drools/compiler/lang/DescrDumper.java | 3 +- .../compiler/rule/builder/PatternBuilder.java | 3 +- .../rule/builder/QueryElementBuilder.java | 5 +- drools-drl/drools-drl-parser-tests/pom.xml | 81 + .../drl10/parser/DRLExprParserTest.java | 271 ++ .../drools/drl10/parser/DRLParserTest.java | 95 + .../drools/drl10/parser/DescrDumperTest.java | 368 ++ .../drl10/parser/MiscDRLParserTest.java | 3443 +++++++++++++++++ .../src/test/resources/logback-test.xml | 16 + .../drools/drl10/parser/Rule_with_Extends.drl | 25 + .../drl10/parser/Rule_with_Metadata.drl | 27 + .../drl10/parser/Rule_with_nested_LHS.drl | 28 + .../org/drools/drl10/parser/accumulate.drl | 25 + .../parser/accumulateExternalFunction.drl | 23 + .../parser/accumulateMultipleFunctions.drl | 30 + .../accumulateMultipleFunctionsConstraint.drl | 32 + .../drools/drl10/parser/accumulateReverse.drl | 26 + .../drl10/parser/accumulate_multi_pattern.drl | 25 + .../drl10/parser/accumulate_with_bindings.drl | 25 + .../parser/accumulate_with_nested_from.drl | 25 + .../drools/drl10/parser/almost_empty_rule.drl | 22 + .../org/drools/drl10/parser/and_or_rule.drl | 27 + .../org/drools/drl10/parser/autofocus.drl | 25 + .../org/drools/drl10/parser/basic_binding.drl | 27 + .../org/drools/drl10/parser/bindings.drl | 29 + .../drl10/parser/brackets_precedence.drl | 23 + .../org/drools/drl10/parser/collect.drl | 22 + .../drl10/parser/collect_with_nested_from.drl | 24 + .../org/drools/drl10/parser/comment.drl | 32 + .../org/drools/drl10/parser/complex.dsl | 5 + .../parser/declaration-in-consequence.drl | 48 + .../drl10/parser/declare_type_with_fields.drl | 35 + .../org/drools/drl10/parser/empty_rule.drl | 23 + .../org/drools/drl10/parser/enumeration.drl | 23 + .../drl10/parser/eol_funny_business.drl | 37 + .../drools/drl10/parser/escaped-string.drl | 23 + .../org/drools/drl10/parser/eval_multiple.drl | 26 + .../org/drools/drl10/parser/eval_parsing.drl | 26 + .../drools/drl10/parser/eval_with_newline.drl | 38 + .../parser/expander_multiple_constraints.dslr | 18 + .../expander_multiple_constraints_flush.dslr | 17 + .../drl10/parser/expander_spread_lines.dslr | 19 + .../drools/drl10/parser/extra_lhs_newline.drl | 27 + .../org/drools/drl10/parser/forall.drl | 23 + .../drools/drl10/parser/forallwithfrom.drl | 23 + .../org/drools/drl10/parser/from.drl | 31 + .../drools/drl10/parser/function_arrays.drl | 31 + .../org/drools/drl10/parser/functions.drl | 43 + .../org/drools/drl10/parser/globals.drl | 30 + .../drools/drl10/parser/in_operator_test.drl | 26 + .../drl10/parser/lhs_semicolon_delim.drl | 29 + .../parser/literal_bool_and_negative.drl | 27 + .../drl10/parser/multiple_constraints.dsl | 6 + .../drools/drl10/parser/multiple_rules.drl | 34 + .../parser/nested_conditional_elements.drl | 27 + .../org/drools/drl10/parser/no-loop.drl | 25 + .../drl10/parser/not_exist_with_brackets.drl | 26 + .../drl10/parser/not_with_constraint.drl | 31 + .../drl10/parser/notin_operator_test.drl | 26 + .../org/drools/drl10/parser/or_binding.drl | 27 + .../drl10/parser/or_binding_complex.drl | 27 + .../drl10/parser/or_binding_with_brackets.drl | 25 + .../org/drools/drl10/parser/or_ce.drl | 26 + .../org/drools/drl10/parser/or_nesting.drl | 27 + .../drl10/parser/package_attributes.drl | 40 + .../drl10/parser/pluggable_operators.drl | 28 + .../drl10/parser/qualified_classname.drl | 25 + .../drools/drl10/parser/query_and_rule.drl | 47 + .../drl10/parser/quoted_string_name_rule.drl | 21 + .../drools/drl10/parser/restrictions_test.drl | 26 + .../drools/drl10/parser/rule_attributes.drl | 33 + .../drools/drl10/parser/rule_attributes2.drl | 46 + .../drl10/parser/rule_attributes_alt.drl | 28 + .../drl10/parser/rule_calendars_attribute.drl | 26 + .../parser/rule_calendars_attribute2.drl | 26 + .../drl10/parser/rule_duration_expression.drl | 26 + .../drl10/parser/rule_enabled_expression.drl | 27 + .../drl10/parser/rule_names_number_prefix.drl | 27 + .../org/drools/drl10/parser/rule_not.drl | 24 + .../org/drools/drl10/parser/ruleflowgroup.drl | 25 + .../org/drools/drl10/parser/semicolon.drl | 43 + .../org/drools/drl10/parser/simple_query.drl | 25 + .../org/drools/drl10/parser/simple_rule.drl | 29 + .../drl10/parser/soundslike_operator.drl | 30 + .../drl10/parser/statement_ordering_1.drl | 45 + .../drl10/parser/ternary_expression.drl | 26 + .../test_CommentLineNumbersInConsequence.drl | 34 + .../test_ComplexChainedCallWithFrom.drl | 24 + .../drools/drl10/parser/test_EmptyPattern.drl | 26 + .../drools/drl10/parser/test_EndPosition.drl | 27 + .../drl10/parser/test_FunctionImport.drl | 29 + .../parser/test_SimpleAccessorArgWithFrom.drl | 27 + .../parser/test_SimpleAccessorWithFrom.drl | 27 + .../test_SimpleFunctionCallWithFrom.drl | 27 + .../parser/test_SimpleMethodCallWithFrom.drl | 27 + .../drools/drl10/parser/type_with_meta.drl | 48 + .../org/drools/drl10/parser/with_eval.drl | 26 + .../drools/drl10/parser/with_predicate.drl | 23 + .../org/drools/drl10/parser/with_retval.drl | 23 + drools-drl/drools-drl-parser/pom.xml | 45 + .../drools/drl10/parser/DRL6Expressions.g4 | 847 ++++ .../org/drools/drl10/parser/DRLLexer.g4 | 161 + .../org/drools/drl10/parser/DRLParser.g4 | 495 +++ .../org/drools/drl10/parser/JavaLexer.g4 | 245 ++ .../org/drools/drl10/parser/JavaParser.g4 | 752 ++++ .../org/drools/drl/parser/DRLFactory.java | 3 + .../org/drools/drl/parser/Drl6ExprParser.java | 90 + .../org/drools/drl/parser/DrlExprParser.java | 56 +- .../drl/parser/DrlExprParserFactory.java | 20 + .../java/org/drools/drl/parser/DrlParser.java | 35 +- .../drools/drl/parser/lang/DRL10Lexer.java | 46 + .../drools/drl10/parser/DRLErrorListener.java | 49 + .../drools/drl10/parser/DRLExpressions.java | 61 + .../drools/drl10/parser/DRLParserError.java | 75 + .../drl10/parser/DRLParserException.java | 30 + .../drools/drl10/parser/DRLParserHelper.java | 126 + .../drools/drl10/parser/DRLParserWrapper.java | 85 + .../drools/drl10/parser/DRLVisitorImpl.java | 845 ++++ .../drools/drl10/parser/Developer_Notes.md | 38 + .../drools/drl10/parser/Drl10ExprParser.java | 87 + .../parser/DroolsParserExceptionFactory.java | 250 ++ .../org/drools/drl10/parser/ParserHelper.java | 678 ++++ .../drl10/parser/ParserStringUtils.java | 81 + drools-drl/pom.xml | 1 + .../mvel/compiler/lang/DRLExprParserTest.java | 3 +- .../mvel/compiler/lang/DescrDumperTest.java | 3 +- .../mvel/integrationtests/AlphaNodeTest.java | 2 + .../visitor/ExprConstraintDescrVisitor.java | 3 +- .../builder/conf/LanguageLevelOption.java | 2 +- pom.xml | 22 + 131 files changed, 11957 insertions(+), 63 deletions(-) create mode 100644 drools-drl/drools-drl-parser-tests/pom.xml create mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java create mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java create mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java create mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declare_type_with_fields.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/empty_rule.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/enumeration.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eol_funny_business.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/escaped-string.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_multiple.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_parsing.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_with_newline.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints.dslr create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints_flush.dslr create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_spread_lines.dslr create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/extra_lhs_newline.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forall.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl create mode 100644 drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 create mode 100644 drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 create mode 100644 drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 create mode 100644 drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 create mode 100644 drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java diff --git a/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java b/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java index 0c90262aa28..48e3e4971f1 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java @@ -127,7 +127,6 @@ public KnowledgeBuilderRulesConfigurationImpl(CompositeConfiguration + + + + 4.0.0 + + org.drools + drools-drl + 999-SNAPSHOT + + + org.drools + drools-drl-parser-tests + + Drools :: DRL :: Parser :: Tests + + + org.drools.drl.parser.tests + + + + + + org.assertj + assertj-core + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + ch.qos.logback + logback-classic + test + + + + org.drools + drools-drl-parser + test + + + org.drools + drools-compiler + test + + + org.drools + drools-mvel + test + + + + diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java new file mode 100644 index 00000000000..1f27a9c861e --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java @@ -0,0 +1,271 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.drools.drl.ast.descr.AtomicExprDescr; +import org.drools.drl.ast.descr.BindingDescr; +import org.drools.drl.ast.descr.ConnectiveType; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.ast.descr.RelationalExprDescr; +import org.drools.drl.parser.DrlExprParser; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * DRLExprTreeTest + */ +public class DRLExprParserTest { + + DrlExprParser parser; + + @BeforeEach + public void setUp() throws Exception { + this.parser = new Drl10ExprParser(LanguageLevelOption.DRL6); + } + + @AfterEach + public void tearDown() throws Exception { + this.parser = null; + } + + @Test + public void testSimpleExpression() throws Exception { + String source = "a > b"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + } + + @Test + public void testAndConnective() throws Exception { + String source = "a > b && 10 != 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + + expr = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("!="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("10"); + assertThat(right.getExpression()).isEqualTo("20"); + } + + @Test + public void testConnective2() throws Exception { + String source = "(a > b || 10 != 20) && someMethod(10) == 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get( 0 ); + assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); + assertThat(or.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + + expr = (RelationalExprDescr) or.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("!="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("10"); + assertThat(right.getExpression()).isEqualTo("20"); + + expr = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod(10)"); + assertThat(right.getExpression()).isEqualTo("20"); + + } + + @Test + public void testBinding() throws Exception { + String source = "$x : property"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + } + + @Test + public void testBindingConstraint() throws Exception { + String source = "$x : property > value"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + RelationalExprDescr rel = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(rel.getOperator()).isEqualTo(">"); + + BindingDescr bind = (BindingDescr) rel.getLeft(); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + + AtomicExprDescr right = (AtomicExprDescr) rel.getRight(); + assertThat(right.getExpression()).isEqualTo("value"); + } + + @Test + public void testBindingWithRestrictions() throws Exception { + String source = "$x : property > value && < 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr rel = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(rel.getOperator()).isEqualTo(">"); + + BindingDescr bind = (BindingDescr) rel.getLeft(); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + + AtomicExprDescr right = (AtomicExprDescr) rel.getRight(); + assertThat(right.getExpression()).isEqualTo("value"); + + rel = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(rel.getOperator()).isEqualTo("<"); + + AtomicExprDescr left = (AtomicExprDescr) rel.getLeft(); + assertThat(left.getExpression()).isEqualTo("property"); + + right = (AtomicExprDescr) rel.getRight(); + assertThat(right.getExpression()).isEqualTo("20"); + } + + @Test + public void testDoubleBinding() throws Exception { + String source = "$x : x.m( 1, a ) && $y : y[z].foo"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("x.m( 1, a )"); + + bind = (BindingDescr) result.getDescrs().get( 1 ); + assertThat(bind.getVariable()).isEqualTo("$y"); + assertThat(bind.getExpression()).isEqualTo("y[z].foo"); + } + + @Test + public void testDeepBinding() throws Exception { + String source = "($a : a > $b : b[10].prop || 10 != 20) && $x : someMethod(10) == 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get( 0 ); + assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); + assertThat(or.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + BindingDescr leftBind = (BindingDescr) expr.getLeft(); + BindingDescr rightBind = (BindingDescr) expr.getRight(); + assertThat(leftBind.getVariable()).isEqualTo("$a"); + assertThat(leftBind.getExpression()).isEqualTo("a"); + assertThat(rightBind.getVariable()).isEqualTo("$b"); + assertThat(rightBind.getExpression()).isEqualTo("b[10].prop"); + + expr = (RelationalExprDescr) or.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("!="); + AtomicExprDescr leftExpr = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr rightExpr = (AtomicExprDescr) expr.getRight(); + assertThat(leftExpr.getExpression()).isEqualTo("10"); + assertThat(rightExpr.getExpression()).isEqualTo("20"); + + expr = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("=="); + leftBind = (BindingDescr) expr.getLeft(); + rightExpr = (AtomicExprDescr) expr.getRight(); + assertThat(leftBind.getVariable()).isEqualTo("$x"); + assertThat(leftBind.getExpression()).isEqualTo("someMethod(10)"); + assertThat(rightExpr.getExpression()).isEqualTo("20"); + + } + + @Test + @Timeout(10000L) + public void testNestedExpression() throws Exception { + // DROOLS-982 + String source = "(((((((((((((((((((((((((((((((((((((((((((((((((( a > b ))))))))))))))))))))))))))))))))))))))))))))))))))"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + } +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java new file mode 100644 index 00000000000..35c4638ebc1 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java @@ -0,0 +1,95 @@ +package org.drools.drl10.parser; + +import java.util.List; + +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.drools.drl10.parser.DRLParserHelper.computeTokenIndex; +import static org.drools.drl10.parser.DRLParserHelper.createDrlParser; +import static org.drools.drl10.parser.DRLParserHelper.parse; + +class DRLParserTest { + + private static final String drl = + "package org.test;\n" + + "import org.test.model.Person;\n" + + "global String result;\n" + + "rule TestRule @Test(true) no-loop salience 15 when \n" + + " $p:Person( age >= 18 )\n" + + "then\n" + + " int a = 4;\n" + + " System.out.println($p.getName());\n" + + "end\n"; + + @Test + void parse_basicRule() { + PackageDescr packageDescr = parse(drl); + assertThat(packageDescr.getName()).isEqualTo("org.test"); + + assertThat(packageDescr.getImports().size()).isEqualTo(1); + assertThat(packageDescr.getImports().get(0).getTarget()).isEqualTo("org.test.model.Person"); + + assertThat(packageDescr.getGlobals().size()).isEqualTo(1); + GlobalDescr globalDescr = packageDescr.getGlobals().get(0); + assertThat(globalDescr.getType()).isEqualTo("String"); + assertThat(globalDescr.getIdentifier()).isEqualTo("result"); + + assertThat(packageDescr.getRules().size()).isEqualTo(1); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + AnnotationDescr annotationDescr = ruleDescr.getAnnotation("Test"); + assertThat(annotationDescr).isNotNull(); + assertThat(annotationDescr.getValue()).isEqualTo("true"); + + assertThat(ruleDescr.getAttributes().size()).isEqualTo(2); + assertThat(ruleDescr.getAttributes().get("no-loop")).isNotNull(); + AttributeDescr salience = ruleDescr.getAttributes().get("salience"); + assertThat(salience).isNotNull(); + assertThat(salience.getValue()).isEqualTo("15"); + + assertThat(ruleDescr.getName()).isEqualTo("TestRule"); + + assertThat(ruleDescr.getLhs().getDescrs().size()).isEqualTo(1); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + assertThat(patternDescr.getIdentifier()).isEqualTo("$p"); + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + + List constraints = patternDescr.getConstraint().getDescrs(); + assertThat(constraints.size()).isEqualTo(1); + ExprConstraintDescr expr = (ExprConstraintDescr) constraints.get(0); + assertThat(expr.getExpression()).isEqualTo("age >= 18"); + + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int a = 4; System.out.println($p.getName());"); + } + + @Test + void computeTokenIndex_basicRule() { + DRLParser parser = createDrlParser(drl); + parser.compilationUnit(); + + assertThat((int) computeTokenIndex(parser, 1, 0)).isEqualTo(0); + assertThat((int) computeTokenIndex(parser, 1, 1)).isEqualTo(0); + assertThat((int) computeTokenIndex(parser, 1, 7)).isEqualTo(0); + assertThat((int) computeTokenIndex(parser, 1, 8)).isEqualTo(1); + assertThat((int) computeTokenIndex(parser, 1, 9)).isEqualTo(2); + assertThat((int) computeTokenIndex(parser, 1, 9)).isEqualTo(2); + assertThat((int) computeTokenIndex(parser, 1, 12)).isEqualTo(3); + assertThat((int) computeTokenIndex(parser, 1, 13)).isEqualTo(4); + assertThat((int) computeTokenIndex(parser, 1, 17)).isEqualTo(5); + assertThat((int) computeTokenIndex(parser, 1, 18)).isEqualTo(6); + assertThat((int) computeTokenIndex(parser, 2, 0)).isEqualTo(6); + assertThat((int) computeTokenIndex(parser, 2, 1)).isEqualTo(7); + assertThat((int) computeTokenIndex(parser, 2, 6)).isEqualTo(7); + assertThat((int) computeTokenIndex(parser, 2, 7)).isEqualTo(8); + // Skip RHS token assertion as it is fluid part at the moment. + } +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java new file mode 100644 index 00000000000..d98ec8ec895 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java @@ -0,0 +1,368 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.drools.compiler.lang.DescrDumper; +import org.drools.compiler.lang.DumperContext; +import org.drools.drl.ast.descr.AtomicExprDescr; +import org.drools.drl.ast.descr.BindingDescr; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.DrlExprParser; +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; + +public class DescrDumperTest { + + private DescrDumper dumper; + + @BeforeEach + public void setUp() throws Exception { + // configure operators + new SetEvaluatorsDefinition(); + new MatchesEvaluatorsDefinition(); + + dumper = new DescrDumper(); + } + + @Test + public void testDump() throws Exception { + String input = "price > 10 && < 20 || == $val || == 30"; + String expected = "( price > 10 && price < 20 || price == $val || price == 30 )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpMatches() throws Exception { + String input = "type.toString matches \"something\\swith\\tsingle escapes\""; + String expected = "type.toString ~= \"something\\swith\\tsingle escapes\""; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpMatches2() throws Exception { + String input = "type.toString matches 'something\\swith\\tsingle escapes'"; + String expected = "type.toString ~= \"something\\swith\\tsingle escapes\""; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpMatches3() throws Exception { + String input = "this[\"content\"] matches \"hello ;=\""; + String expected = "this[\"content\"] ~= \"hello ;=\""; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpContains() throws Exception { + String input = "list contains \"b\""; + String expected = "list contains \"b\""; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpContains2() throws Exception { + String input = "list not contains \"b\""; + String expected = "!( list contains \"b\" )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpExcludes() throws Exception { + String input = "list excludes \"b\""; + String expected = "!( list contains \"b\" )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpExcludes2() throws Exception { + String input = "list not excludes \"b\""; + String expected = "list contains \"b\""; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test @Disabled + public void testDumpWithDateAttr() throws Exception { + String input = "son.birthDate == \"01-jan-2000\""; + String expected = "son.birthDate == org.drools.util.DateUtils.parseDate( \"01-jan-2000\" )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpComplex() throws Exception { + String input = "a ( > 60 && < 70 ) || ( > 50 && < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\""; + String expected = "( ( a > 60 && a < 70 || a > 50 && a < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\" )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpBindings() throws Exception { + String input = "$x : property > value"; + String expected = "property > value"; + + ConstraintConnectiveDescr descr = parse( input ); + DumperContext ctx = new DumperContext(); + String result = dumper.dump( descr, + ctx ); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings().size()).isEqualTo(1); + BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + } + + @Test + public void testDumpBindings2() throws Exception { + String input = "( $a : a > $b : b[10].prop || 10 != 20 ) && $x : someMethod(10) == 20"; + String expected = "( a > b[10].prop || 10 != 20 ) && someMethod(10) == 20"; + + ConstraintConnectiveDescr descr = parse( input ); + DumperContext ctx = new DumperContext(); + String result = dumper.dump( descr, + ctx ); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings().size()).isEqualTo(3); + BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$a"); + assertThat(bind.getExpression()).isEqualTo("a"); + bind = ctx.getBindings().get( 1 ); + assertThat(bind.getVariable()).isEqualTo("$b"); + assertThat(bind.getExpression()).isEqualTo("b[10].prop"); + bind = ctx.getBindings().get( 2 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("someMethod(10)"); + } + + @Test + public void testDumpBindings3() throws Exception { + String input = "( $a : a > $b : b[10].prop || 10 != 20 ) && $x : someMethod(10)"; + String expected = "( a > b[10].prop || 10 != 20 )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpBindings4() throws Exception { + String input = "( $a : a > $b : b[10].prop || $x : someMethod(10) ) && 10 != 20"; + String expected = "( a > b[10].prop ) && 10 != 20"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpBindingsWithRestriction() throws Exception { + String input = "$x : age > 10 && < 20 || > 30"; + String expected = "( age > 10 && age < 20 || age > 30 )"; + + ConstraintConnectiveDescr descr = parse( input ); + DumperContext ctx = new DumperContext(); + String result = dumper.dump( descr, + ctx ); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings().size()).isEqualTo(1); + BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("age"); + } + + @Test + public void testDumpBindingsComplexOp() throws Exception { + String input = "$x : age in (10, 20, $someVal)"; + String expected = "( age == 10 || age == 20 || age == $someVal )"; + + ConstraintConnectiveDescr descr = parse( input ); + DumperContext ctx = new DumperContext(); + String result = dumper.dump( descr, + ctx ); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings().size()).isEqualTo(1); + BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("age"); + } + + @Test + public void testDumpBindingsComplexOp2() throws Exception { + String input = "$x : age not in (10, 20, $someVal)"; + String expected = "age != 10 && age != 20 && age != $someVal"; + + ConstraintConnectiveDescr descr = parse( input ); + DumperContext ctx = new DumperContext(); + String result = dumper.dump( descr, + ctx ); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings().size()).isEqualTo(1); + BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("age"); + } + + @Test + public void testProcessInlineCast() throws Exception { + String expr = "field1#Class.field2"; + String expectedInstanceof = "field1 instanceof Class"; + String expectedcasted = "((Class)field1).field2"; + AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); + ccd.addDescr( atomicExpr ); + String[] instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null); + assertThat(ccd.getDescrs().size()).isEqualTo(2); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedInstanceof); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedcasted); + + expr = "field1#Class1.field2#Class2.field3"; + String expectedInstanceof1 = "field1 instanceof Class1"; + String expectedInstanceof2 = "((Class1)field1).field2 instanceof Class2"; + expectedcasted = "((Class2)((Class1)field1).field2).field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr( ); + instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedInstanceof1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedInstanceof2); + assertThat(instanceofAndCastedExpr[1]).isEqualTo(expectedcasted); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedcasted); + } + + @Test + public void testProcessNullSafeDereferencing() throws Exception { + String expr = "field1!.field2"; + String expectedNullCheck = "field1 != null"; + String expectedExpr = "field1.field2"; + AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); + String[] nullCheckAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedNullCheck); + assertThat(nullCheckAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + + expr = "field1!.field2!.field3"; + String expectedNullCheck1 = "field1 != null"; + String expectedNullCheck2 = "field1.field2 != null"; + expectedExpr = "field1.field2.field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr( ); + nullCheckAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedNullCheck1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedNullCheck2); + assertThat(nullCheckAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + } + + @Test + public void testProcessImplicitConstraints() throws Exception { + String expr = "field1#Class!.field2"; + String expectedConstraints = "field1 instanceof Class"; + String expectedExpr = "((Class)field1).field2"; + AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); + String[] constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints); + assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + + expr = "field1!.field2#Class.field3"; + String expectedConstraints1 = "field1 != null"; + String expectedConstraints2 = "field1.field2 instanceof Class"; + expectedExpr = "((Class)field1.field2).field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr( ); + constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedConstraints2); + assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + + expr = "field1#Class.field2!.field3"; + expectedConstraints1 = "field1 instanceof Class"; + expectedConstraints2 = "((Class)field1).field2 != null"; + expectedExpr = "((Class)field1).field2.field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr( ); + constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedConstraints2); + assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + } + + public ConstraintConnectiveDescr parse( final String constraint ) { + DrlExprParser parser = new Drl10ExprParser(LanguageLevelOption.DRL6); + ConstraintConnectiveDescr result = parser.parse( constraint ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + return result; + } + +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java new file mode 100644 index 00000000000..6353be53ac7 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java @@ -0,0 +1,3443 @@ +package org.drools.drl10.parser; + +import java.io.BufferedReader; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Pattern; + +import org.drools.drl.ast.descr.AccumulateDescr; +import org.drools.drl.ast.descr.AccumulateImportDescr; +import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.BehaviorDescr; +import org.drools.drl.ast.descr.CollectDescr; +import org.drools.drl.ast.descr.EntryPointDeclarationDescr; +import org.drools.drl.ast.descr.EntryPointDescr; +import org.drools.drl.ast.descr.EvalDescr; +import org.drools.drl.ast.descr.ExistsDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.ForallDescr; +import org.drools.drl.ast.descr.FromDescr; +import org.drools.drl.ast.descr.FunctionDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.ImportDescr; +import org.drools.drl.ast.descr.MVELExprDescr; +import org.drools.drl.ast.descr.NotDescr; +import org.drools.drl.ast.descr.OrDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.QueryDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.TypeDeclarationDescr; +import org.drools.drl.ast.descr.TypeFieldDescr; +import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl10.parser.DRLParserWrapper; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/* + * This test class is ported from org.drools.mvel.compiler.lang.RuleParserTest + */ +class MiscDRLParserTest { + + private DRLParserWrapper parser; + + @BeforeEach + public void setUp() { + parser = new DRLParserWrapper(); + } + + @AfterEach + public void tearDown() { + } + + private String readResource(final String filename) throws Exception { + Path path = Paths.get(getClass().getResource(filename).toURI()); + final StringBuilder sb = new StringBuilder(); + try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { + for (String line; (line = br.readLine()) != null; ) { + sb.append(line); + sb.append("\n"); + } + } catch (IOException e) { + e.printStackTrace(); + } + return sb.toString(); + } + + private RuleDescr parseAndGetFirstRuleDescr(String drl) { + PackageDescr pkg = parser.parse(drl); + assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); + assertThat(pkg.getRules()).isNotEmpty(); + return pkg.getRules().get(0); + } + + private RuleDescr parseAndGetFirstRuleDescrFromFile(String filename) throws Exception { + return parseAndGetFirstRuleDescr(readResource(filename)); + } + + private PackageDescr parseAndGetPackageDescrFromFile(String filename) throws Exception { + return parser.parse(readResource(filename)); + } + + private QueryDescr parseAndGetFirstQueryDescr(String drl) { + PackageDescr pkg = parser.parse(drl); + assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); + assertThat(pkg.getRules()).isNotEmpty(); + Optional optQuery = pkg.getRules().stream().filter(QueryDescr.class::isInstance).map(QueryDescr.class::cast).findFirst(); + assertThat(optQuery).isPresent(); + return optQuery.get(); + } + + private QueryDescr parseAndGetFirstQueryDescrFromFile(String filename) throws Exception { + return parseAndGetFirstQueryDescr(readResource(filename)); + } + + @Test + void parse_validPackage() { + final String source = "package foo.bar.baz"; + final PackageDescr pkg = parser.parse(source); + assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); + } + + @Test + void parse_packageWithErrorNode() { + final String source = "package 12 foo.bar.baz"; + final PackageDescr pkg = parser.parse(source); + assertThat(parser.hasErrors()).isTrue(); + assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); + } + + @Test + void parse_packageWithAllErrorNode() { + final String source = "package 12 12312 231"; + final PackageDescr pkg = parser.parse(source); + assertThat(parser.hasErrors()).isTrue(); + assertThat(pkg.getName()).isEmpty(); + } + + @Test + void parse_import() { + final String source = "package foo; import com.foo.Bar; import com.foo.Baz;"; + PackageDescr pkg = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(pkg.getName()).isEqualTo("foo"); + assertThat(pkg.getImports()).hasSize(2); + ImportDescr impdescr = pkg.getImports().get(0); + assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); + + impdescr = pkg.getImports().get(1); + assertThat(impdescr.getTarget()).isEqualTo("com.foo.Baz"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); + } + + @Test + void parse_functionImport() { + final String source = "package foo\n" + + "import function java.lang.Math.max\n" + + "import function java.lang.Math.min;\n" + + "import foo.bar.*\n" + + "import baz.Baz"; + PackageDescr pkg = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(pkg.getName()).isEqualTo("foo"); + assertThat(pkg.getImports()).hasSize(2); + ImportDescr impdescr = pkg.getImports().get(0); + assertThat(impdescr.getTarget()).isEqualTo("foo.bar.*"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); + + impdescr = pkg.getImports().get(1); + assertThat(impdescr.getTarget()).isEqualTo("baz.Baz"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); + + assertThat(pkg.getFunctionImports()).hasSize(2); + impdescr = pkg.getFunctionImports().get(0); + assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.max"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length() - 1); + + impdescr = pkg.getFunctionImports().get(1); + assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.min"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length()); + } + + @Test + void parse_globalWithComplexType() { + final String source = "package foo.bar.baz\n" + + "import com.foo.Bar\n" + + "global java.util.List> aList;\n" + + "global Integer aNumber"; + PackageDescr pkg = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); + assertThat(pkg.getImports()).hasSize(1); + + ImportDescr impdescr = pkg.getImports().get(0); + assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); + + assertThat(pkg.getGlobals()).hasSize(2); + + GlobalDescr global = pkg.getGlobals().get(0); + assertThat(global.getType()).isEqualTo("java.util.List>"); + assertThat(global.getIdentifier()).isEqualTo("aList"); + assertThat(global.getStartCharacter()).isEqualTo(source.indexOf("global " + global.getType())); + assertThat(global.getEndCharacter()).isEqualTo(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + + ("global " + global.getType() + " " + global.getIdentifier()).length()); + + global = pkg.getGlobals().get(1); + assertThat(global.getType()).isEqualTo("Integer"); + assertThat(global.getIdentifier()).isEqualTo("aNumber"); + assertThat(global.getStartCharacter()).isEqualTo(source.indexOf("global " + global.getType())); + assertThat(global.getEndCharacter()).isEqualTo(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + + ("global " + global.getType() + " " + global.getIdentifier()).length() - 1); + } + + @Test + void parse_globalWithOrWithoutSemi() throws Exception { + String source = readResource("globals.drl"); + PackageDescr pkg = parser.parse(source); + + assertThat(pkg.getRules()).hasSize(1); + + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + assertThat(pkg.getImports()).hasSize(1); + assertThat(pkg.getGlobals()).hasSize(2); + + final GlobalDescr foo = pkg.getGlobals().get(0); + assertThat(foo.getType()).isEqualTo("java.lang.String"); + assertThat(foo.getIdentifier()).isEqualTo("foo"); + final GlobalDescr bar = pkg.getGlobals().get(1); + assertThat(bar.getType()).isEqualTo("java.lang.Integer"); + assertThat(bar.getIdentifier()).isEqualTo("bar"); + } + + @Test + void parse_functionImportWithNotExist() throws Exception { + String source = readResource("test_FunctionImport.drl"); + PackageDescr pkg = parser.parse(source); + + assertThat(pkg.getFunctionImports()).hasSize(2); + + assertThat(pkg.getFunctionImports().get(0).getTarget()).isEqualTo("abd.def.x"); + assertThat(pkg.getFunctionImports().get(0).getStartCharacter()).isNotSameAs(-1); + assertThat(pkg.getFunctionImports().get(0).getEndCharacter()).isNotSameAs(-1); + assertThat(pkg.getFunctionImports().get(1).getTarget()).isEqualTo("qed.wah.*"); + assertThat(pkg.getFunctionImports().get(1).getStartCharacter()).isNotSameAs(-1); + assertThat(pkg.getFunctionImports().get(1).getEndCharacter()).isNotSameAs(-1); + } + + @Test + void parse_fromComplexAccessor() { + String source = "rule \"Invalid customer id\" ruleflow-group \"validate\" lock-on-active true \n" + + " when \n" + + " o: Order( ) \n" + + " not( Customer( ) from customerService.getCustomer(o.getCustomerId()) ) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); " + + "\n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parser.parse(source); + + assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("Invalid customer id"); + + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(1); + PatternDescr customer = (PatternDescr) not.getDescrs().get(0); + + assertThat(customer.getObjectType()).isEqualTo("Customer"); + assertThat(((FromDescr) customer.getSource()).getDataSource().getText()).isEqualTo("customerService.getCustomer(o.getCustomerId())"); + } + + @Test + void parse_fromWithInlineList() { + String source = "rule XYZ \n" + + " when \n" + + " o: Order( ) \n" + + " not( Number( ) from [1, 2, 3] ) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("XYZ"); + + PatternDescr number = (PatternDescr) ((NotDescr) rule.getLhs().getDescrs().get(1)).getDescrs().get(0); + assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3]"); + } + + @Test + void parse_fromWithInlineListMethod() { + String source = "rule XYZ \n" + + " when \n" + + " o: Order( ) \n" + + " Number( ) from [1, 2, 3].sublist(1, 2) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("XYZ"); + + assertThat(parser.hasErrors()).isFalse(); + PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); + + assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3].sublist(1, 2)"); + } + + @Test + void parse_fromWithInlineListIndex() { + String source = "rule XYZ \n" + + " when \n" + + " o: Order( ) \n" + + " Number( ) from [1, 2, 3][1] \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parser.parse(source); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("XYZ"); + + assertThat(parser.hasErrors()).isFalse(); + PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3][1]"); + } + + @Test + void parse_ruleWithoutEnd() { + String source = "rule \"Invalid customer id\" \n" + + " when \n" + + " o: Order( ) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n"; + parser.parse(source); + assertThat(parser.hasErrors()).isTrue(); + } + + @Test + void parse_orWithSpecialBind() { + String source = "rule \"A and (B or C or D)\" \n" + + " when \n" + + " pdo1 : ParametricDataObject( paramID == 101, stringValue == \"1000\" ) and \n" + + " pdo2 :(ParametricDataObject( paramID == 101, stringValue == \"1001\" ) or \n" + + " ParametricDataObject( paramID == 101, stringValue == \"1002\" ) or \n" + + " ParametricDataObject( paramID == 101, stringValue == \"1003\" )) \n" + + " then \n" + + " System.out.println( \"Rule: A and (B or C or D) Fired. pdo1: \" + pdo1 + \" pdo2: \"+ pdo2); \n" + + "end\n"; + PackageDescr pkg = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get(0); + AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs()).hasSize(2); + + PatternDescr pdo1 = (PatternDescr) lhs.getDescrs().get(0); + assertThat(pdo1.getIdentifier()).isEqualTo("pdo1"); + + OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(1); + assertThat(or.getDescrs()).hasSize(3); + for (BaseDescr pdo2 : or.getDescrs()) { + assertThat(((PatternDescr) pdo2).getIdentifier()).isEqualTo("pdo2"); + } + } + + @Test + void parse_compatibleRestriction() { + String source = "package com.sample rule test when Test( ( text == null || text2 matches \"\" ) ) then end"; + PackageDescr pkg = parser.parse(source); + + assertThat(pkg.getName()).isEqualTo("com.sample"); + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("test"); + ExprConstraintDescr expr = (ExprConstraintDescr) ((PatternDescr) rule.getLhs().getDescrs().get(0)).getDescrs().get(0); + assertThat(expr.getText()).isEqualTo("( text == null || text2 matches \"\" )"); + } + + @Test + void parse_simpleConstraint() { + String source = "package com.sample rule test when Cheese( type == 'stilton', price > 10 ) then end"; + PackageDescr pkg = parser.parse(source); + + assertThat(pkg.getName()).isEqualTo("com.sample"); + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("test"); + + assertThat(rule.getLhs().getDescrs()).hasSize(1); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + + AndDescr constraint = (AndDescr) pattern.getConstraint(); + assertThat(constraint.getDescrs()).hasSize(2); + assertThat(constraint.getDescrs().get(0)).hasToString("type == \"stilton\""); + assertThat(constraint.getDescrs().get(1)).hasToString("price > 10"); + } + + @Test + void parse_stringEscapes() { + String source = "package com.sample rule test when Cheese( type matches \"\\..*\\\\.\" ) then end"; + PackageDescr pkg = parser.parse(source); + assertThat(pkg.getName()).isEqualTo("com.sample"); + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("test"); + + assertThat(rule.getLhs().getDescrs()).hasSize(1); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + + AndDescr constraint = (AndDescr) pattern.getConstraint(); + assertThat(constraint.getDescrs()).hasSize(1); + assertThat(constraint.getDescrs().get(0)).hasToString("type matches \"\\..*\\\\.\""); + } + + @Test + void parse_dialectWithSingleQuotation() { + final String source = "dialect 'mvel'"; + PackageDescr pkg = parser.parse(source); + AttributeDescr attr = pkg.getAttributes().get(0); + assertThat(attr.getName()).isEqualTo("dialect"); + assertThat(attr.getValue()).isEqualTo("mvel"); + } + + @Test + void parse_dialectWithDoubleQuotation() { + final String source = "dialect \"mvel\""; + PackageDescr pkg = parser.parse(source); + AttributeDescr attr = pkg.getAttributes().get(0); + assertThat(attr.getName()).isEqualTo("dialect"); + assertThat(attr.getValue()).isEqualTo("mvel"); + } + + @Test + void parse_emptyRuleWithoutWhen() throws Exception { + String source = readResource("empty_rule.drl"); // without WHEN + parser.parse(source); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isTrue(); + + // Note : RuleParserTest.testEmptyRule allows this DRL, but I think is doesn't make sense to pass this DRL + } + + @Test + void parse_keywordCollisions() throws Exception { + String source = readResource("eol_funny_business.drl"); // keywords everywhere + + // Note: eol_funny_business.drl is modified from the one under drools-test-coverage to be more realistic. + // e.g. "package" is not allowed in a package value in Java, so it doesn't make sense to test. (Right to raise a parser error) + + PackageDescr pkg = parser.parse(source); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(pkg.getRules()).hasSize(1); + } + + @Test + void parse_ternaryExpression() throws Exception { + String source = readResource("ternary_expression.drl"); + PackageDescr pkg = parser.parse(source); + + final RuleDescr rule = pkg.getRules().get(0); + assertThat(pkg.getRules()).hasSize(1); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if (speed > speedLimit ? true : false;) pullEmOver();"); + } + + @Test + void parse_functionWithArrays() throws Exception { + String source = readResource("function_arrays.drl"); + + // Note: function_arrays.drl is modified from the one under drools-test-coverage to be more realistic. + // new String[3] {"a","b","c"} is invalid in Java (Cannot define dimension expressions when an array initializer is provided) + // , so it doesn't make sense to test. (Right to raise a parser error) + + PackageDescr pkg = parser.parse(source); + + assertThat(pkg.getName()).isEqualTo("foo"); + assertThat(pkg.getRules()).hasSize(1); + + final RuleDescr rule = pkg.getRules().get(0); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("yourFunction(new String[] {\"a\",\"b\",\"c\"});"); + + final FunctionDescr func = pkg.getFunctions().get(0); + + assertThat(func.getReturnType()).isEqualTo("String[]"); + assertThat(func.getParameterNames().get(0)).isEqualTo("args[]"); + assertThat(func.getParameterTypes().get(0)).isEqualTo("String"); + } + + @Test + void parse_almostEmptyRule() throws Exception { + String source = readResource("almost_empty_rule.drl"); + PackageDescr pkg = parser.parse(source); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(pkg).isNotNull(); + + RuleDescr rule = pkg.getRules().get(0); + + assertThat(rule.getName()).isEqualTo("almost_empty"); + assertThat(rule.getLhs()).isNotNull(); + assertThat(((String) rule.getConsequence()).trim()).isEmpty(); + } + + @Test + void parse_quotedStringNameRule() throws Exception { + String source = readResource("quoted_string_name_rule.drl"); + PackageDescr pkg = parser.parse(source); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("quoted string name"); + assertThat(rule.getLhs()).isNotNull(); + assertThat(((String) rule.getConsequence()).trim()).isEmpty(); + } + + @Test + void parse_noLoop() throws Exception { + String source = readResource("no-loop.drl"); + PackageDescr pkg = parser.parse(source); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("rule1"); + final AttributeDescr att = rule.getAttributes().get("no-loop"); + assertThat(att.getValue()).isEqualTo("false"); + assertThat(att.getName()).isEqualTo("no-loop"); + } + + @Test + void parse_autofocus() throws Exception { + String source = readResource("autofocus.drl"); + PackageDescr pkg = parser.parse(source); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("rule1"); + final AttributeDescr att = rule.getAttributes().get("auto-focus"); + assertThat(att.getValue()).isEqualTo("true"); + assertThat(att.getName()).isEqualTo("auto-focus"); + } + + @Test + void parse_ruleFlowGroup() throws Exception { + String source = readResource("ruleflowgroup.drl"); + PackageDescr pkg = parser.parse(source); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("rule1"); + final AttributeDescr att = rule.getAttributes().get("ruleflow-group"); + assertThat(att.getValue()).isEqualTo("a group"); + assertThat(att.getName()).isEqualTo("ruleflow-group"); + } + + @Test + void parse_consequenceWithDeclaration() throws Exception { + String source = readResource("declaration-in-consequence.drl"); + PackageDescr pkg = parser.parse(source); + + // Note : Removed "i\i;" from the original declaration-in-consequence.drl under drools-test-coverage + // because it's not a valid java expression and doesn't make sense to test. (Right to raise a parser error) + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("myrule"); + + final String expected = "int i = 0; i = 1; i / 1; i == 1; i(i); i = 'i'; i.i.i; ii; i=\"i\"; ++i;" + + "i++; --i; i--; i += i; i -= i; i *= i; i /= i;" + + "int i = 5;" + "for(int j; j 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("--") > 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("+=") > 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("==") > 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("i++") > 0).isTrue(); + // note, need to assert that "i++" is preserved as is, no extra spaces. + } + + @Test + void parse_or() { + final String text = "rule X when Person(age < 42, location==\"atlanta\") \nor\nPerson(name==\"bob\") then end"; + PackageDescr pkg = parser.parse(text); + RuleDescr rule = pkg.getRules().get(0); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(rule).isNotNull(); + + AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs()).hasSize(1); + assertThat(((OrDescr) lhs.getDescrs().get(0)).getDescrs()).hasSize(2); + } + + @Test + void parse_lhsWithStringQuotes() { + final String text = "rule X when Person( location==\"atlanta\\\"\") then end\n"; + PackageDescr pkg = parser.parse(text); + RuleDescr rule = pkg.getRules().get(0); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(rule).isNotNull(); + + AndDescr lhs = rule.getLhs(); + ExprConstraintDescr constr = (ExprConstraintDescr) ((PatternDescr) lhs.getDescrs().get(0)).getDescrs().get(0); + + assertThat(constr.getText()).isEqualToIgnoringWhitespace("location==\"atlanta\\\"\""); + } + + @Test + void parse_lhsWithStringQuotesEscapeChars() { + final String text = "rule X when Cheese( $x: type, type == \"s\\tti\\\"lto\\nn\" ) then end\n"; + PackageDescr pkg = parser.parse(text); + RuleDescr rule = pkg.getRules().get(0); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(rule).isNotNull(); + + AndDescr lhs = rule.getLhs(); + ExprConstraintDescr constr = (ExprConstraintDescr) ((PatternDescr) lhs.getDescrs().get(0)).getDescrs().get(1); + + assertThat(constr.getText()).isEqualToIgnoringWhitespace("type == \"s\\tti\\\"lto\\nn\""); + } + + @Test + void parse_literalBoolAndNegativeNumbersRule() throws Exception { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("literal_bool_and_negative.drl"); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs()).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("cons();"); + + final AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs()).hasSize(3); + + PatternDescr pattern = (PatternDescr) lhs.getDescrs().get(0); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + AndDescr fieldAnd = (AndDescr) pattern.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == false"); + + pattern = (PatternDescr) lhs.getDescrs().get(1); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + + fieldAnd = (AndDescr) pattern.getConstraint(); + fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + + assertThat(fld.getText()).isEqualToIgnoringWhitespace("boo > -42"); + + pattern = (PatternDescr) lhs.getDescrs().get(2); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + + fieldAnd = (AndDescr) pattern.getConstraint(); + fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + + assertThat(fld.getText()).isEqualToIgnoringWhitespace("boo > -42.42"); + } + + @Test + void parse_emptyPattern() throws Exception { + String source = readResource("test_EmptyPattern.drl"); + PackageDescr pkg = parser.parse(source); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr ruleDescr = pkg.getRules().get(0); + assertThat(ruleDescr.getName()).isEqualTo("simple rule"); + assertThat(ruleDescr.getLhs()).isNotNull(); + assertThat(ruleDescr.getLhs().getDescrs()).hasSize(1); + final PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + assertThat(patternDescr.getConstraint().getDescrs()).isEmpty(); // this + assertThat(patternDescr.getObjectType()).isEqualTo("Cheese"); + } + + @Test + void parse_simpleMethodCallWithFrom() throws Exception { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleMethodCallWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr method = (MVELExprDescr) from.getDataSource(); + + assertThat(method.getExpression()).isEqualToIgnoringWhitespace("something.doIt( foo,bar,42,\"hello\",[ a : \"b\", \"something\" : 42, \"a\" : foo, x : [x:y]],\"end\", [a, \"b\", 42] )"); + } + + @Test + void parse_simpleFunctionCallWithFrom() throws Exception { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleFunctionCallWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr func = (MVELExprDescr) from.getDataSource(); + + assertThat(func.getExpression()).isEqualToIgnoringWhitespace("doIt( foo,bar,42,\"hello\",[ a : \"b\", \"something\" : 42, \"a\" : foo, x : [x:y]],\"end\", [a, \"b\", 42] )"); + } + + @Test + void parse_simpleAccessorWithFrom() throws Exception { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleAccessorWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); + + assertThat(accessor.getExpression()).isEqualTo("something.doIt"); + } + + @Test + void parse_simpleAccessorAndArgWithFrom() throws Exception { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleAccessorArgWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); + + assertThat(accessor.getExpression()).isEqualTo("something.doIt[\"key\"]"); + } + + @Test + void parse_complexChainedAccessor() throws Exception { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_ComplexChainedCallWithFrom.drl"); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); + + assertThat(accessor.getExpression()).isEqualToIgnoringWhitespace("doIt1( foo,bar,42,\"hello\",[ a : \"b\"], [a, \"b\", 42] ).doIt2(bar, [a, \"b\", 42]).field[\"key\"]"); + } + + @Test + void parse_from() throws Exception { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("from.drl"); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("using_from"); + + assertThat(rule.getLhs().getDescrs()).hasSize(9); + } + + @Test + void parse_simpleRuleWithBindings() throws Exception { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("simple_rule.drl"); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + + assertThat(rule.getConsequenceLine()).isEqualTo(22); + assertThat(rule.getConsequencePattern()).isEqualTo(2); + + final AndDescr lhs = rule.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs()).hasSize(3); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + + assertThat(first.getConstraint().getDescrs()).hasSize(1); + + AndDescr fieldAnd = (AndDescr) first.getConstraint(); + ExprConstraintDescr constraint = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + assertThat(constraint).isNotNull(); + + assertThat(constraint.getExpression()).isEqualToIgnoringWhitespace("a==3"); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get(1); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + // no constraints, only a binding + fieldAnd = (AndDescr) second.getConstraint(); + assertThat(fieldAnd.getDescrs()).hasSize(1); + + final ExprConstraintDescr binding = (ExprConstraintDescr) second.getConstraint().getDescrs().get(0); + assertThat(binding.getExpression()).isEqualToIgnoringWhitespace("a4:a==4"); + + // Check third pattern + final PatternDescr third = (PatternDescr) lhs.getDescrs().get(2); + assertThat(third.getIdentifier()).isNull(); + assertThat(third.getObjectType()).isEqualTo("Baz"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if ( a == b ) { " + " assert( foo3 );" + "} else {" + " retract( foo4 );" + "}" + " System.out.println( a4 );"); + } + + @Test + void parse_multipleRestrictionsConstraint() throws Exception { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("restrictions_test.drl"); + assertThat(rule).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("consequence();"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + // The first pattern, with 2 restrictions on a single field (plus a + // connective) + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat( pattern.getConstraint().getDescrs()).hasSize(1); + + AndDescr and = (AndDescr) pattern.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + + // the second col, with 2 fields, the first with 2 restrictions, the + // second field with one + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); + + and = (AndDescr) pattern.getConstraint(); + fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace( "type == \"sedan\" || == \"wagon\""); + + // now the second field + fld = (ExprConstraintDescr) and.getDescrs().get( 1 ); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace( "age < 3"); + } + +//------------------------------------------------------------------------- +// DROOLS-7271 : ported from RuleParserTest +// Failing tests are annotated with @Disabled. We can fix issues one by one +//------------------------------------------------------------------------- + + @Disabled("Priority : Mid | implement Descr lineNumber") + @Test + public void parse_LineNumberInAST() throws Exception { + // also see testSimpleExpander to see how this works with an expander + // (should be the same). + + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "simple_rule.drl" ); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + + assertThat(rule.getConsequenceLine()).isEqualTo(22); + assertThat(rule.getConsequencePattern()).isEqualTo(2); + + final AndDescr lhs = rule.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs().size()).isEqualTo(3); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + final PatternDescr third = (PatternDescr) lhs.getDescrs().get( 2 ); + assertThat(third.getObjectType()).isEqualTo("Baz"); + + assertThat(first.getLine()).isEqualTo(19); + assertThat(second.getLine()).isEqualTo(20); + assertThat(third.getLine()).isEqualTo(21); + } + + @Test + public void parse_LineNumberIncludingCommentsInRHS() throws Exception { + PackageDescr pkg = parseAndGetPackageDescrFromFile( + "test_CommentLineNumbersInConsequence.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + final String rhs = (String) ((RuleDescr) pkg.getRules().get( 0 )).getConsequence(); + String expected = "\\s*//woot$\\s*first;$\\s*$\\s*//$\\s*$\\s*/\\* lala$\\s*$\\s*\\*/$\\s*second;$\\s*"; + assertThat(Pattern.compile(expected, + Pattern.DOTALL | Pattern.MULTILINE).matcher(rhs).matches()).isTrue(); + } + + @Test + public void parse_LhsSemicolonDelim() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "lhs_semicolon_delim.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + + final AndDescr lhs = rule.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs().size()).isEqualTo(3); + + // System.err.println( lhs.getDescrs() ); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + + assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); + + // LiteralDescr constraint = (LiteralDescr) first.getDescrs().get( 0 ); + AndDescr and = (AndDescr) first.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + assertThat(fld).isNotNull(); + + assertThat(fld.getExpression()).isEqualTo("a==3"); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + assertThat(second.getDescrs().size()).isEqualTo(1); + + final ExprConstraintDescr fieldBindingDescr = (ExprConstraintDescr) second.getDescrs().get( 0 ); + assertThat(fieldBindingDescr.getExpression()).isEqualTo("a4:a==4"); + + // Check third pattern + final PatternDescr third = (PatternDescr) lhs.getDescrs().get( 2 ); + assertThat(third.getIdentifier()).isNull(); + assertThat(third.getObjectType()).isEqualTo("Baz"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if ( a == b ) { " + " assert( foo3 );" + "} else {" + " retract( foo4 );" + "}" + " System.out.println( a4 );"); + } + + @Test + public void parse_NotNode() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_not.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(rule).isNotNull(); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + final AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + final NotDescr not = (NotDescr) lhs.getDescrs().get( 0 ); + assertThat(not.getDescrs().size()).isEqualTo(1); + final PatternDescr pattern = (PatternDescr) not.getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + + final AndDescr and = (AndDescr) pattern.getConstraint(); + final ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); + } + + @Test + public void parse_NotExistWithBrackets() throws Exception { + + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "not_exist_with_brackets.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + assertThat(rule).isNotNull(); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + final AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs().size()).isEqualTo(2); + final NotDescr not = (NotDescr) lhs.getDescrs().get( 0 ); + assertThat(not.getDescrs().size()).isEqualTo(1); + final PatternDescr pattern = (PatternDescr) not.getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + + final ExistsDescr ex = (ExistsDescr) lhs.getDescrs().get(1 ); + assertThat(ex.getDescrs().size()).isEqualTo(1); + final PatternDescr exPattern = (PatternDescr) ex.getDescrs().get( 0 ); + assertThat(exPattern.getObjectType()).isEqualTo("Foo"); + } + + @Test + public void parse_SimpleQuery() throws Exception { + final QueryDescr query = parseAndGetFirstQueryDescrFromFile( + "simple_query.drl" ); + + assertThat(query).isNotNull(); + + assertThat(query.getName()).isEqualTo("simple_query"); + + final AndDescr lhs = query.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs().size()).isEqualTo(3); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + + assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); + + AndDescr and = (AndDescr) first.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + assertThat(fld).isNotNull(); + + assertThat(fld.getExpression()).isEqualTo("a==3"); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + assertThat(second.getDescrs().size()).isEqualTo(1); + // check it has field bindings. + final ExprConstraintDescr bindingDescr = (ExprConstraintDescr) second.getDescrs().get( 0 ); + assertThat(bindingDescr.getExpression()).isEqualTo("a4:a==4"); + } + + @Test + public void parse_QueryRuleMixed() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "query_and_rule.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(4); // as queries are rules + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getName()).isEqualTo("bar"); + + QueryDescr query = (QueryDescr) pkg.getRules().get( 1 ); + assertThat(query.getName()).isEqualTo("simple_query"); + + rule = (RuleDescr) pkg.getRules().get( 2 ); + assertThat(rule.getName()).isEqualTo("bar2"); + + query = (QueryDescr) pkg.getRules().get( 3 ); + assertThat(query.getName()).isEqualTo("simple_query2"); + } + + @Test + public void parse_MultipleRules() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "multiple_rules.drl" ); + + final List rules = pkg.getRules(); + + assertThat(rules.size()).isEqualTo(2); + + final RuleDescr rule0 = rules.get( 0 ); + assertThat(rule0.getName()).isEqualTo("Like Stilton"); + + final RuleDescr rule1 = rules.get( 1 ); + assertThat(rule1.getName()).isEqualTo("Like Cheddar"); + + // checkout the first rule + AndDescr lhs = rule1.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + assertThat((String) rule0.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"I like \" + t);"); + + // Check first pattern + PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(first.getObjectType()).isEqualTo("Cheese"); + + // checkout the second rule + lhs = rule1.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + assertThat((String) rule1.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"I like \" + t);"); + + // Check first pattern + first = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(first.getObjectType()).isEqualTo("Cheese"); + } + + @Disabled("Priority : low | Not yet support DSL") + @Test + public void parse_ExpanderLineSpread() throws Exception { +// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); +// final PackageDescr pkg = parser.parse( this.getReader( "expander_spread_lines.dslr" ), +// this.getReader( "complex.dsl" ) ); +// +// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); +// +// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); +// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); +// +// final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); +// assertThat(or.getDescrs().size()).isEqualTo(2); +// assertThat( (String) rule.getConsequence() ).isNotNull(); + + } + + @Disabled("Priority : low | Not yet support DSL") + @Test + public void parse_ExpanderMultipleConstraints() throws Exception { +// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); +// final PackageDescr pkg = parser.parse( this.getReader( "expander_multiple_constraints.dslr" ), +// this.getReader( "multiple_constraints.dsl" ) ); +// +// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); +// +// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); +// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); +// +// PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); +// assertThat(pattern.getObjectType()).isEqualTo("Person"); +// +// assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); +// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); +// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); +// +// pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); +// assertThat(pattern.getObjectType()).isEqualTo("Bar"); +// +// assertThat( (String) rule.getConsequence() ).isNotNull(); + + } + + @Disabled("Priority : low | Not yet support DSL") + @Test + public void parse_ExpanderMultipleConstraintsFlush() throws Exception { +// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); +// // this is similar to the other test, but it requires a flush to add the +// // constraints +// final PackageDescr pkg = parser.parse( this.getReader( "expander_multiple_constraints_flush.dslr" ), +// this.getReader( "multiple_constraints.dsl" ) ); +// +// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); +// +// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); +// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); +// +// final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); +// assertThat(pattern.getObjectType()).isEqualTo("Person"); +// +// assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); +// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); +// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); +// +// assertThat( (String) rule.getConsequence() ).isNotNull(); + + } + + @Test + public void parse_BasicBinding() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "basic_binding.drl" ); + + final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get( 0 ); + + final AndDescr lhs = ruleDescr.getLhs(); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese.getConstraint().getDescrs().size()).isEqualTo(1); + final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get( 0 ); + assertThat(fieldBinding.getExpression()).isEqualToIgnoringWhitespace("$type:type"); + } + + @Test + public void parse_BoundVariables() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "bindings.drl" ); + + final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get( 0 ); + + final AndDescr lhs = ruleDescr.getLhs(); + assertThat(lhs.getDescrs().size()).isEqualTo(2); + final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get( 0 ); + assertThat(fieldBinding.getExpression()).isEqualTo("$type : type == \"stilton\""); + + final PatternDescr person = (PatternDescr) lhs.getDescrs().get( 1 ); + assertThat(person.getDescrs().size()).isEqualTo(2); + fieldBinding = (ExprConstraintDescr) person.getDescrs().get( 0 ); + assertThat(fieldBinding.getExpression()).isEqualTo("$name : name == \"bob\""); + + ExprConstraintDescr fld = (ExprConstraintDescr) person.getDescrs().get( 1 ); + assertThat(fld.getExpression()).isEqualTo("likes == $type"); + } + + @Test + public void parse_OrNesting() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_nesting.drl" ); + + assertThat(pkg).isNotNull(); + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + + final PatternDescr first = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(first.getObjectType()).isEqualTo("Person"); + + final AndDescr and = (AndDescr) or.getDescrs().get( 1 ); + assertThat(and.getDescrs().size()).isEqualTo(2); + + final PatternDescr left = (PatternDescr) and.getDescrs().get( 0 ); + assertThat(left.getObjectType()).isEqualTo("Person"); + + final PatternDescr right = (PatternDescr) and.getDescrs().get( 1 ); + assertThat(right.getObjectType()).isEqualTo("Cheese"); + } + + /** Test that explicit "&&", "||" works as expected */ + @Test + public void parse_AndOrRules() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "and_or_rule.drl" ); + + assertThat(pkg).isNotNull(); + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + // we will have 3 children under the main And node + final AndDescr and = rule.getLhs(); + assertThat(and.getDescrs().size()).isEqualTo(3); + + PatternDescr left = (PatternDescr) and.getDescrs().get( 0 ); + PatternDescr right = (PatternDescr) and.getDescrs().get( 1 ); + assertThat(left.getObjectType()).isEqualTo("Person"); + assertThat(right.getObjectType()).isEqualTo("Cheese"); + + assertThat(left.getConstraint().getDescrs().size()).isEqualTo(1); + + ExprConstraintDescr fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualTo("name == \"mark\""); + + assertThat(right.getConstraint().getDescrs().size()).isEqualTo(1); + + fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); + + // now the "||" part + final OrDescr or = (OrDescr) and.getDescrs().get( 2 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + left = (PatternDescr) or.getDescrs().get( 0 ); + right = (PatternDescr) or.getDescrs().get( 1 ); + assertThat(left.getObjectType()).isEqualTo("Person"); + assertThat(right.getObjectType()).isEqualTo("Cheese"); + assertThat(left.getConstraint().getDescrs().size()).isEqualTo(1); + + fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualTo("name == \"mark\""); + + assertThat(right.getConstraint().getDescrs().size()).isEqualTo(1); + + fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" );"); + } + + /** test basic foo : Fact() || Fact() stuff */ + @Test + public void parse_OrWithBinding() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_binding.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + + final PatternDescr leftPattern = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(leftPattern.getObjectType()).isEqualTo("Person"); + assertThat(leftPattern.getIdentifier()).isEqualTo("foo"); + + final PatternDescr rightPattern = (PatternDescr) or.getDescrs().get( 1 ); + assertThat(rightPattern.getObjectType()).isEqualTo("Person"); + assertThat(rightPattern.getIdentifier()).isEqualTo("foo"); + + final PatternDescr cheeseDescr = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(cheeseDescr.getObjectType()).isEqualTo("Cheese"); + assertThat(cheeseDescr.getIdentifier()).isEqualTo(null); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); + } + + /** test basic foo : Fact() || Fact() stuff binding to an "or" */ + @Test + public void parse_OrBindingComplex() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_binding_complex.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + + // first fact + final PatternDescr firstFact = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(firstFact.getObjectType()).isEqualTo("Person"); + assertThat(firstFact.getIdentifier()).isEqualTo("foo"); + + // second "option" + final PatternDescr secondFact = (PatternDescr) or.getDescrs().get( 1 ); + assertThat(secondFact.getObjectType()).isEqualTo("Person"); + assertThat(secondFact.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(secondFact.getIdentifier()).isEqualTo("foo"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); + } + + @Test + public void parse_OrBindingWithBrackets() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_binding_with_brackets.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + + // first fact + final PatternDescr firstFact = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(firstFact.getObjectType()).isEqualTo("Person"); + assertThat(firstFact.getIdentifier()).isEqualTo("foo"); + + // second "option" + final PatternDescr secondFact = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(secondFact.getObjectType()).isEqualTo("Person"); + assertThat(secondFact.getIdentifier()).isEqualTo("foo"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); + } + + @Test + void parenthesesOrAndOr() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "brackets_precedence.drl" ); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + + assertThat(rootAnd.getDescrs()).hasSize(2); + + final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get( 0 ); + + assertThat(leftOr.getDescrs()).hasSize(2); + final NotDescr not = (NotDescr) leftOr.getDescrs().get( 0 ); + final PatternDescr foo1 = (PatternDescr) not.getDescrs().get( 0 ); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final PatternDescr foo2 = (PatternDescr) leftOr.getDescrs().get( 1 ); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + + final OrDescr rightOr = (OrDescr) rootAnd.getDescrs().get( 1 ); + + assertThat(rightOr.getDescrs()).hasSize(2); + final PatternDescr shoes = (PatternDescr) rightOr.getDescrs().get( 0 ); + assertThat(shoes.getObjectType()).isEqualTo("Shoes"); + final PatternDescr butt = (PatternDescr) rightOr.getDescrs().get( 1 ); + assertThat(butt.getObjectType()).isEqualTo("Butt"); + } + + @Test + void parenthesesAndOrOr() { + final String drl = "rule and_or_or\n" + + " when\n" + + " (Foo(x == 1) and Bar(x == 2)) or (Foo(x == 3) or Bar(x == 4))\n" + + " then\n" + + "end"; + PackageDescr pkg = parser.parse(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final AndDescr leftAnd = (AndDescr) topOr.getDescrs().get(0); + assertThat(leftAnd.getDescrs()).hasSize(2); + final PatternDescr foo1 = (PatternDescr) leftAnd.getDescrs().get(0); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar1 = (PatternDescr) leftAnd.getDescrs().get(1); + assertThat(bar1.getObjectType()).isEqualTo("Bar"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).hasSize(2); + final PatternDescr foo2 = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar2 = (PatternDescr) rightOr.getDescrs().get(1); + assertThat(bar2.getObjectType()).isEqualTo("Bar"); + } + + @Test + void parenthesesOrAndAnd() { + final String drl = "rule or_and_and\n" + + " when\n" + + " (Foo(x == 1) or Bar(x == 2)) and (Foo(x == 3) and Bar(x == 4))\n" + + " then\n" + + "end"; + PackageDescr pkg = parser.parse(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(2); + + final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(leftOr.getDescrs()).hasSize(2); + final PatternDescr foo1 = (PatternDescr) leftOr.getDescrs().get(0); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar1 = (PatternDescr) leftOr.getDescrs().get(1); + assertThat(bar1.getObjectType()).isEqualTo("Bar"); + + final AndDescr rightAnd = (AndDescr) rootAnd.getDescrs().get(1); + assertThat(rightAnd.getDescrs()).hasSize(2); + final PatternDescr foo2 = (PatternDescr) rightAnd.getDescrs().get(0); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar2 = (PatternDescr) rightAnd.getDescrs().get(1); + assertThat(bar2.getObjectType()).isEqualTo("Bar"); + } + + @Test + void multipleLevelNestAndOrOrOrAnd() throws Exception { + final String drl = "rule and_or_or_or_and\n" + + " when\n" + + " (Foo(x == 1) and (Bar(x == 2) or Foo(x == 3))) or (Bar(x == 4) or (Foo(x == 5) and Bar(x == 6)))\n" + + " then\n" + + "end"; + PackageDescr pkg = parser.parse(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final AndDescr leftAnd = (AndDescr) topOr.getDescrs().get(0); + assertThat(leftAnd.getDescrs()).hasSize(2); + final PatternDescr foo1 = (PatternDescr) leftAnd.getDescrs().get(0); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final OrDescr leftOr = (OrDescr) leftAnd.getDescrs().get(1); + assertThat(leftOr.getDescrs()).hasSize(2); + final PatternDescr bar1 = (PatternDescr) leftOr.getDescrs().get(0); + assertThat(bar1.getObjectType()).isEqualTo("Bar"); + final PatternDescr foo2 = (PatternDescr) leftOr.getDescrs().get(1); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).hasSize(2); + final PatternDescr bar2 = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(bar2.getObjectType()).isEqualTo("Bar"); + final AndDescr rightAnd = (AndDescr) rightOr.getDescrs().get(1); + assertThat(rightAnd.getDescrs()).hasSize(2); + final PatternDescr foo3 = (PatternDescr) rightAnd.getDescrs().get(0); + assertThat(foo3.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar3 = (PatternDescr) rightAnd.getDescrs().get(1); + assertThat(bar3.getObjectType()).isEqualTo("Bar"); + } + + @Test + void multipleLevelNestWithThreeOrSiblings() throws Exception { + final String drl = "rule nest_or_siblings\n" + + " when\n" + + " (A() or (B() or C() or (D() and E())))\n" + + " then\n" + + "end"; + PackageDescr pkg = parser.parse(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final PatternDescr leftPattern = (PatternDescr) topOr.getDescrs().get(0); + assertThat(leftPattern.getObjectType()).isEqualTo("A"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).as("top level Or has 3 sibling children").hasSize(3); + final PatternDescr bPattern = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(bPattern.getObjectType()).isEqualTo("B"); + final PatternDescr cPattern = (PatternDescr) rightOr.getDescrs().get(1); + assertThat(cPattern.getObjectType()).isEqualTo("C"); + final AndDescr deAnd = (AndDescr) rightOr.getDescrs().get(2); + assertThat(deAnd.getDescrs()).hasSize(2); + + final PatternDescr dPattern = (PatternDescr) deAnd.getDescrs().get(0); + assertThat(dPattern.getObjectType()).isEqualTo("D"); + final PatternDescr ePattern = (PatternDescr) deAnd.getDescrs().get(1); + assertThat(ePattern.getObjectType()).isEqualTo("E"); + } + + @Test + public void existsMultipleLevelNestWithThreeOrSiblings() throws Exception { + final String drl = "rule nest_or_siblings\n" + + " when\n" + + " exists(A() or (B() or C() or (D() and E())))\n" + + " then\n" + + "end"; + PackageDescr pkg = parser.parse(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final ExistsDescr topExists = (ExistsDescr) rootAnd.getDescrs().get(0); + assertThat(topExists.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) topExists.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final PatternDescr leftPattern = (PatternDescr) topOr.getDescrs().get(0); + assertThat(leftPattern.getObjectType()).isEqualTo("A"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).hasSize(3); + final PatternDescr bPattern = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(bPattern.getObjectType()).isEqualTo("B"); + final PatternDescr cPattern = (PatternDescr) rightOr.getDescrs().get(1); + assertThat(cPattern.getObjectType()).isEqualTo("C"); + final AndDescr deAnd = (AndDescr) rightOr.getDescrs().get(2); + assertThat(deAnd.getDescrs()).hasSize(2); + + final PatternDescr dPattern = (PatternDescr) deAnd.getDescrs().get(0); + assertThat(dPattern.getObjectType()).isEqualTo("D"); + final PatternDescr ePattern = (PatternDescr) deAnd.getDescrs().get(1); + assertThat(ePattern.getObjectType()).isEqualTo("E"); + } + + @Test + public void parse_EvalMultiple() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "eval_multiple.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(4); + + final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(0 ); + assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace( "abc(\"foo\") + 5"); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("Foo"); + + } + + @Test + public void parse_WithEval() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "with_eval.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(3); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Foo"); + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("Bar"); + + final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get( 2 ); + assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace( "abc(\"foo\")"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "Kapow"); + } + + @Test + public void parse_WithRetval() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "with_retval.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(col.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(col.getObjectType()).isEqualTo("Foo"); + final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("name== (a + b)"); + } + + @Test + public void parse_WithPredicate() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "with_predicate.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + AndDescr and = (AndDescr) col.getConstraint(); + assertThat(and.getDescrs().size()).isEqualTo(2); + + final ExprConstraintDescr field = (ExprConstraintDescr) col.getDescrs().get( 0 ); + final ExprConstraintDescr pred = (ExprConstraintDescr) and.getDescrs().get( 1 ); + assertThat(field.getExpression()).isEqualToIgnoringWhitespace("$age2:age"); + assertThat(pred.getExpression()).isEqualToIgnoringWhitespace( "$age2 == $age1+2"); + } + + @Test + public void parse_NotWithConstraint() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "not_with_constraint.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fieldBinding.getExpression()).isEqualToIgnoringWhitespace("$likes:like"); + + final NotDescr not = (NotDescr) rule.getLhs().getDescrs().get( 1 ); + pattern = (PatternDescr) not.getDescrs().get( 0 ); + + final ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type == $likes"); + } + + @Disabled("Priority : Mid | Implement Descr lineNumber") + @Test + public void parse_Functions() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "functions.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(2); + + final List functions = pkg.getFunctions(); + assertThat(functions.size()).isEqualTo(2); + + FunctionDescr func = functions.get( 0 ); + assertThat(func.getName()).isEqualTo("functionA"); + assertThat(func.getReturnType()).isEqualTo("String"); + assertThat(func.getParameterNames().size()).isEqualTo(2); + assertThat(func.getParameterTypes().size()).isEqualTo(2); + assertThat(func.getLine()).isEqualTo(19); + assertThat(func.getColumn()).isEqualTo(0); + + assertThat(func.getParameterTypes().get(0)).isEqualTo("String"); + assertThat(func.getParameterNames().get(0)).isEqualTo("s"); + + assertThat(func.getParameterTypes().get(1)).isEqualTo("Integer"); + assertThat(func.getParameterNames().get(1)).isEqualTo("i"); + + assertThat(func.getBody()).isEqualToIgnoringWhitespace( "foo();"); + + func = functions.get( 1 ); + assertThat(func.getName()).isEqualTo("functionB"); + assertThat(func.getText()).isEqualToIgnoringWhitespace( "bar();"); + } + + @Test + public void parse_Comment() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "comment.drl" ); + + assertThat(pkg).isNotNull(); + + assertThat(pkg.getName()).isEqualTo("foo.bar"); + } + + @Test + public void parse_Attributes() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_attributes.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(6); + + 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"); + assertThat(at.getValue()).isEqualTo("my_group"); + + at = (AttributeDescr) attrs.get( "no-loop" ); + assertThat(at.getName()).isEqualTo("no-loop"); + assertThat(at.getValue()).isEqualTo("true"); + + at = (AttributeDescr) attrs.get( "duration" ); + assertThat(at.getName()).isEqualTo("duration"); + assertThat(at.getValue()).isEqualTo("42"); + + at = (AttributeDescr) attrs.get( "activation-group" ); + assertThat(at.getName()).isEqualTo("activation-group"); + assertThat(at.getValue()).isEqualTo("my_activation_group"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Test + public void parse_Attributes2() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "rule_attributes2.drl" ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + List rules = pkg.getRules(); + assertThat(rules.size()).isEqualTo(3); + + RuleDescr rule = rules.get( 0 ); + assertThat(rule.getName()).isEqualTo("rule1"); + Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + 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"); + assertThat(at.getValue()).isEqualTo("my_group"); + + rule = rules.get( 1 ); + assertThat(rule.getName()).isEqualTo("rule2"); + attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + at = (AttributeDescr) attrs.get( "salience" ); + assertThat(at.getName()).isEqualTo("salience"); + assertThat(at.getValue()).isEqualTo("(Integer.MIN_VALUE)"); + at = (AttributeDescr) attrs.get( "no-loop" ); + assertThat(at.getName()).isEqualTo("no-loop"); + + rule = rules.get( 2 ); + assertThat(rule.getName()).isEqualTo("rule3"); + attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + at = (AttributeDescr) attrs.get( "enabled" ); + assertThat(at.getName()).isEqualTo("enabled"); + assertThat(at.getValue()).isEqualTo("(Boolean.TRUE)"); + at = (AttributeDescr) attrs.get( "activation-group" ); + assertThat(at.getName()).isEqualTo("activation-group"); + assertThat(at.getValue()).isEqualTo("my_activation_group"); + + } + + @Test + public void parse_AttributeRefract() throws Exception { + final String source = "rule Test refract when Person() then end"; + + PackageDescr pkg = parser.parse( + source ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + assertThat(rule.getName()).isEqualTo("Test"); + Map attributes = rule.getAttributes(); + assertThat(attributes.size()).isEqualTo(1); + AttributeDescr refract = attributes.get( "refract" ); + assertThat(refract).isNotNull(); + assertThat(refract.getValue()).isEqualTo("true"); + + } + + @Test + public void parse_EnabledExpression() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_enabled_expression.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(3); + + AttributeDescr at = (AttributeDescr) attrs.get( "enabled" ); + assertThat(at.getName()).isEqualTo("enabled"); + assertThat(at.getValue()).isEqualTo("( 1 + 1 == 2 )"); + + at = (AttributeDescr) attrs.get( "salience" ); + assertThat(at.getName()).isEqualTo("salience"); + assertThat(at.getValue()).isEqualTo("( 1+2 )"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Test + public void parse_DurationExpression() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_duration_expression.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + + AttributeDescr at = (AttributeDescr) attrs.get( "duration" ); + assertThat(at.getName()).isEqualTo("duration"); + assertThat(at.getValue()).isEqualTo("1h30m"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Test + public void parse_Calendars() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_calendars_attribute.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + + AttributeDescr at = (AttributeDescr) attrs.get( "calendars" ); + assertThat(at.getName()).isEqualTo("calendars"); + assertThat(at.getValue()).isEqualTo("[ \"cal1\" ]"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Test + public void parse_Calendars2() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_calendars_attribute2.drl" ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + + AttributeDescr at = (AttributeDescr) attrs.get( "calendars" ); + assertThat(at.getName()).isEqualTo("calendars"); + assertThat(at.getValue()).isEqualTo("[ \"cal 1\", \"cal 2\", \"cal 3\" ]"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Disabled("Priority : Low | Not written in docs nor other unit tests. Drop the support?") + @Test + public void parse_Attributes_alternateSyntax() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_attributes_alt.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(6); + + 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"); + assertThat(at.getValue()).isEqualTo("my_group"); + + at = (AttributeDescr) attrs.get( "no-loop" ); + assertThat(at.getName()).isEqualTo("no-loop"); + assertThat(at.getValue()).isEqualTo("true"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + + at = (AttributeDescr) attrs.get( "duration" ); + assertThat(at.getName()).isEqualTo("duration"); + assertThat(at.getValue()).isEqualTo("42"); + + at = (AttributeDescr) attrs.get( "activation-group" ); + assertThat(at.getName()).isEqualTo("activation-group"); + assertThat(at.getValue()).isEqualTo("my_activation_group"); + } + + @Test + public void parse_Enumeration() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "enumeration.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(col.getObjectType()).isEqualTo("Foo"); + assertThat(col.getConstraint().getDescrs().size()).isEqualTo(1); + final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == Foo.BAR"); + } + + @Test + public void parse_ExtraLhsNewline() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "extra_lhs_newline.drl" ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + } + + @Disabled("Priority : Low | Implement soundslike") + @Test + public void parse_SoundsLike() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "soundslike_operator.drl" ); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + PatternDescr pat = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + pat.getConstraint(); + } + + @Test + public void parse_PackageAttributes() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "package_attributes.drl" ); + + AttributeDescr at = (AttributeDescr) pkg.getAttributes().get( 0 ); + assertThat(at.getName()).isEqualTo("agenda-group"); + assertThat(at.getValue()).isEqualTo("x"); + at = (AttributeDescr) pkg.getAttributes().get( 1 ); + assertThat(at.getName()).isEqualTo("dialect"); + assertThat(at.getValue()).isEqualTo("java"); + + assertThat(pkg.getRules().size()).isEqualTo(2); + + assertThat(pkg.getImports().size()).isEqualTo(2); + + 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"); + assertThat(at.getValue()).isEqualTo("x"); + at = (AttributeDescr) rule.getAttributes().get( "dialect" ); + assertThat(at.getName()).isEqualTo("dialect"); + assertThat(at.getValue()).isEqualTo("java"); + + rule = (RuleDescr) pkg.getRules().get( 1 ); + assertThat(rule.getName()).isEqualTo("baz"); + 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"); + assertThat(at.getValue()).isEqualTo("x"); + + } + + @Test + public void parse_StatementOrdering1() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "statement_ordering_1.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(2); + + assertThat(((RuleDescr) pkg.getRules().get(0)).getName()).isEqualTo("foo"); + assertThat(((RuleDescr) pkg.getRules().get(1)).getName()).isEqualTo("bar"); + + assertThat(pkg.getFunctions().size()).isEqualTo(2); + + assertThat(((FunctionDescr) pkg.getFunctions().get(0)).getName()).isEqualTo("cheeseIt"); + assertThat(((FunctionDescr) pkg.getFunctions().get(1)).getName()).isEqualTo("uncheeseIt"); + + assertThat(pkg.getImports().size()).isEqualTo(4); + assertThat(((ImportDescr) pkg.getImports().get(0)).getTarget()).isEqualTo("im.one"); + assertThat(((ImportDescr) pkg.getImports().get(1)).getTarget()).isEqualTo("im.two"); + assertThat(((ImportDescr) pkg.getImports().get(2)).getTarget()).isEqualTo("im.three"); + assertThat(((ImportDescr) pkg.getImports().get(3)).getTarget()).isEqualTo("im.four"); + } + + @Test + public void parse_RuleNamesStartingWithNumbers() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "rule_names_number_prefix.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(2); + + assertThat(((RuleDescr) pkg.getRules().get(0)).getName()).isEqualTo("1. Do Stuff!"); + assertThat(((RuleDescr) pkg.getRules().get(1)).getName()).isEqualTo("2. Do More Stuff!"); + } + + @Test + public void parse_EvalWithNewline() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "eval_with_newline.drl"); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + } + + @Disabled("Priority : Mid | implement Descr lineNumber") + @Test + public void parse_EndPosition() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "test_EndPosition.drl" ); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(col.getLine()).isEqualTo(21); + assertThat(col.getEndLine()).isEqualTo(23); + } + + @Test + public void parse_QualifiedClassname() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "qualified_classname.drl" ); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + final PatternDescr p = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + assertThat(p.getObjectType()).isEqualTo("com.cheeseco.Cheese"); + } + + @Test + public void parse_Accumulate() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;"); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;"); + assertThat(accum.getReverseCode()).isNull(); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)"); + + assertThat(accum.isExternalFunction()).isFalse(); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Test + public void parse_AccumulateWithBindings() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate_with_bindings.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace( "$counter"); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;"); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;"); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Test + public void parse_Collect() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "collect.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final CollectDescr collect = (CollectDescr) outPattern.getSource(); + + final PatternDescr pattern = (PatternDescr) collect.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Test + public void parse_Predicate2() throws Exception { + // predicates are also prefixed by the eval keyword + final RuleDescr rule = parseAndGetFirstRuleDescr( + "rule X when Foo(eval( $var.equals(\"xyz\") )) then end" ); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final List< ? > constraints = pattern.getConstraint().getDescrs(); + assertThat(constraints.size()).isEqualTo(1); + + final ExprConstraintDescr predicate = (ExprConstraintDescr) constraints.get( 0 ); + assertThat(predicate.getExpression()).isEqualToIgnoringWhitespace("eval( $var.equals(\"xyz\") )"); + } + + @Test + public void parse_EscapedStrings() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "escaped-string.drl" ); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("test_Quotes"); + + final String expected = "String s = \"\\\"\\n\\t\\\\\";"; + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( expected); + } + + @Test + public void parse_NestedCEs() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "nested_conditional_elements.drl" ); + + assertThat(rule).isNotNull(); + + final AndDescr root = rule.getLhs(); + final NotDescr not1 = (NotDescr) root.getDescrs().get( 0 ); + final AndDescr and1 = (AndDescr) not1.getDescrs().get( 0 ); + + final PatternDescr state = (PatternDescr) and1.getDescrs().get( 0 ); + final NotDescr not2 = (NotDescr) and1.getDescrs().get( 1 ); + final AndDescr and2 = (AndDescr) not2.getDescrs().get( 0 ); + final PatternDescr person = (PatternDescr) and2.getDescrs().get( 0 ); + final PatternDescr cheese = (PatternDescr) and2.getDescrs().get( 1 ); + + final PatternDescr person2 = (PatternDescr) root.getDescrs().get( 1 ); + final OrDescr or = (OrDescr) root.getDescrs().get( 2 ); + final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get( 0 ); + final PatternDescr cheese3 = (PatternDescr) or.getDescrs().get( 1 ); + + assertThat("State").isEqualTo(state.getObjectType()); + assertThat("Person").isEqualTo(person.getObjectType()); + assertThat("Cheese").isEqualTo(cheese.getObjectType()); + assertThat("Person").isEqualTo(person2.getObjectType()); + assertThat("Cheese").isEqualTo(cheese2.getObjectType()); + assertThat("Cheese").isEqualTo(cheese3.getObjectType()); + } + + @Test + public void parse_Forall() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "forall.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0 ); + + assertThat(forall.getDescrs().size()).isEqualTo(2); + final PatternDescr pattern = forall.getBasePattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + final List remaining = forall.getRemainingPatterns(); + assertThat(remaining.size()).isEqualTo(1); + final PatternDescr cheese = (PatternDescr) remaining.get( 0 ); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + } + + @Test + public void parse_ForallWithFrom() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "forallwithfrom.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get( 0 ); + + assertThat(forall.getDescrs().size()).isEqualTo(2); + final PatternDescr pattern = forall.getBasePattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(((FromDescr) pattern.getSource()).getDataSource().toString()).isEqualTo("$village"); + final List remaining = forall.getRemainingPatterns(); + assertThat(remaining.size()).isEqualTo(1); + final PatternDescr cheese = (PatternDescr) remaining.get( 0 ); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + assertThat(((FromDescr) cheese.getSource()).getDataSource().toString()).isEqualTo("$cheesery"); + } + + @Test + public void parse_Memberof() throws Exception { + final String text = "rule X when Country( $cities : city )\nPerson( city memberOf $cities )\n then end"; + AndDescr descrs = parseAndGetFirstRuleDescr( + text).getLhs(); + + assertThat(descrs.getDescrs().size()).isEqualTo(2); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 1 ); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); + + assertThat(fieldConstr.getExpression()).isEqualTo("city memberOf $cities"); + } + + @Test + public void parse_NotMemberof() throws Exception { + final String text = "rule X when Country( $cities : city )\nPerson( city not memberOf $cities ) then end\n"; + AndDescr descrs = parseAndGetFirstRuleDescr( + text).getLhs(); + + assertThat(descrs.getDescrs().size()).isEqualTo(2); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 1 ); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); + + assertThat(fieldConstr.getExpression()).isEqualTo("city not memberOf $cities"); + } + + @Test + public void parse_InOperator() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "in_operator_test.drl" ); + + assertThat(rule).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "consequence();"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + // The first pattern, with 2 restrictions on a single field (plus a + // connective) + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + + ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + + // the second col, with 2 fields, the first with 2 restrictions, the + // second field with one + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); + + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type in ( \"sedan\", \"wagon\" )"); + + // now the second field + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 1 ); + assertThat(fld.getExpression()).isEqualTo("age < 3"); + + } + + @Test + public void parse_NotInOperator() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "notin_operator_test.drl" ); + + assertThat(rule).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "consequence();"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + // The first pattern, with 2 restrictions on a single field (plus a + // connective) + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + + ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + + // the second col, with 2 fields, the first with 2 restrictions, the + // second field with one + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); + + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type not in ( \"sedan\", \"wagon\" )"); + + // now the second field + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 1 ); + assertThat(fld.getExpression()).isEqualTo("age < 3"); + + } + + @Test + public void parse_CheckOrDescr() throws Exception { + final String text = "rule X when Person( eval( age == 25 ) || ( eval( name.equals( \"bob\" ) ) && eval( age == 30 ) ) ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + assertThat(AndDescr.class).isEqualTo(pattern.getConstraint().getClass()); + + assertThat(pattern.getConstraint().getDescrs().get(0).getClass()).isEqualTo(ExprConstraintDescr.class); + + } + + @Test + public void parse_ConstraintAndConnective() throws Exception { + final String text = "rule X when Person( age < 42 && location==\"atlanta\") then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 && location==\"atlanta\""); + } + + @Test + public void parse_ConstraintOrConnective() throws Exception { + final String text = "rule X when Person( age < 42 || location==\"atlanta\") then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 || location==\"atlanta\""); + } + + @Test + public void parse_Restrictions() throws Exception { + final String text = "rule X when Foo( bar > 1 || == 1 ) then end\n"; + + AndDescr descrs = (AndDescr) parseAndGetFirstRuleDescr( + text ).getLhs(); + + assertThat(descrs.getDescrs().size()).isEqualTo(1); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 0 ); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); + + assertThat(fieldConstr.getExpression()).isEqualTo("bar > 1 || == 1"); + } + + @Test + public void parse_Semicolon() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "semicolon.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); + assertThat(pkg.getGlobals().size()).isEqualTo(1); + assertThat(pkg.getRules().size()).isEqualTo(3); + + final RuleDescr rule1 = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule1.getLhs().getDescrs().size()).isEqualTo(2); + + final RuleDescr query1 = (RuleDescr) pkg.getRules().get( 1 ); + assertThat(query1.getLhs().getDescrs().size()).isEqualTo(3); + + final RuleDescr rule2 = (RuleDescr) pkg.getRules().get( 2 ); + assertThat(rule2.getLhs().getDescrs().size()).isEqualTo(2); + } + + @Test + public void parse_Eval() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "eval_parsing.drl" ); + + assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); + assertThat(pkg.getRules().size()).isEqualTo(1); + + final RuleDescr rule1 = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule1.getLhs().getDescrs().size()).isEqualTo(1); + } + + @Test + public void parse_AccumulateReverse() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateReverse.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;" + ); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;" + ); + assertThat(accum.getReverseCode()).isEqualToIgnoringWhitespace( "x--;" + ); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)" + ); + assertThat(accum.isExternalFunction()).isFalse(); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Test + public void parse_AccumulateExternalFunction() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateExternalFunction.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.getFunctions().get( 0 ).getParams()[0]).isEqualToIgnoringWhitespace( "$age" + ); + assertThat(accum.getFunctions().get( 0 ).getFunction()).isEqualToIgnoringWhitespace( "average" + ); + assertThat(accum.isExternalFunction()).isTrue(); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Test + public void parse_CollectWithNestedFrom() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "collect_with_nested_from.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final CollectDescr collect = (CollectDescr) out.getSource(); + + PatternDescr person = (PatternDescr) collect.getInputPattern(); + assertThat(person.getObjectType()).isEqualTo("Person"); + + final CollectDescr collect2 = (CollectDescr) person.getSource(); + + final PatternDescr people = collect2.getInputPattern(); + assertThat(people.getObjectType()).isEqualTo("People"); + } + + @Test + public void parse_AccumulateWithNestedFrom() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate_with_nested_from.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accumulate = (AccumulateDescr) out.getSource(); + + PatternDescr person = (PatternDescr) accumulate.getInputPattern(); + assertThat(person.getObjectType()).isEqualTo("Person"); + + final CollectDescr collect2 = (CollectDescr) person.getSource(); + + final PatternDescr people = collect2.getInputPattern(); + assertThat(people.getObjectType()).isEqualTo("People"); + } + + @Test + public void parse_AccumulateMultipleFunctions() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateMultipleFunctions.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(3); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$a1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(1).getFunction()).isEqualTo("min"); + assertThat(functions.get(1).getBind()).isEqualTo("$m1"); + assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(2).getFunction()).isEqualTo("max"); + assertThat(functions.get(2).getBind()).isEqualTo("$M1"); + assertThat(functions.get(2).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + public void parse_AccumulateMnemonic() throws Exception { + String drl = "package org.drools.mvel.compiler\n" + + "rule \"Accumulate 1\"\n" + + "when\n" + + " acc( Cheese( $price : price ),\n" + + " $a1 : average( $price ) )\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parser.parse( + drl ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(1); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$a1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + public void parse_AccumulateMnemonic2() throws Exception { + String drl = "package org.drools.mvel.compiler\n" + + "rule \"Accumulate 1\"\n" + + "when\n" + + " Number() from acc( Cheese( $price : price ),\n" + + " average( $price ) )\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parser.parse( + drl ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Number"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(1); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + public void parse_ImportAccumulate() throws Exception { + String drl = "package org.drools.mvel.compiler\n" + + "import acc foo.Bar baz\n" + + "import accumulate foo.Bar2 baz2\n" + + "rule \"Accumulate 1\"\n" + + "when\n" + + " acc( Cheese( $price : price ),\n" + + " $v1 : baz( $price ), \n" + + " $v2 : baz2( $price ) )\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parser.parse( + drl ); + + assertThat(pkg.getAccumulateImports().size()).isEqualTo(2); + AccumulateImportDescr imp = (AccumulateImportDescr) pkg.getAccumulateImports().get(0); + assertThat(imp.getTarget()).isEqualTo("foo.Bar"); + assertThat(imp.getFunctionName()).isEqualTo("baz"); + + imp = (AccumulateImportDescr) pkg.getAccumulateImports().get(1); + assertThat(imp.getTarget()).isEqualTo("foo.Bar2"); + assertThat(imp.getFunctionName()).isEqualTo("baz2"); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(2); + assertThat(functions.get(0).getFunction()).isEqualTo("baz"); + assertThat(functions.get(0).getBind()).isEqualTo("$v1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(1).getFunction()).isEqualTo("baz2"); + assertThat(functions.get(1).getBind()).isEqualTo("$v2"); + assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + public void parse_AccumulateMultipleFunctionsConstraint() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateMultipleFunctionsConstraint.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Object"); + assertThat(out.getConstraint().getDescrs().size()).isEqualTo(2); + assertThat(out.getConstraint().getDescrs().get(0).toString()).isEqualTo("$a1 > 10 && $M1 <= 100"); + assertThat(out.getConstraint().getDescrs().get(1).toString()).isEqualTo("$m1 == 5"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(3); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$a1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(1).getFunction()).isEqualTo("min"); + assertThat(functions.get(1).getBind()).isEqualTo("$m1"); + assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(2).getFunction()).isEqualTo("max"); + assertThat(functions.get(2).getBind()).isEqualTo("$M1"); + assertThat(functions.get(2).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + public void parse_OrCE() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_ce.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + final PatternDescr person = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(person.getObjectType()).isEqualTo("Person"); + assertThat(person.getIdentifier()).isEqualTo("$p"); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + + final PatternDescr cheese1 = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(cheese1.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese1.getIdentifier()).isEqualTo("$c"); + final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get( 1 ); + assertThat(cheese2.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese2.getIdentifier()).isNull(); + } + + @Test + public void parse_RuleSingleLine() throws Exception { + final String text = "rule \"another test\" salience 10 when eval( true ) then System.out.println(1); end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text ); + + assertThat(rule.getName()).isEqualTo("another test"); + assertThat((String)rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1); "); + } + + @Test + public void parse_RuleTwoLines() throws Exception { + final String text = "rule \"another test\" salience 10 when eval( true ) then System.out.println(1);\n end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text ); + + assertThat(rule.getName()).isEqualTo("another test"); + assertThat((String)rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1);\n "); + } + + @Test + public void parse_RuleParseLhs3() throws Exception { + final String text = "rule X when (or\nnot Person()\n(and Cheese()\nMeat()\nWine())) then end"; + AndDescr pattern = parseAndGetFirstRuleDescr( + text ).getLhs(); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + OrDescr or = (OrDescr) pattern.getDescrs().get( 0 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + NotDescr not = (NotDescr) or.getDescrs().get( 0 ); + AndDescr and = (AndDescr) or.getDescrs().get( 1 ); + assertThat(not.getDescrs().size()).isEqualTo(1); + PatternDescr person = (PatternDescr) not.getDescrs().get( 0 ); + assertThat(person.getObjectType()).isEqualTo("Person"); + assertThat(and.getDescrs().size()).isEqualTo(3); + PatternDescr cheese = (PatternDescr) and.getDescrs().get( 0 ); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + PatternDescr meat = (PatternDescr) and.getDescrs().get( 1 ); + assertThat(meat.getObjectType()).isEqualTo("Meat"); + PatternDescr wine = (PatternDescr) and.getDescrs().get( 2 ); + assertThat(wine.getObjectType()).isEqualTo("Wine"); + + } + + @Test + public void parse_AccumulateMultiPattern() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate_multi_pattern.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace( "$counter" + ); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;" + ); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;" + ); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)" + ); + + final AndDescr and = (AndDescr) accum.getInput(); + assertThat(and.getDescrs().size()).isEqualTo(2); + final PatternDescr person = (PatternDescr) and.getDescrs().get( 0 ); + final PatternDescr cheese = (PatternDescr) and.getDescrs().get( 1 ); + assertThat(person.getObjectType()).isEqualTo("Person"); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + } + + @Test + public void parse_PluggableOperators() throws Exception { + + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "pluggable_operators.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(5); + + final PatternDescr eventA = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(eventA.getIdentifier()).isEqualTo("$a"); + assertThat(eventA.getObjectType()).isEqualTo("EventA"); + + final PatternDescr eventB = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(eventB.getIdentifier()).isEqualTo("$b"); + assertThat(eventB.getObjectType()).isEqualTo("EventB"); + assertThat(eventB.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(eventB.getConstraint().getDescrs().size()).isEqualTo(1); + + final ExprConstraintDescr fcdB = (ExprConstraintDescr) eventB.getConstraint().getDescrs().get( 0 ); + assertThat(fcdB.getExpression()).isEqualTo("this after[1,10] $a || this not after[15,20] $a"); + + final PatternDescr eventC = (PatternDescr) rule.getLhs().getDescrs().get( 2 ); + assertThat(eventC.getIdentifier()).isEqualTo("$c"); + assertThat(eventC.getObjectType()).isEqualTo("EventC"); + assertThat(eventC.getConstraint().getDescrs().size()).isEqualTo(1); + final ExprConstraintDescr fcdC = (ExprConstraintDescr) eventC.getConstraint().getDescrs().get( 0 ); + assertThat(fcdC.getExpression()).isEqualTo("this finishes $b"); + + final PatternDescr eventD = (PatternDescr) rule.getLhs().getDescrs().get( 3 ); + assertThat(eventD.getIdentifier()).isEqualTo("$d"); + assertThat(eventD.getObjectType()).isEqualTo("EventD"); + assertThat(eventD.getConstraint().getDescrs().size()).isEqualTo(1); + final ExprConstraintDescr fcdD = (ExprConstraintDescr) eventD.getConstraint().getDescrs().get( 0 ); + assertThat(fcdD.getExpression()).isEqualTo("this not starts $a"); + + final PatternDescr eventE = (PatternDescr) rule.getLhs().getDescrs().get( 4 ); + assertThat(eventE.getIdentifier()).isEqualTo("$e"); + assertThat(eventE.getObjectType()).isEqualTo("EventE"); + assertThat(eventE.getConstraint().getDescrs().size()).isEqualTo(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"); + } + + @Test + public void parse_RuleMetadata() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "Rule_with_Metadata.drl" ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + // @fooAttribute(barValue) + // @fooAtt2(barVal2) + RuleDescr rule = pkg.getRules().get( 0 ); + assertThat(rule.getAnnotationNames().contains("fooMeta1")).isTrue(); + assertThat(rule.getAnnotation("fooMeta1").getValue()).isEqualTo("barVal1"); + assertThat(rule.getAnnotationNames().contains("fooMeta2")).isTrue(); + assertThat(rule.getAnnotation("fooMeta2").getValue()).isEqualTo("barVal2"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"Consequence\");" + ); + } + + @Test + public void parse_RuleExtends() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "Rule_with_Extends.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get( 0 ); + assertThat(rule.getParentName() != null).isTrue(); + assertThat(rule.getParentName()).isEqualTo("rule1"); + + AndDescr lhs = rule.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + + PatternDescr pattern = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("foo"); + assertThat(pattern.getIdentifier()).isEqualTo("$foo"); + + } + + @Test + public void parse_TypeDeclarationWithFields() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "declare_type_with_fields.drl" ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + List td = pkg.getTypeDeclarations(); + assertThat(td.size()).isEqualTo(3); + + TypeDeclarationDescr d = td.get( 0 ); + assertThat(d.getTypeName()).isEqualTo("SomeFact"); + assertThat(d.getFields().size()).isEqualTo(2); + assertThat(d.getFields().containsKey("name")).isTrue(); + assertThat(d.getFields().containsKey("age")).isTrue(); + + TypeFieldDescr f = d.getFields().get("name" ); + assertThat(f.getPattern().getObjectType()).isEqualTo("String"); + + f = d.getFields().get( "age" ); + assertThat(f.getPattern().getObjectType()).isEqualTo("Integer"); + + d = td.get( 1 ); + assertThat(d.getTypeName()).isEqualTo("AnotherFact"); + + TypeDeclarationDescr type = td.get( 2 ); + assertThat(type.getTypeName()).isEqualTo("Person"); + + assertThat(type.getAnnotation("role").getValue()).isEqualTo("fact"); + assertThat(type.getAnnotation("doc").getValue("descr")).isEqualTo("\"Models a person\""); + assertThat(type.getAnnotation("doc").getValue("author")).isEqualTo("\"Bob\""); + assertThat(type.getAnnotation("doc").getValue("date")).isEqualTo("Calendar.getInstance().getDate()"); + + assertThat(type.getFields().size()).isEqualTo(2); + TypeFieldDescr field = type.getFields().get( "name" ); + assertThat(field.getFieldName()).isEqualTo("name"); + assertThat(field.getPattern().getObjectType()).isEqualTo("String"); + assertThat(field.getInitExpr()).isEqualTo("\"John Doe\""); + assertThat(field.getAnnotation("length").getValue("max")).isEqualTo("50"); + assertThat( field.getAnnotation( "key" ) ).isNotNull(); + + field = type.getFields().get( "age" ); + assertThat(field.getFieldName()).isEqualTo("age"); + assertThat(field.getPattern().getObjectType()).isEqualTo("int"); + assertThat(field.getInitExpr()).isEqualTo("-1"); + assertThat(field.getAnnotation("ranged").getValue("min")).isEqualTo("0"); + assertThat(field.getAnnotation("ranged").getValue("max")).isEqualTo("150"); + assertThat(field.getAnnotation("ranged").getValue("unknown")).isEqualTo("-1"); + + } + + @Test + public void parenthesesOneLevelNestWithThreeSiblings() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( "Rule_with_nested_LHS.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get( 0 ); + assertThat(rule.getName()).isEqualTo("test"); + + AndDescr lhs = rule.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs().size()).isEqualTo(2); + + PatternDescr a = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(a.getObjectType()).isEqualTo("A"); + + OrDescr or = (OrDescr) lhs.getDescrs().get( 1 ); + assertThat(or.getDescrs().size()).isEqualTo(3); + + AndDescr and1 = (AndDescr) or.getDescrs().get( 0 ); + assertThat(and1.getDescrs().size()).isEqualTo(2); + PatternDescr b = (PatternDescr) and1.getDescrs().get( 0 ); + PatternDescr c = (PatternDescr) and1.getDescrs().get( 1 ); + assertThat(b.getObjectType()).isEqualTo("B"); + assertThat(c.getObjectType()).isEqualTo("C"); + + AndDescr and2 = (AndDescr) or.getDescrs().get( 1 ); + assertThat(and2.getDescrs().size()).isEqualTo(2); + PatternDescr d = (PatternDescr) and2.getDescrs().get( 0 ); + PatternDescr e = (PatternDescr) and2.getDescrs().get( 1 ); + assertThat(d.getObjectType()).isEqualTo("D"); + assertThat(e.getObjectType()).isEqualTo("E"); + + AndDescr and3 = (AndDescr) or.getDescrs().get( 2 ); + assertThat(and3.getDescrs().size()).isEqualTo(2); + PatternDescr f = (PatternDescr) and3.getDescrs().get( 0 ); + PatternDescr g = (PatternDescr) and3.getDescrs().get( 1 ); + assertThat(f.getObjectType()).isEqualTo("F"); + assertThat(g.getObjectType()).isEqualTo("G"); + } + + @Test + public void parse_EntryPoint() throws Exception { + final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point StreamA then end"; + + PackageDescr pkg = parser.parse( + text ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); + + assertThat(pattern.getSource()).isNotNull(); + EntryPointDescr entry = (EntryPointDescr) pattern.getSource(); + assertThat(entry.getEntryId()).isEqualTo("StreamA"); + } + + @Test + public void parse_EntryPoint2() throws Exception { + final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point \"StreamA\" then end"; + + PackageDescr pkg = parser.parse( + text ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); + + assertThat(pattern.getSource()).isNotNull(); + EntryPointDescr entry = (EntryPointDescr) pattern.getSource(); + assertThat(entry.getEntryId()).isEqualTo("StreamA"); + } + + @Test + public void parse_SlidingWindow() throws Exception { + final String text = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end"; + + PackageDescr pkg = parser.parse( text ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); + + List behaviors = pattern.getBehaviors(); + assertThat(behaviors).isNotNull(); + assertThat(behaviors.size()).isEqualTo(1); + BehaviorDescr descr = behaviors.get( 0 ); + assertThat(descr.getType()).isEqualTo("window"); + assertThat(descr.getSubType()).isEqualTo("length"); + assertThat(descr.getParameters().get(0)).isEqualTo("10"); + } + + @Test + public void parse_RuleOldSyntax1() throws Exception { + final String source = "rule \"Test\" when ( not $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; + + PackageDescr pkg = parser.parse( + source ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + assertThat(rule.getName()).isEqualTo("Test"); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(((NotDescr) rule.getLhs().getDescrs().get(0)).getDescrs().size()).isEqualTo(1); + NotDescr notDescr = (NotDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr patternDescr = (PatternDescr) notDescr.getDescrs().get( 0 ); + assertThat(patternDescr.getIdentifier()).isEqualTo("$r"); + assertThat(patternDescr.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get( 0 ); + assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); + } + + @Test + public void parse_RuleOldSyntax2() throws Exception { + final String source = "rule \"Test\" when ( $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; + + PackageDescr pkg = parser.parse( + source ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + assertThat(rule.getName()).isEqualTo("Test"); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + PatternDescr patternDescr = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(patternDescr.getIdentifier()).isEqualTo("$r"); + assertThat(patternDescr.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get( 0 ); + assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); + } + + @Test + public void parse_TypeWithMetaData() throws Exception { + + PackageDescr pkg = parseAndGetPackageDescrFromFile( + "type_with_meta.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + final List declarations = pkg.getTypeDeclarations(); + + assertThat(declarations.size()).isEqualTo(3); + } + + @Test + public void parse_NullConstraints() throws Exception { + final String text = "rule X when Person( name == null ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("name == null"); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); + } + + @Test + public void parse_PositionalConstraintsOnly() throws Exception { + final String text = "rule X when Person( \"Mark\", 42; ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(2); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + assertThat(fcd.getExpression()).isEqualTo("42"); + assertThat(fcd.getPosition()).isEqualTo(1); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + } + + @Test + public void parse_IsQuery() throws Exception { + final String text = "rule X when ?person( \"Mark\", 42; ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.isQuery()).isTrue(); + + assertThat(pattern.getDescrs().size()).isEqualTo(2); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + assertThat(fcd.getExpression()).isEqualTo("42"); + assertThat(fcd.getPosition()).isEqualTo(1); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + } + + @Test + public void parse_FromFollowedByQuery() throws Exception { + // the 'from' expression requires a ";" to disambiguate the "?" + // prefix for queries from the ternary operator "? :" + final String text = "rule X when Cheese() from $cheesery ?person( \"Mark\", 42; ) then end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + assertThat(pattern.getSource().getText()).isEqualTo("from $cheesery"); + assertThat(pattern.isQuery()).isFalse(); + + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("person"); + assertThat(pattern.isQuery()).isTrue(); + + } + + @Test + public void parse_FromWithTernaryFollowedByQuery() throws Exception { + // the 'from' expression requires a ";" to disambiguate the "?" + // prefix for queries from the ternary operator "? :" + final String text = "rule X when Cheese() from (isFull ? $cheesery : $market) ?person( \"Mark\", 42; ) then end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + assertThat(pattern.getSource().getText()).isEqualToIgnoringWhitespace("from (isFull ? $cheesery : $market)"); + assertThat(pattern.isQuery()).isFalse(); + + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("person"); + assertThat(pattern.isQuery()).isTrue(); + + } + + @Disabled("Priority : Low | Implement multi-value annotation. Not written in docs") + @Test + public void parse_MultiValueAnnotationsBackwardCompatibility() throws Exception { + // multiple values with no keys are parsed as a single value + final String text = "rule X @ann1( val1, val2 ) @ann2( \"val1\", \"val2\" ) when then end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text ); + + AnnotationDescr ann = rule.getAnnotation("ann1" ); + assertThat(ann).isNotNull(); + assertThat(ann.getValue()).isEqualTo("val1, val2"); + + ann = rule.getAnnotation( "ann2" ); + assertThat(ann).isNotNull(); + assertThat(ann.getValue()).isEqualTo("\"val1\", \"val2\""); + } + + @Test + public void parse_PositionalsAndNamedConstraints() throws Exception { + final String text = "rule X when Person( \"Mark\", 42; location == \"atlanta\" ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(3); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + assertThat(fcd.getExpression()).isEqualTo("42"); + assertThat(fcd.getPosition()).isEqualTo(1); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + + fcd = (ExprConstraintDescr) pattern.getDescrs().get( 2 ); + assertThat(fcd.getExpression()).isEqualTo("location == \"atlanta\""); + assertThat(fcd.getPosition()).isEqualTo(2); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); + + } + + @Test + public void parse_UnificationBinding() throws Exception { + final String text = "rule X when $p := Person( $name := name, $loc : location ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getIdentifier()).isEqualTo("$p"); + assertThat(pattern.isUnification()).isTrue(); + + assertThat(pattern.getDescrs().size()).isEqualTo(2); + ExprConstraintDescr bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(bindingDescr.getExpression()).isEqualTo("$name := name"); + + bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + assertThat(bindingDescr.getExpression()).isEqualTo("$loc : location"); + + } + + @Test + public void parse_BigLiterals() { + final String text = "rule X when Primitives( bigInteger == (10I), " + + " bigDecimal == (10B), " + + " bigInteger < 50I, " + + " bigDecimal < 50.2B ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(4); + ExprConstraintDescr ecd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(ecd.getExpression()).isEqualTo("bigInteger == (10I)"); + + ecd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + assertThat(ecd.getExpression()).isEqualTo("bigDecimal == (10B)"); + + ecd = (ExprConstraintDescr) pattern.getDescrs().get( 2 ); + assertThat(ecd.getExpression()).isEqualTo("bigInteger < 50I"); + + ecd = (ExprConstraintDescr) pattern.getDescrs().get( 3 ); + assertThat(ecd.getExpression()).isEqualTo("bigDecimal < 50.2B"); + } + + @Test + public void parse_BindingComposite() throws Exception { + final String text = "rule X when Person( $name : name == \"Bob\" || $loc : location == \"Montreal\" ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.isUnification()).isFalse(); + + // embedded bindings are extracted at compile time + List< ? > constraints = pattern.getDescrs(); + assertThat(constraints.size()).isEqualTo(1); + assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name == \"Bob\" || $loc : location == \"Montreal\""); + } + + @Test + public void parse_BindingCompositeWithMethods() throws Exception { + final String text = "rule X when Person( $name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\" ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.isUnification()).isFalse(); + + // embedded bindings are extracted at compile time + List< ? > constraints = pattern.getDescrs(); + assertThat(constraints.size()).isEqualTo(1); + assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\""); + } + + @Test + public void parse_PluggableOperators2() throws Exception { + final String text = "rule \"tt\"\n" + + " dialect \"mvel\"\n" + + "when\n" + + " exists (TelephoneCall( this finishes [1m] \"25-May-2011\" ))\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) ((ExistsDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 )).getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("TelephoneCall"); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(constr.getText()).isEqualTo("this finishes [1m] \"25-May-2011\""); + + } + + @Test + public void parse_InlineEval() throws Exception { + final String text = "rule \"inline eval\"\n" + + "when\n" + + " Person( eval( name.startsWith(\"b\") && name.finishesWith(\"b\")) )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("Person"); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(constr.getText()).isEqualToIgnoringWhitespace("eval( name.startsWith(\"b\") && name.finishesWith(\"b\"))"); + + } + + @Test + public void parse_InfinityLiteral() throws Exception { + final String text = "rule \"infinity\"\n" + + "when\n" + + " StockTick( this after[-*,*] $another )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("StockTick"); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(constr.getText()).isEqualTo("this after[-*,*] $another"); + + } + + @Test + public void parse_EntryPointDeclaration() throws Exception { + final String text = "package org.drools\n" + + "declare entry-point eventStream\n" + + " @source(\"jndi://queues/events\")\n" + + " @foo( true )\n" + + "end"; + PackageDescr pkg = parser.parse( + text ); + + assertThat(pkg.getName()).isEqualTo("org.drools"); + assertThat(pkg.getEntryPointDeclarations().size()).isEqualTo(1); + + EntryPointDeclarationDescr epd = pkg.getEntryPointDeclarations().iterator().next(); + + assertThat(epd.getEntryPointId()).isEqualTo("eventStream"); + assertThat(epd.getAnnotations().size()).isEqualTo(2); + assertThat(epd.getAnnotation("source").getValue()).isEqualTo("\"jndi://queues/events\""); + assertThat(epd.getAnnotation("foo").getValue()).isEqualTo("true"); + } + + @Test + public void parse_WindowDeclaration() throws Exception { + final String text = "package org.drools\n" + + "declare window Ticks\n" + + " @doc(\"last 10 stock ticks\")\n" + + " $s : StockTick( source == \"NYSE\" )\n" + + " over window:length( 10, $s.symbol )\n" + + " from entry-point stStream\n" + + "end"; + PackageDescr pkg = parser.parse( + text ); + + assertThat(pkg.getName()).isEqualTo("org.drools"); + assertThat(pkg.getWindowDeclarations().size()).isEqualTo(1); + + WindowDeclarationDescr wdd = pkg.getWindowDeclarations().iterator().next(); + + assertThat(wdd.getName()).isEqualTo("Ticks"); + assertThat(wdd.getAnnotations().size()).isEqualTo(1); + assertThat(wdd.getAnnotation("doc").getValue()).isEqualTo("\"last 10 stock ticks\""); + + PatternDescr pd = wdd.getPattern(); + assertThat(pd).isNotNull(); + assertThat(pd.getIdentifier()).isEqualTo("$s"); + assertThat(pd.getObjectType()).isEqualTo("StockTick"); + assertThat(pd.getSource().getText()).isEqualTo("stStream"); + + assertThat(pd.getBehaviors().size()).isEqualTo(1); + BehaviorDescr bd = pd.getBehaviors().get( 0 ); + assertThat(bd.getType()).isEqualTo("window"); + assertThat(bd.getSubType()).isEqualTo("length"); + assertThat(bd.getParameters().size()).isEqualTo(2); + assertThat(bd.getParameters().get(0)).isEqualTo("10"); + assertThat(bd.getParameters().get(1)).isEqualTo("$s.symbol"); + } + + @Disabled("Priority : Mid | Implement using declared window. Not written in docs, but unit tests found.") + @Test + public void parse_WindowUsage() throws Exception { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " StockTick() from window Y\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parser.parse( + text ); + + assertThat(pkg.getName()).isEqualTo("org.drools"); + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rd = pkg.getRules().get(0); + + assertThat(rd.getName()).isEqualTo("X"); + assertThat(rd.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr pd = (PatternDescr) rd.getLhs().getDescrs().get(0); + assertThat(pd).isNotNull(); + assertThat(pd.getObjectType()).isEqualTo("StockTick"); + assertThat(pd.getSource().getText()).isEqualTo("Y"); + } + + @Test + public void endInRhs() throws Exception { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " System.out.println($s.endsWith(\"xyz\"));\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text ); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("System.out.println($s.endsWith(\"xyz\"));"); + } + + @Test + public void endTokenInRhs() throws Exception { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " int end = 10;\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text ); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int end = 10;"); + } + + @Test + public void ruleTokenInRhs() throws Exception { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " int rule = 10;\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text ); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int rule = 10;"); + } +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml b/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml new file mode 100644 index 00000000000..7740901e7d3 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml @@ -0,0 +1,16 @@ + + + + + + %date{HH:mm:ss.SSS} [%thread] %-5level %class{36}.%method:%line - %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl new file mode 100644 index 00000000000..74cff04d3c1 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule test_rule extends rule1 + when + $foo : foo() + then + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl new file mode 100644 index 00000000000..122634a9b26 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +package org.drools.compiler + +rule test_rule + @fooMeta1(barVal1) + @fooMeta2(barVal2) + when + then + System.out.println("Consequence"); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl new file mode 100644 index 00000000000..c009e6ec210 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl @@ -0,0 +1,28 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule test + when + A() + ( B() and C() ) or + ( D() and E() ) or + ( F() and G() ) + then + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl new file mode 100755 index 00000000000..7f3f4ce75f9 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateParserTest" +when + Integer() from accumulate( Person( age > 21 ), + init( int x = 0; ), + action( x++; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl new file mode 100755 index 00000000000..43ee672e90b --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl @@ -0,0 +1,23 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateReverseParserTest" +when + Number() from accumulate( Person( $age : age > 21 ), + average( $age ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl new file mode 100755 index 00000000000..0557d308f43 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule "Accumulate 1" +when + accumulate( Cheese( $price : price ), + $a1 : average( $price ), + $m1 : min( $price ), + $M1 : max( $price ) // binds are optional, but it makes no sense to not have a binding in this case + ) +then + // do something +end + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl new file mode 100755 index 00000000000..9c146f05edb --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl @@ -0,0 +1,32 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule "Accumulate 1" +when + accumulate( Cheese( $price : price ); + $a1 : average( $price ), + $m1 : min( $price ), + $M1 : max( $price ); // binds are optional, but it makes no sense to not have a binding in this case + $a1 > 10 && $M1 <= 100, + $m1 == 5 // inline evals + ) +then + // do something +end + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl new file mode 100755 index 00000000000..76872623dda --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateReverseParserTest" +when + Integer() from accumulate( Person( age > 21 ), + init( int x = 0; ), + action( x++; ), + reverse( x--; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl new file mode 100755 index 00000000000..8d3f6828f50 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateMultiPatternParserTest" +when + $counter:Integer() from accumulate( $person : Person( age > 21 ) and Cheese( type == $person.likes ), + init( int x = 0; ), + action( x++; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl new file mode 100755 index 00000000000..75d70816931 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateParserTest" +when + $counter:Integer() from accumulate( $person : Person( age > 21 ), + init( int x = 0; ), + action( x++; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl new file mode 100755 index 00000000000..3696836b1f2 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +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() ), + max( $age ) ); +then +end + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl new file mode 100644 index 00000000000..5155aa035de --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl @@ -0,0 +1,22 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule almost_empty + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl new file mode 100644 index 00000000000..e81b1d4a18f --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +import org.drools.compiler.Person + +rule simple_rule + when + Person(name == "mark") and Cheese(type == "stilton") + Person(name == "mark") or Cheese(type == "stilton") + then + System.out.println( "Mark and Michael" ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl new file mode 100644 index 00000000000..48fa4c52a19 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule rule1 + auto-focus true + when + not Cheese(type == "stilton") + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl new file mode 100644 index 00000000000..7c48ee595b5 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +rule "like cheddar" + when + Cheese( $type:type ) + then + System.out.println("I like " + $type); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl new file mode 100644 index 00000000000..6aabea7bd1b --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl @@ -0,0 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; +import org.drools.compiler.Person; + +rule "Who likes Stilton" + when + Cheese($type : type == "stilton") + $person : Person( $name : name == "bob", likes == $type) + then + System.out.println( $name + " likes " + $type); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl new file mode 100644 index 00000000000..8259a28773c --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl @@ -0,0 +1,23 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + ( (not Foo(x=="a") or Foo(x=="y") ) and ( Shoes() or Butt() ) ) + then +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl new file mode 100755 index 00000000000..839e2c6c19e --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl @@ -0,0 +1,22 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "CollectParserTest" +when + $personList : ArrayList() from collect( Person( age > 21 ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl new file mode 100755 index 00000000000..146b9e46c6a --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl @@ -0,0 +1,24 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "CollectParserTest" +when + // below statement makes no sense, but is useful to test parsing recursiveness + $personList : ArrayList() from collect( $p : Person( age > 21 || age < 10 ) from collect( People() from $town.getPeople() ) ); +then +end + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl new file mode 100644 index 00000000000..e46ecbe4601 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl @@ -0,0 +1,32 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +//this starts with a comment +package foo.bar + +//and another comment + +/* +yet + another + style +*/ + +rule "test" + when + then +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl new file mode 100644 index 00000000000..b2cf4cb9c84 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl @@ -0,0 +1,5 @@ +#place your comments here - this is just a description for your own purposes. +[when]There is a Person with name of {name}=Person(name=="{name}") +[when]Person is at least {age} years old and lives in {location}=Person(age > {age}, location == "{location}") +[then]Log "{message}"=System.out.println("{message}"); +[when]Or=or diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl new file mode 100644 index 00000000000..836a53dcd57 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl @@ -0,0 +1,48 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + +rule myrule + when + then + int i = 0; + i = 1; + i / 1; + i == 1; + i(i); + i = 'i'; + i.i.i; + ii; + i="i"; + ++i; + i++; + --i; + i--; + i += i; + i -= i; + i *= i; + i /= i; + int i = 5; + for(int j; j 21, $likes : likes ) + Cheese( type == $likes ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl new file mode 100644 index 00000000000..d387cf9c647 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl @@ -0,0 +1,23 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "ForallParserTest" +when + forall( Person( age > 21, $likes : likes ) from $village + Cheese( type == $likes ) from $cheesery ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl new file mode 100644 index 00000000000..47f918be139 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl @@ -0,0 +1,31 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule using_from + when + Foo() from bar.baz + Foo() from bar.baz["key"] + Foo() from bar.baz[$key] + Foo() from bar.baz[1] + Whee(bar=="baz") from whee("y") + f: Foo(la==2) from bar.la(x) + Bam() from wa() + Kah() from la.wa(42, 42.42, false, null) + Bam(a=="c") + then + whee(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl new file mode 100644 index 00000000000..98df27bf96a --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl @@ -0,0 +1,31 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package foo + +function String[] yourFunction(String args[]) { + baz(); +} + +rule "new rule" + + when + Something() + then + yourFunction(new String[] {"a","b","c"}); + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl new file mode 100644 index 00000000000..2a543650f58 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +import java.lang.String + +function String functionA(String s, Integer i) { + + foo(); + +} + +function void functionB() { + bar(); +} + + +rule something + when + then +end + +rule "one more thing" + when + then +end + + + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl new file mode 100644 index 00000000000..ed6d45ff31f --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +global java.lang.String foo +global java.lang.Integer bar; + +rule baz + when + Cheese( ) + then + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl new file mode 100644 index 00000000000..54f5225c3e8 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +//testing 'in' operator + +rule simple_rule + when + Person(age > 30 && < 40) + Vehicle(type in ( "sedan", "wagon" ), age < 3) + then + consequence(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl new file mode 100644 index 00000000000..3d4d2df7c75 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl @@ -0,0 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + foo3 : Bar(a==3) ; foo4 : Bar(a4:a==4) ; Baz() + then + if ( a == b ) { + assert( foo3 ); + } else { + retract( foo4 ); + } + System.out.println( a4 ); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl new file mode 100644 index 00000000000..a1d01a65573 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +//check that it can handle true/false literals, and +//negative numbers +rule simple_rule + when + Foo(bar == false) + Foo(boo > -42) + Foo(boo > -42.42) + then + cons(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl new file mode 100644 index 00000000000..92a142ec007 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl @@ -0,0 +1,6 @@ +#place your comments here - this is just a description for your own purposes. +[when]There is a Person with=Person() +[when]- age less than {age}=age < {age} +[when]- location is '{city}'=location=={city} +[when]Bar bar black sheep=Bar() +[then]Log "{message}"=System.out.println("{message}"); diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl new file mode 100644 index 00000000000..067e55fdb9d --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl @@ -0,0 +1,34 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.integrationtests.Cheese; + +rule "Like Stilton" + when + Cheese( t:type == "stilton" ) + then + System.out.println("I like " + t); +end + +rule "Like Cheddar" + when + Cheese( t:type == "cheddar" ) + then + System.out.println("I like " + t ); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl new file mode 100755 index 00000000000..0b11f17c562 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "test nested CEs" + when + not ( State( $state : state ) and + not( Person( status == $state, $likes : likes ) and + Cheese( type == $likes ) ) ) + Person( name == "Bob" ) + ( Cheese( price == 10 ) or Cheese( type == "brie" ) ) + then + results.add("OK"); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl new file mode 100644 index 00000000000..768fa8775c8 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule rule1 + no-loop false + when + not Cheese(type == "stilton") + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl new file mode 100644 index 00000000000..8ec3fd4f86e --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package HR1 + +rule simple_rule + when + not ( Cheese(type == "stilton") ) + exists ( Foo() ) + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl new file mode 100644 index 00000000000..573fe4808d6 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl @@ -0,0 +1,31 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +global java.util.List list; +global java.lang.Integer five; + +rule "not rule test" + when + $person : Person( $likes:like ) + not Cheese( type == $likes ) + then + list.add( $person ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl new file mode 100644 index 00000000000..a2eae254405 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +//testing not 'in' operator + +rule simple_rule + when + Person(age > 30 && < 40) + Vehicle(type not in ( "sedan", "wagon" ), age < 3) + then + consequence(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl new file mode 100644 index 00000000000..87907a60b7a --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +import org.drools.compiler.Person + +rule simple_rule + when + foo : ( Person(name == "mark") or Person(type == "fan") ) + Cheese(type == "green") + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl new file mode 100644 index 00000000000..2090d8f8565 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + +rule simple_rule + when + foo : ( Person(name == "mark") + or + Person(type == "fan") ) + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl new file mode 100644 index 00000000000..a96bae49029 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule simple_rule + when + foo : ( + Person(name == "mark") or Person(type == "fan") + ) + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl new file mode 100644 index 00000000000..3e576f091a8 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule "testing OR CE" +when + $p : Person( name == "bob" ) + $c : Cheese( type == $p.likes ) or Cheese( price == 10 ) +then + // do something +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl new file mode 100644 index 00000000000..ecf9ddb2338 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +import org.drools.compiler.Person + +rule simple_rule + when + Person(name == "mark") or + ( Person(type == "fan") and Cheese(type == "green") ) + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl new file mode 100644 index 00000000000..156f5c58f6d --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl @@ -0,0 +1,40 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package com.foo; + +agenda-group "x" + +import goo.ber +import wee.waa + + +dialect "java" + + + + +rule bar + when + then +end + +rule baz + dialect "mvel" + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl new file mode 100644 index 00000000000..59c31d2c8e7 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl @@ -0,0 +1,28 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule "test pluggable operators" +when + $a : EventA() + $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 ) +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl new file mode 100644 index 00000000000..9347834bbbb --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +rule "Who likes Stilton" + when + com.cheeseco.Cheese($type : type == "stilton") + then + System.out.println( $name + " likes " + $type); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl new file mode 100644 index 00000000000..e9b9be3edd2 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl @@ -0,0 +1,47 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +package foo + +rule bar + when + Baz() + then + Boo() +end + +query "simple_query" + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + +end + +rule bar2 + when + Baz() + then + Boo() +end + +query "simple_query2" + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl new file mode 100644 index 00000000000..9eda0358e56 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl @@ -0,0 +1,21 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "quoted string name" + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl new file mode 100644 index 00000000000..edf674db5ed --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +//this is for showing off all the new multi restriction stuff + +rule simple_rule + when + Person(age > 30 && < 40) + Vehicle(type == "sedan" || == "wagon", age < 3) + then + consequence(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl new file mode 100644 index 00000000000..faf0d0c3351 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl @@ -0,0 +1,33 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + + +rule simple_rule + // attributes keywork (and colon) is totally optional + salience 42 + agenda-group "my_group" + no-loop + duration 42 + activation-group "my_activation_group" + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl new file mode 100644 index 00000000000..cece840aa59 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl @@ -0,0 +1,46 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package foo.bar + + +rule rule1 + salience (42) + agenda-group "my_group" + when + Foo() + then + bar(); +end + +rule rule2 + salience (Integer.MIN_VALUE) + no-loop + when + Foo() + then + bar(); +end + +rule rule3 + enabled (Boolean.TRUE) + activation-group "my_activation_group" + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl new file mode 100644 index 00000000000..fafc7032171 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl @@ -0,0 +1,28 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + + +rule simple_rule + attributes: + salience 42, agenda-group "my_group", no-loop, lock-on-active, duration 42, activation-group "my_activation_group" + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl new file mode 100644 index 00000000000..2605f494aa9 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + calendars "cal1" + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl new file mode 100644 index 00000000000..31040f9e95f --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + calendars "cal 1", "cal 2", "cal 3" + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl new file mode 100644 index 00000000000..c0ca3ba4430 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + duration ( 1h30m ) + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl new file mode 100644 index 00000000000..12550c159c7 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + enabled ( 1 + 1 == 2 ) + salience ( 1+2 ) + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl new file mode 100644 index 00000000000..cd14e5699a6 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule "1. Do Stuff!" + when + then +end + +rule "2. Do More Stuff!" + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl new file mode 100644 index 00000000000..96a2448ca41 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl @@ -0,0 +1,24 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + not Cheese(type == "stilton") + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl new file mode 100755 index 00000000000..8b48eea0fe9 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule rule1 + ruleflow-group "a group" + when + not Cheese(type == "stilton") + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl new file mode 100644 index 00000000000..7d25f230e25 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.mvel.compiler + +global java.util.List list; + +rule "rule1" +when + Pattern1(); + Pattern2() from x.y.z; +then + System.out.println("Test"); +end; + +query "query1" + Pattern5(); + Pattern6(); + Pattern7(); +end; + +rule "rule2" +when + Pattern3(); + Pattern4() from collect( Pattern5() ); +then + System.out.println("Test"); +end; + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl new file mode 100644 index 00000000000..2532abc0b6c --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + +query "simple_query" + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl new file mode 100644 index 00000000000..afc7e6480b0 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl @@ -0,0 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ +rule simple_rule + when + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + then + if ( a == b ) { + assert( foo3 ); + } else { + retract( foo4 ); + } + System.out.println( a4 ); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl new file mode 100644 index 00000000000..0b6c21d5bc4 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package nesting; + + + + +rule "test something" + + when + p: Person( name soundslike "Michael" ) + then + p.name = "goober" + System.out.println(p.name) +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl new file mode 100644 index 00000000000..4b0b93995d1 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl @@ -0,0 +1,45 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +package com.foo; + +import im.one + +import im.two + +rule foo + when + then +end + +function cheeseIt() { + +} + +import im.three; + +rule bar + when + then +end + +function uncheeseIt() { + +} + +import im.four; \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl new file mode 100644 index 00000000000..23013d6b5d2 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package foo + +rule rule_one + when + Foo() + then + if (speed > speedLimit ? true : false;) + pullEmOver(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl new file mode 100644 index 00000000000..7c7df07bd51 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl @@ -0,0 +1,34 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package la + + +rule simple_rule + when + Baz() + then + //woot + first; + + // + + /* lala + + */ + second; +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl new file mode 100755 index 00000000000..4c50536c900 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl @@ -0,0 +1,24 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule blah + when + Col1() from doIt1( foo,bar,42,"hello",[ a : "b"], [a, "b", 42] ).doIt2(bar, [a, "b", 42]).field["key"] + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl new file mode 100644 index 00000000000..de85f100561 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +rule "simple rule" + when + Cheese( ) + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl new file mode 100644 index 00000000000..f867e69fe2d --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + + +rule simple_rule + when + Foo( + bar == baz, la==laz + ) + then +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl new file mode 100644 index 00000000000..1b56f045643 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl @@ -0,0 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package HR1 + +import function abd.def.x +import function qed.wah.* + +rule simple_rule + when + not ( Cheese(type == "stilton") ) + exists ( Foo() ) + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl new file mode 100644 index 00000000000..2bf358046e0 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule blah + + when + + Col1() from something.doIt["key"] + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl new file mode 100644 index 00000000000..da376e84385 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule blah + + when + + Col1() from something.doIt + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl new file mode 100644 index 00000000000..af156c5ea1c --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule blah + + when + + Col1() from doIt( foo,bar,42,"hello",[ a : "b", "something" : 42, "a" : foo, x : [x:y]],"end", [a, "b", 42] ) + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl new file mode 100644 index 00000000000..a8e32df1d53 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule blah + + when + + Col1() from something.doIt( foo,bar,42,"hello",[ a : "b", "something" : 42, "a" : foo, x : [x:y]],"end", [a, "b", 42] ) + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl new file mode 100644 index 00000000000..708bd667b0a --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl @@ -0,0 +1,48 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +declare NetworkNode + locElevation: java.math.BigDecimal + name: String @key + nodeClass: String + locLongitude: java.math.BigDecimal + nodeType: String + locLatitude: java.math.BigDecimal +end + +declare NetworkConnection + id: String @key + node1: NetworkNode + node2: NetworkNode + hops: Integer +end + +declare NetworkEvent + @role( event ) + @timestamp( creationTime ) + + id: String @key + locElevation: java.math.BigDecimal + description: String + sourceComponent: NetworkNode + locLongitude: java.math.BigDecimal + severity: Integer + creationTime: java.util.Date + locLatitude: java.math.BigDecimal +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl new file mode 100644 index 00000000000..c2e0145747d --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + Foo() + Bar() + eval(abc("foo")) + then + Kapow +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl new file mode 100644 index 00000000000..41ff2715d8a --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl @@ -0,0 +1,23 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + Person( $age2:age, $age2 == $age1+2 ) + then +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl new file mode 100644 index 00000000000..8db9671fee7 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl @@ -0,0 +1,23 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + Foo(name== (a + b)) + then +end diff --git a/drools-drl/drools-drl-parser/pom.xml b/drools-drl/drools-drl-parser/pom.xml index 545625e5ad4..0eeb7871009 100644 --- a/drools-drl/drools-drl-parser/pom.xml +++ b/drools-drl/drools-drl-parser/pom.xml @@ -66,7 +66,32 @@ org.antlr antlr-runtime + + org.antlr + antlr4-runtime + + + + org.assertj + assertj-core + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + ch.qos.logback + logback-classic + test + @@ -101,6 +126,26 @@ + + + + org.antlr + antlr4-maven-plugin + ${version.org.antlr4} + + + + antlr4 + + + true + false + src/main/antlr4/org/drools/drl10/parser/ + + + + + diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 new file mode 100644 index 00000000000..ef6e0982672 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 @@ -0,0 +1,847 @@ +parser grammar DRL6Expressions; + +options { + language = Java; + tokenVocab = DRLLexer; + superClass=DRLExpressions; +} + +@header { + import java.util.LinkedList; + import org.drools.drl.parser.DroolsParserException; + import org.drools.drl.parser.lang.DroolsEditorType; + import org.drools.drl.parser.lang.DroolsParserExceptionFactory; + import org.drools.drl.parser.lang.DroolsSentence; + import org.drools.drl.parser.lang.DroolsSoftKeywords; + import org.drools.drl.parser.lang.Location; + + import org.drools.drl.ast.dsl.AnnotatedDescrBuilder; + import org.drools.drl.ast.dsl.AnnotationDescrBuilder; + + import org.drools.drl.ast.descr.AnnotatedBaseDescr; + import org.drools.drl.ast.descr.AnnotationDescr; + import org.drools.drl.ast.descr.AtomicExprDescr; + import org.drools.drl.ast.descr.BaseDescr; + import org.drools.drl.ast.descr.BindingDescr; + import org.drools.drl.ast.descr.ConstraintConnectiveDescr; + import org.drools.drl.ast.descr.RelationalExprDescr; +} + +@members { + private ParserHelper helper; + + public DRL6Expressions(TokenStream input, + ParserHelper helper ) { + this( input ); + this.helper = helper; + } + + public ParserHelper getHelper() { return helper; } + public boolean hasErrors() { return helper.hasErrors(); } + public List getErrors() { return helper.getErrors(); } + public List getErrorMessages() { return helper.getErrorMessages(); } + public void enableEditorInterface() { helper.enableEditorInterface(); } + public void disableEditorInterface() { helper.disableEditorInterface(); } + public LinkedList getEditorInterface() { return helper.getEditorInterface(); } + public void reportError(RecognitionException ex) { helper.reportError( ex ); } + public void emitErrorMessage(String msg) {} + + private boolean buildDescr; + private int inMap = 0; + private int ternOp = 0; + private boolean hasBindings; + public void setBuildDescr( boolean build ) { this.buildDescr = build; } + public boolean isBuildDescr() { return this.buildDescr; } + + public void setLeftMostExpr( String value ) { helper.setLeftMostExpr( value ); } + public String getLeftMostExpr() { return helper.getLeftMostExpr(); } + + public void setHasBindings( boolean value ) { this.hasBindings = value; } + public boolean hasBindings() { return this.hasBindings; } + + @Override + public final BaseDescr conditionalOrExpressionDescr() throws RecognitionException { + return conditionalOrExpression().result; + } + + private boolean isNotEOF() { + // TODO verify that we can omit the backtracking check + /*if (state.backtracking != 0){ + return false; + }*/ + if (_input.get( _input.index() - 1 ).getType() == DRLLexer.WS){ + return true; + } + if (_input.LA(-1) == DRLLexer.LPAREN){ + return true; + } + return _input.get( _input.index() ).getType() != DRLLexer.EOF; + } + + private boolean notStartWithNewline() { + int currentTokenIndex = _input.index(); // current position in input stream + Token previousHiddenToken = _input.get(currentTokenIndex - 1); + String previousHiddenTokenText = previousHiddenToken.getText(); + return !previousHiddenTokenText.contains("\n"); + } +} + +// Alter code generation so catch-clauses get replace with +// this action. +@rulecatch { +catch (RecognitionException re) { + throw re; +} +} + +// -------------------------------------------------------- +// GENERAL RULES +// -------------------------------------------------------- +literal + : STRING_LITERAL { helper.emit($STRING_LITERAL, DroolsEditorType.STRING_CONST); } + | DRL_STRING_LITERAL { helper.emit($DRL_STRING_LITERAL, DroolsEditorType.STRING_CONST); } + | DECIMAL_LITERAL { helper.emit($DECIMAL_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | HEX_LITERAL { helper.emit($HEX_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | FLOAT_LITERAL { helper.emit($FLOAT_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | BOOL_LITERAL { helper.emit($BOOL_LITERAL, DroolsEditorType.BOOLEAN_CONST); } + | NULL_LITERAL { helper.emit($NULL_LITERAL, DroolsEditorType.NULL_CONST); } + | TIME_INTERVAL { helper.emit($TIME_INTERVAL, DroolsEditorType.NULL_CONST); } + | MUL { helper.emit($MUL, DroolsEditorType.NUMERIC_CONST); } // this means "infinity" in Drools + ; + +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 ); } } + : 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); } + | rop=relationalOp { $negated = $rop.negated; $opr=($x != null ? $x.text : "")+$rop.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 ); } } + : ( 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);} + | op=GT { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | xop=complexOp { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | not_key nop=neg_operator_key { $negated = true; $opr=$nop.text;} + | cop=operator_key { $negated = false; $opr=$cop.text;} + ) + ; + +complexOp returns [String opr] + : t=TILDE e=ASSIGN { $opr=$t.text+$e.text; } + ; + +typeList + : type (COMMA type)* + ; + +type + : tm=typeMatch + ; + +typeMatch + : primitiveType (LBRACK RBRACK)* + | IDENTIFIER (typeArguments)? (DOT IDENTIFIER (typeArguments)? )* (LBRACK RBRACK)* + ; + +typeArguments + : LT typeArgument (COMMA typeArgument)* GT + ; + +typeArgument + : type + | QUESTION ((extends_key | super_key) type)? + ; + +// -------------------------------------------------------- +// EXPRESSIONS +// -------------------------------------------------------- +// the following dymmy rule is to force the AT symbol to be +// included in the follow set of the expression on the DFAs +dummy + : expression ( AT | SEMI | EOF | IDENTIFIER | RPAREN ) ; + +dummy2 + : relationalExpression EOF; + +// top level entry point for arbitrary expression parsing +expression returns [BaseDescr result] + : left=conditionalExpression { if( buildDescr ) { $result = $left.result; } } + (op=assignmentOperator right=expression)? + ; + +conditionalExpression returns [BaseDescr result] + : left=conditionalOrExpression { if( buildDescr ) { $result = $left.result; } } + ternaryExpression? + ; + +ternaryExpression +@init{ ternOp++; } + : QUESTION ts=expression COLON fs=expression + ; +finally { ternOp--; } + + +fullAnnotation [AnnotatedDescrBuilder inDescrBuilder] returns [AnnotationDescr result] +@init{ String n = ""; AnnotationDescrBuilder annoBuilder = null; } + : AT name=IDENTIFIER { n = $name.text; } ( DOT x=IDENTIFIER { n += "." + $x.text; } )* + { if( buildDescr ) { + if ( inDescrBuilder == null ) { + $result = new AnnotationDescr( n ); + } else { + annoBuilder = inDescrBuilder instanceof AnnotationDescrBuilder ? + ((AnnotationDescrBuilder) inDescrBuilder).newAnnotation( n ) : inDescrBuilder.newAnnotation( n ); + $result = (AnnotationDescr) annoBuilder.getDescr(); + } + } + } + annotationArgs[$result, annoBuilder] + ; + +annotationArgs [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] + : LPAREN + ( + annotationElementValuePairs[descr, inDescrBuilder] + | value=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setValue( $value.result ); } } + )? + RPAREN + ; + +annotationElementValuePairs [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] + : annotationElementValuePair[descr, inDescrBuilder] ( COMMA annotationElementValuePair[descr, inDescrBuilder] )* + ; + +annotationElementValuePair [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] + : key=IDENTIFIER ASSIGN val=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setKeyValue( $key.text, $val.result ); } } + ; + +annotationValue[AnnotatedDescrBuilder inDescrBuilder] returns [Object result] + : exp=expression { if ( buildDescr ) $result = $exp.text; } + | annos=annotationArray[inDescrBuilder] { if ( buildDescr ) $result = $annos.result.toArray(); } + | anno=fullAnnotation[inDescrBuilder] { if ( buildDescr ) $result = $anno.result; } + ; + +annotationArray[AnnotatedDescrBuilder inDescrBuilder] returns [java.util.List result] +@init { $result = new java.util.ArrayList();} + : LBRACE ( anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } + ( COMMA anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } )* )? + RBRACE + ; + + + +conditionalOrExpression returns [BaseDescr result] + : left=conditionalAndExpression { if( buildDescr ) { $result = $left.result; } } + ( OR + { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } + args=fullAnnotation[null]? right=conditionalAndExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newOr(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } + $result = descr; + } + } + )* + ; + +conditionalAndExpression returns [BaseDescr result] + : left=inclusiveOrExpression { if( buildDescr ) { $result = $left.result; } } + ( AND + { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } + args=fullAnnotation[null]? right=inclusiveOrExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newAnd(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } + $result = descr; + } + } + )* + ; + +inclusiveOrExpression returns [BaseDescr result] + : left=exclusiveOrExpression { if( buildDescr ) { $result = $left.result; } } + ( BITOR right=exclusiveOrExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newIncOr(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + $result = descr; + } + } + )* + ; + +exclusiveOrExpression returns [BaseDescr result] + : left=andExpression { if( buildDescr ) { $result = $left.result; } } + ( CARET right=andExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newXor(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + $result = descr; + } + } + )* + ; + +andExpression returns [BaseDescr result] + : left=equalityExpression { if( buildDescr ) { $result = $left.result; } } + ( BITAND right=equalityExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newIncAnd(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + $result = descr; + } + } + )* + ; + +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 ); } + right=instanceOfExpression + { if( buildDescr ) { + $result = new RelationalExprDescr( $op.text, false, null, $left.result, $right.result ); + } + } + )* + ; + +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 ); } + right=type + { if( buildDescr ) { + $result = new RelationalExprDescr( $op.text, false, null, $left.result, new AtomicExprDescr($right.text) ); + } + } + )? + ; + +inExpression returns [BaseDescr result] +@init { ConstraintConnectiveDescr descr = null; BaseDescr leftDescr = null; BindingDescr binding = null; } +@after { if( binding != null && descr != null ) descr.addOrMerge( binding ); } + : left=relationalExpression + { if( buildDescr ) { $result = $left.result; } + if( $left.result instanceof BindingDescr ) { + binding = (BindingDescr)$left.result; + leftDescr = new AtomicExprDescr( binding.getExpression() ); + } else { + leftDescr = $left.result; + } + } + (not_key in=in_key LPAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + e1=expression + { descr = ConstraintConnectiveDescr.newAnd(); + RelationalExprDescr rel1 = new RelationalExprDescr( "!=", false, null, leftDescr, $e1.result ); + descr.addOrMerge( rel1 ); + $result = descr; + } + (COMMA e2=expression + { RelationalExprDescr rel2 = new RelationalExprDescr( "!=", false, null, leftDescr, $e2.result ); + descr.addOrMerge( rel2 ); + } + )* RPAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } + | in=in_key LPAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + e1=expression + { descr = ConstraintConnectiveDescr.newOr(); + RelationalExprDescr rel1 = new RelationalExprDescr( "==", false, null, leftDescr, $e1.result ); + descr.addOrMerge( rel1 ); + $result = descr; + } + (COMMA e2=expression + { RelationalExprDescr rel2 = new RelationalExprDescr( "==", false, null, leftDescr, $e2.result ); + descr.addOrMerge( rel2 ); + } + )* RPAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } + )? + ; + +relationalExpression returns [BaseDescr result] +locals [ BaseDescr lsd ] +// TODO access lsd directly instead of through dynamic context here +@init { $relationalExpression::lsd = null; } + : left=shiftExpression + { if( buildDescr ) { + if ( $left.result == null ) { + $result = new AtomicExprDescr( $left.text ); + } else if ( $left.result instanceof AtomicExprDescr ) { + if ( $left.text.equals(((AtomicExprDescr)$left.result).getExpression()) ) { + $result = $left.result; + } else { + $result = new AtomicExprDescr( $left.text ) ; + } + } else if ( $left.result instanceof BindingDescr ) { + if ( $left.text.equals(((BindingDescr)$left.result).getExpression()) ) { + $result = $left.result; + } else { + BindingDescr bind = (BindingDescr) $left.result; + int offset = bind.isUnification() ? 2 : 1; + String fullExpression = $left.text.substring( $left.text.indexOf( ":" ) + offset ).trim(); + $result = new BindingDescr( bind.getVariable(), bind.getExpression(), fullExpression, bind.isUnification() ); + } + } else { + $result = $left.result; + } + // TODO access lsd directly instead of through dynamic context here + $relationalExpression::lsd = $result; + } + } + ( right=orRestriction + { if( buildDescr ) { + $result = $right.result; + // TODO access lsd directly instead of through dynamic context here + $relationalExpression::lsd = $result; + } + } + )* + ; + +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 ); } + ( sa=squareArguments value=shiftExpression + | value=shiftExpression + ) + { if( buildDescr ) { + BaseDescr descr = ( $value.result != null && + ( (!($value.result instanceof AtomicExprDescr)) || + ($value.text.equals(((AtomicExprDescr)$value.result).getExpression())) )) ? + $value.result : + new AtomicExprDescr( $value.text ) ; + $result = new RelationalExprDescr( $op.opr, $op.negated, $ctx.sa != null ? $sa.args : null, $relationalExpression::lsd, descr ); + if( $relationalExpression::lsd instanceof BindingDescr ) { + $relationalExpression::lsd = new AtomicExprDescr( ((BindingDescr)$relationalExpression::lsd).getExpression() ); + } + } + helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); + } + | LPAREN or=orRestriction RPAREN { $result = $or.result; } + ; + + + +shiftExpression returns [BaseDescr result] + : left=additiveExpression { if( buildDescr ) { $result = $left.result; } } + ( shiftOp additiveExpression )* + ; + +shiftOp + : ( LT LT + | GT GT GT + | GT GT ) + ; + +additiveExpression returns [BaseDescr result] + : left=multiplicativeExpression { if( buildDescr ) { $result = $left.result; } } + ( (ADD | SUB) multiplicativeExpression )* + ; + +multiplicativeExpression returns [BaseDescr result] + : left=unaryExpression { if( buildDescr ) { $result = $left.result; } } + ( ( MUL | DIV | MOD ) unaryExpression )* + ; + +unaryExpression returns [BaseDescr result] + : ADD ue=unaryExpression + { if( buildDescr ) { + $result = $ue.result; + if( $result instanceof AtomicExprDescr ) { + ((AtomicExprDescr)$result).setExpression( "+" + ((AtomicExprDescr)$result).getExpression() ); + } + } } + | SUB ue=unaryExpression + { if( buildDescr ) { + $result = $ue.result; + if( $result instanceof AtomicExprDescr ) { + ((AtomicExprDescr)$result).setExpression( "-" + ((AtomicExprDescr)$result).getExpression() ); + } + } } + | INC primary + | DEC primary + | left=unaryExpressionNotPlusMinus { if( buildDescr ) { $result = $left.result; } } + ; + +unaryExpressionNotPlusMinus returns [BaseDescr result] +@init { boolean isLeft = false; BindingDescr bind = null;} + : TILDE unaryExpression + | BANG ue=unaryExpression + { + if( buildDescr && $ue.result != null ) { + $result = $ue.result.negate(); + } + } + | castExpression + | backReferenceExpression + | { isLeft = helper.getLeftMostExpr() == null;} + ( ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.COLON}? (var=IDENTIFIER COLON + { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($COLON, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, false); helper.setStart( bind, $var ); } } )) + | ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.DRL_UNIFY}? (var=IDENTIFIER DRL_UNIFY + { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($DRL_UNIFY, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, true); helper.setStart( bind, $var ); } } )) + )? + + ( left2=xpathPrimary { if( buildDescr ) { $result = $left2.result; } } + | left1=primary { if( buildDescr ) { $result = $left1.result; } } + ) + + (selector)* + { + if( buildDescr ) { + String expr = $text; + if( isLeft ) { + helper.setLeftMostExpr( expr ); + } + if( bind != null ) { + if( bind.isUnification() ) { + expr = expr.substring( expr.indexOf( ":=" ) + 2 ).trim(); + } else { + expr = expr.substring( expr.indexOf( ":" ) + 1 ).trim(); + } + bind.setExpressionAndBindingField( expr ); + helper.setEnd( bind ); + $result = bind; + } + } + } + ((INC|DEC))? + ; + +castExpression + : LPAREN primitiveType RPAREN expr=unaryExpression + | LPAREN type RPAREN unaryExpressionNotPlusMinus + ; + +backReferenceExpression + : (DOT DOT DIV)+ unaryExpressionNotPlusMinus + ; + +primitiveType + : boolean_key + | char_key + | byte_key + | short_key + | int_key + | long_key + | float_key + | double_key + ; + +xpathSeparator + : DIV + | QUESTION_DIV + ; + +xpathPrimary returns [BaseDescr result] + : xpathChunk ({notStartWithNewline()}? xpathChunk)* + ; + +xpathChunk returns [BaseDescr result] + : xpathSeparator IDENTIFIER (DOT IDENTIFIER)* (HASH IDENTIFIER)? (LBRACK xpathExpressionList RBRACK)? + ; + +xpathExpressionList returns [java.util.List exprs] +@init { $exprs = new java.util.ArrayList();} + : f=expression { $exprs.add( $f.text ); } + (COMMA s=expression { $exprs.add( $s.text ); })* + ; + +primary returns [BaseDescr result] + : expr=parExpression { if( buildDescr ) { $result = $expr.result; } } + | nonWildcardTypeArguments (explicitGenericInvocationSuffix | this_key arguments) + | literal { if( buildDescr ) { $result = new AtomicExprDescr( $literal.text, true ); } } + //| this_key ({!helper.validateSpecialID(2)}? DOT IDENTIFIER)* ({helper.validateIdentifierSufix()}? identifierSuffix)? + | super_key superSuffix + | new_key creator + | primitiveType (LBRACK RBRACK)* DOT class_key + //| void_key DOT class_key + | inlineMapExpression + | inlineListExpression + | i1=IDENTIFIER { helper.emit($i1, DroolsEditorType.IDENTIFIER); } + ( + ( d=DOT i2=IDENTIFIER { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + | + ( d=(DOT|NULL_SAFE_DOT) LPAREN { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($LPAREN, DroolsEditorType.SYMBOL); } + expression (COMMA { helper.emit($COMMA, DroolsEditorType.SYMBOL); } expression)* + RPAREN { helper.emit($RPAREN, DroolsEditorType.SYMBOL); } + ) + | + ( h=HASH i2=IDENTIFIER { helper.emit($h, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + | + ( n=NULL_SAFE_DOT i2=IDENTIFIER { helper.emit($n, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + )* (identifierSuffix)? + ; + +inlineListExpression + : LBRACK expressionList? RBRACK + ; + +inlineMapExpression +@init{ inMap++; } + : LBRACK mapExpressionList RBRACK + ; +finally { inMap--; } + +mapExpressionList + : mapEntry (COMMA mapEntry)* + ; + +mapEntry + : expression COLON expression + ; + +parExpression returns [BaseDescr result] + : LPAREN expr=expression RPAREN + { if( buildDescr ) { + $result = $expr.result; + if( $result instanceof AtomicExprDescr ) { + ((AtomicExprDescr)$result).setExpression("(" +((AtomicExprDescr)$result).getExpression() + ")" ); + } + } + } + ; + +identifierSuffix + : (LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } + RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } )+ + DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } class_key + | (LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } + expression + RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } )+ // can also be matched by selector, but do here + | arguments +// | DOT class_key +// | DOT explicitGenericInvocation +// | DOT this_key +// | DOT super_key arguments +// | DOT new_key (nonWildcardTypeArguments)? innerCreator + ; + +creator + : nonWildcardTypeArguments? createdName + (arrayCreatorRest | classCreatorRest) + ; + +createdName + : IDENTIFIER typeArguments? + ( DOT IDENTIFIER typeArguments?)* + | primitiveType + ; + +innerCreator + : {!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? IDENTIFIER classCreatorRest + ; + +arrayCreatorRest + : LBRACK + ( RBRACK (LBRACK RBRACK)* arrayInitializer + | expression RBRACK ({!helper.validateLT(2,"]")}? LBRACK expression RBRACK)* (LBRACK RBRACK)* + ) + ; + +variableInitializer + : arrayInitializer + | expression + ; + +arrayInitializer + : LBRACE (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RBRACE + ; + +classCreatorRest + : arguments //classBody? //sotty: restored classBody to allow for inline, anonymous classes + ; + +explicitGenericInvocation + : nonWildcardTypeArguments arguments + ; + +nonWildcardTypeArguments + : LT typeList GT + ; + +explicitGenericInvocationSuffix + : super_key superSuffix + | IDENTIFIER arguments + ; + +selector + : DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } super_key superSuffix + | DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } new_key (nonWildcardTypeArguments)? innerCreator + | DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } + IDENTIFIER { helper.emit($IDENTIFIER, DroolsEditorType.IDENTIFIER); } + (arguments)? + | NULL_SAFE_DOT { helper.emit($NULL_SAFE_DOT, DroolsEditorType.SYMBOL); } + IDENTIFIER { helper.emit($IDENTIFIER, DroolsEditorType.IDENTIFIER); } + (arguments)? + //| DOT this_key + | LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } + expression + RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } + ; + +superSuffix + : arguments + | DOT IDENTIFIER (arguments)? + ; + +squareArguments returns [java.util.List args] + : LBRACK (el=expressionList { $args = $el.exprs; })? RBRACK + ; + +arguments + : LPAREN { helper.emit($LPAREN, DroolsEditorType.SYMBOL); } + expressionList? + RPAREN { helper.emit($RPAREN, DroolsEditorType.SYMBOL); } + ; + +expressionList returns [java.util.List exprs] +@init { $exprs = new java.util.ArrayList();} + : f=expression { $exprs.add( $f.text ); } + (COMMA s=expression { $exprs.add( $s.text ); })* + ; + +assignmentOperator + : ASSIGN + | ADD_ASSIGN + | SUB_ASSIGN + | MUL_ASSIGN + | DIV_ASSIGN + | AND_ASSIGN + | OR_ASSIGN + | XOR_ASSIGN + | MOD_ASSIGN + | LT LT ASSIGN + | GT GT GT ASSIGN + | GT GT ASSIGN + ; + +// -------------------------------------------------------- +// KEYWORDS +// -------------------------------------------------------- +extends_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.EXTENDS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +super_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.SUPER))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +instanceof_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +boolean_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.BOOLEAN))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +char_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.CHAR))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +byte_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.BYTE))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +short_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.SHORT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +int_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.INT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +float_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.FLOAT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +long_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.LONG))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +double_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.DOUBLE))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +void_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.VOID))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +this_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.THIS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +class_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.CLASS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +new_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.NEW))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +not_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.NOT))}? id=DRL_NOT { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +in_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.IN))}? id=DRL_IN { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +operator_key + // TODO get rid of the DRL_MATCHES token or introduce DRL_CONTAINS etc. for consistency. + : {(helper.isPluggableEvaluator(false))}? id=(IDENTIFIER|DRL_MATCHES) { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +neg_operator_key + : {(helper.isPluggableEvaluator(true))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 new file mode 100644 index 00000000000..8aac81873cc --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 @@ -0,0 +1,161 @@ +lexer grammar DRLLexer; + +import JavaLexer; + +@members { + public String normalizeString( String input ) { + if( input != null && (input.length() == 2 || input.length() >= 4) ) { + input = input.substring( 1, input.length() - 1 ); + input = input.replaceAll( "\'", "'" ); + input = input.replaceAll( "\"", "\\\"" ); + input = "\"" + input + "\""; + } + return input; + } +} + +///////////////// +// KEYWORDS +///////////////// + +// These keywords are already declared in JavaLexer. They should not be overriden with different names, or else Vocabulary's literalName will be null. +// So no need to declare by DRLLexer +// PACKAGE : 'package'; +// IMPORT : 'import'; +// STATIC : 'static'; +// EXTENDS : 'extends'; +// SUPER : 'super'; + +// DRL keywords +DRL_UNIT : 'unit'; +DRL_FUNCTION : 'function'; +DRL_GLOBAL : 'global'; +DRL_DECLARE : 'declare'; +DRL_RULE : 'rule'; +DRL_QUERY : 'query'; +DRL_WHEN : 'when'; +DRL_THEN : 'then' -> pushMode(RHS); +DRL_END : 'end'; + +DRL_AND : 'and'; +DRL_OR : 'or'; + +DRL_EXISTS : 'exists'; +DRL_NOT : 'not'; +DRL_IN : 'in'; +DRL_FROM : 'from'; +DRL_COLLECT : 'collect'; +DRL_MATCHES : 'matches'; +DRL_MEMBEROF : 'memberOf'; +DRL_ACCUMULATE : 'accumulate'; +DRL_ACC : 'acc'; +DRL_INIT : 'init'; +DRL_ACTION : 'action'; +DRL_REVERSE : 'reverse'; +DRL_RESULT : 'result'; +DRL_ENTRY_POINT : 'entry-point'; +DRL_EVAL : 'eval'; +DRL_FORALL : 'forall'; +DRL_OVER : 'over'; + +// temporal operators +DRL_AFTER : 'after'; +DRL_BEFORE : 'before'; +DRL_COINCIDES : 'coincides'; +DRL_DURING : 'during'; +DRL_INCLUDES : 'includes'; +DRL_FINISHES : 'finishes'; +DRL_FINISHED_BY : 'finishedby'; +DRL_MEETS : 'meets'; +DRL_MET_BY : 'metby'; +DRL_OVERLAPS : 'overlaps'; +DRL_OVERLAPPED_BY : 'overlappedby'; +DRL_STARTS : 'starts'; +DRL_STARTED_BY : 'startedby'; + +DRL_WINDOW : 'window'; + +// attributes +DRL_SALIENCE : 'salience'; +DRL_ENABLED : 'enabled'; +DRL_NO_LOOP : 'no-loop'; +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'; +DRL_DATE_EXPIRES : 'date-expires'; +DRL_DIALECT : 'dialect'; +DRL_CALENDARS : 'calendars'; +DRL_TIMER : 'timer'; +DRL_DURATION : 'duration'; + +///////////////// +// LEXER +///////////////// + +TIME_INTERVAL + : (('0'..'9')+ 'd') (('0'..'9')+ 'h')?(('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'h') (('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'm') (('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 's') (('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'ms') + ; + +DRL_STRING_LITERAL + : ('"' ( DrlEscapeSequence | ~('\\'|'"') )* '"') + | ('\'' ( DrlEscapeSequence | ~('\\'|'\'') )* '\'') { setText( normalizeString( getText() ) ); } + ; + +DRL_BIG_DECIMAL_LITERAL + : ('0'..'9')+ [B] + | ('0'..'9')+ '.' ('0'..'9')+ [B] + ; + +DRL_BIG_INTEGER_LITERAL + : ('0'..'9')+ [I] + ; + +///////////////// +// SYMBOLS +///////////////// + +HASH : '#'; +DRL_UNIFY : ':=' ; +NULL_SAFE_DOT : '!.' ; +QUESTION_DIV : '?/' ; + +MISC : '\'' | '\\' | '$' ; + +///////////////// +// Fragment +///////////////// +fragment +DrlEscapeSequence + : '\\' ('b'|'B'|'t'|'n'|'f'|'r'|'"'|'\''|'\\'|'.'|'o'| + 'x'|'a'|'e'|'c'|'d'|'D'|'s'|'S'|'w'|'W'|'p'|'A'| + 'G'|'Z'|'z'|'Q'|'E'|'*'|'['|']'|'('|')'|'$'|'^'| + '{'|'}'|'?'|'+'|'-'|'&'|'|') + | DrlUnicodeEscape + | DrlOctalEscape + ; + +fragment +DrlOctalEscape + : '\\' ('0'..'3') ('0'..'7') ('0'..'7') + | '\\' ('0'..'7') ('0'..'7') + | '\\' ('0'..'7') + ; + +fragment +DrlUnicodeEscape + : '\\' 'u' HexDigit HexDigit HexDigit HexDigit + ; + +mode RHS; +RHS_WS : [ \t\r\n\u000C]+ -> channel(HIDDEN); +DRL_RHS_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) {setText("end");} -> popMode; +RHS_CHUNK : ~[ \t\r\n\u000C]+ ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 new file mode 100644 index 00000000000..933c013ee6c --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 @@ -0,0 +1,495 @@ +parser grammar DRLParser; + +options { tokenVocab=DRLLexer; } + +import JavaParser; + + /* + * statement := importStatement + * | globalStatement + * | declare + * | rule + * | ruleAttribute + * | function + * | query + * ; + */ +compilationUnit : packagedef? unitdef? drlStatementdef* ; + +drlStatementdef + : importdef + | globaldef + | declaredef + | ruledef + | attributes + | functiondef + | querydef + ; + +packagedef : PACKAGE name=drlQualifiedName SEMI? ; + +unitdef : DRL_UNIT name=drlQualifiedName SEMI? ; + +importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? SEMI? #importStandardDef + | IMPORT (DRL_ACCUMULATE|DRL_ACC) drlQualifiedName IDENTIFIER SEMI? #importAccumulateDef + ; + +globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; + +/** + * declare := DECLARE + * | (ENTRY-POINT) => entryPointDeclaration + * | (WINDOW) => windowDeclaration + * | (TRAIT) => typeDeclaration (trait) + * | (ENUM) => enumDeclaration + * | typeDeclaration (class) + * END + */ + +declaredef : DRL_DECLARE ( + | entryPointDeclaration + | windowDeclaration + | typeDeclaration + ) DRL_END ; + +/* + * typeDeclaration := [TYPE] qualifiedIdentifier (EXTENDS qualifiedIdentifier)? + * annotation* + * field* + * END + */ + +typeDeclaration : name=drlQualifiedName (EXTENDS superType=drlQualifiedName)? drlAnnotation* field* ; + +// entryPointDeclaration := ENTRY-POINT stringId annotation* END + +entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* ; + +// windowDeclaration := WINDOW ID annotation* lhsPatternBind END + +windowDeclaration : DRL_WINDOW name=stringId drlAnnotation* lhsPatternBind ; + +// field := label fieldType (EQUALS_ASSIGN conditionalExpression)? annotation* SEMICOLON? + +field : label type (ASSIGN initExpr=conditionalOrExpression)? drlAnnotation* SEMI? ; + +// rule := RULE stringId (EXTENDS stringId)? annotation* attributes? lhs? rhs END + +ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* attributes? lhs rhs DRL_RHS_END ; + +// query := QUERY stringId parameters? annotation* lhsExpression END + +querydef : DRL_QUERY name=stringId formalParameters? drlAnnotation* lhsExpression+ DRL_END SEMI?; + +lhs : DRL_WHEN lhsExpression* ; + +lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed + | lhsUnary #lhsUnarySingle + | LPAREN DRL_AND lhsExpression+ RPAREN #lhsAnd + | lhsExpression (DRL_AND lhsExpression)+ #lhsAnd + | LPAREN DRL_OR lhsExpression+ RPAREN #lhsOr + | lhsExpression (DRL_OR lhsExpression)+ #lhsOr + ; + +// 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 lhsUnary)* + | LPAREN DRL_AND lhsUnary+ RPAREN + ; + +/* +lhsUnary : ( lhsExists namedConsequence? + | lhsNot namedConsequence? + | lhsEval consequenceInvocation* + | lhsForall + | lhsAccumulate + | LPAREN lhsOr RPAREN namedConsequence? + | lhsPatternBind consequenceInvocation* + ) SEMI? ; +*/ + +lhsUnary : ( + lhsExists + | lhsNot + | lhsEval + | lhsForall + | lhsAccumulate + | lhsPatternBind + ) SEMI? ; + +lhsPatternBind : (label|unif)? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; + +/* +lhsPattern : xpathPrimary (OVER patternFilter)? | + ( QUESTION? qualifiedIdentifier LPAREN positionalConstraints? constraints? RPAREN (OVER patternFilter)? (FROM patternSource)? ) ; +*/ + +lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN (DRL_OVER patternFilter)? (DRL_FROM patternSource)? ; +positionalConstraints : constraint (COMMA constraint)* SEMI ; +constraints : constraint (COMMA constraint)* ; +constraint : ( nestedConstraint | conditionalOrExpression ) ; +nestedConstraint : ( IDENTIFIER ( DOT | HASH ) )* IDENTIFIER DOT LPAREN constraints RPAREN ; +conditionalOrExpression : left=conditionalAndExpression (OR right=conditionalAndExpression)* ; +conditionalAndExpression : left=inclusiveOrExpression (AND right=inclusiveOrExpression)* ; +inclusiveOrExpression : left=exclusiveOrExpression (BITOR right=exclusiveOrExpression)* ; +exclusiveOrExpression : left=andExpression (CARET right=andExpression)* ; +andExpression : left=equalityExpression (BITAND right=equalityExpression)* ; +equalityExpression : label? left=instanceOfExpression ( ( op=EQUAL | op=NOTEQUAL ) right=instanceOfExpression )* ; +instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; +inExpression : left=relationalExpression ( 'not'? 'in' LPAREN drlExpression (COMMA drlExpression)* RPAREN )? ; +relationalExpression : left=drlExpression (right=orRestriction)* ; +orRestriction : left=andRestriction (OR right=andRestriction)* ; +andRestriction : left=singleRestriction (AND right=singleRestriction)* ; +singleRestriction : op=relationalOperator drlExpression ; + +relationalOperator + : EQUAL + | NOTEQUAL + | LE + | GE + | GT + | LT + | temporalOperator + ; + +/* function := FUNCTION type? ID parameters(typed) chunk_{_} */ +functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters block ; + + +/* extending JavaParser qualifiedName */ +drlQualifiedName + : drlIdentifier (DOT drlIdentifier)* + ; + +/* extending JavaParser identifier */ +drlIdentifier + : drlKeywords + | IDENTIFIER + | MODULE + | OPEN + | REQUIRES + | EXPORTS + | OPENS + | TO + | USES + | PROVIDES + | WITH + | TRANSITIVE + | YIELD + | SEALED + | PERMITS + | RECORD + | VAR + ; + +drlKeywords + : DRL_UNIT + | DRL_FUNCTION + | DRL_GLOBAL + | DRL_DECLARE + | DRL_RULE + | DRL_QUERY + | DRL_WHEN + | DRL_THEN + | DRL_END + | DRL_AND + | DRL_OR + | DRL_EXISTS + | DRL_NOT + | DRL_IN + | DRL_FROM + | DRL_MATCHES + | DRL_MEMBEROF + | DRL_ACCUMULATE + | DRL_ACC + | DRL_INIT + | DRL_ACTION + | DRL_REVERSE + | DRL_RESULT + | DRL_ENTRY_POINT + | DRL_EVAL + | DRL_SALIENCE + | DRL_ENABLED + | DRL_NO_LOOP + | DRL_AUTO_FOCUS + | DRL_LOCK_ON_ACTIVE + | DRL_REFRACT + | DRL_DIRECT + | DRL_AGENDA_GROUP + | DRL_ACTIVATION_GROUP + | DRL_RULEFLOW_GROUP + | DRL_DATE_EFFECTIVE + | DRL_DATE_EXPIRES + | DRL_DIALECT + | DRL_CALENDARS + | DRL_TIMER + | DRL_DURATION + ; + +/* extending JavaParser expression */ +drlExpression + : drlPrimary + | drlExpression bop=DOT + ( + drlIdentifier + | methodCall + | THIS + | NEW nonWildcardTypeArguments? innerCreator + | SUPER superSuffix + | explicitGenericInvocation + ) + | drlExpression LBRACK drlExpression RBRACK + | DRL_EVAL LPAREN conditionalOrExpression RPAREN + | methodCall + | NEW drlCreator + | LPAREN annotation* typeType (BITAND typeType)* RPAREN drlExpression + | drlExpression postfix=(INC | DEC) + | prefix=(ADD|SUB|INC|DEC) drlExpression + | prefix=(TILDE|BANG) drlExpression + | drlExpression bop=(MUL|DIV|MOD) drlExpression + | drlExpression bop=(ADD|SUB) drlExpression + | drlExpression (LT LT | GT GT GT | GT GT) drlExpression + | drlExpression bop=(LE | GE | GT | LT) drlExpression + | drlExpression temporalOperator drlExpression + | drlExpression bop=INSTANCEOF (typeType | pattern) + | drlExpression bop=DRL_MATCHES drlExpression + | drlExpression DRL_NOT? DRL_MEMBEROF drlExpression + | drlExpression bop=DRL_UNIFY drlExpression + | drlExpression bop=(EQUAL | NOTEQUAL) drlExpression + | drlExpression bop=BITAND drlExpression + | drlExpression bop=CARET drlExpression + | drlExpression bop=BITOR drlExpression + | drlExpression bop=AND drlExpression + | drlExpression bop=OR drlExpression + | drlExpression bop=QUESTION drlExpression COLON drlExpression + | drlExpression + bop=(ASSIGN | ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | RSHIFT_ASSIGN | URSHIFT_ASSIGN | LSHIFT_ASSIGN | MOD_ASSIGN) + drlExpression + | lambdaExpression // Java8 + | switchExpression // Java17 + + // Java 8 methodReference + | drlExpression COLONCOLON typeArguments? drlIdentifier + | typeType COLONCOLON (typeArguments? drlIdentifier | NEW) + | classType COLONCOLON typeArguments? NEW + ; + +temporalOperator : DRL_NOT? bop=(DRL_AFTER | DRL_BEFORE | DRL_COINCIDES | DRL_DURING | DRL_INCLUDES | DRL_FINISHES | DRL_FINISHED_BY | DRL_MEETS | DRL_MET_BY | DRL_OVERLAPS | DRL_OVERLAPPED_BY | DRL_STARTS | DRL_STARTED_BY) timeAmount? ; + +timeAmount : LBRACK (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL) (COMMA (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL))* RBRACK ; + +/* extending JavaParser primary */ +drlPrimary + : LPAREN drlExpression RPAREN + | THIS + | SUPER + | drlLiteral + | drlIdentifier + | typeTypeOrVoid DOT CLASS + | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) + | inlineListExpression + | inlineMapExpression + ; + +/* extending JavaParser literal */ +drlLiteral + : integerLiteral + | floatLiteral + | DRL_BIG_DECIMAL_LITERAL + | DRL_BIG_INTEGER_LITERAL + | CHAR_LITERAL + | DRL_STRING_LITERAL + | BOOL_LITERAL + | NULL_LITERAL + | TEXT_BLOCK // Java17 + ; + +inlineListExpression + : LBRACK expressionList? RBRACK + ; + +expressionList + : drlExpression (COMMA drlExpression)* + ; + +inlineMapExpression + : LBRACK mapExpressionList RBRACK + ; + +mapExpressionList + : mapEntry (COMMA mapEntry)* + ; + +mapEntry + : drlExpression COLON drlExpression + ; + +/* + patternFilter := OVER filterDef + filterDef := label ID LEFT_PAREN parameters RIGHT_PAREN +*/ +patternFilter : DRL_WINDOW COLON IDENTIFIER LPAREN expressionList RPAREN ; + +/* + patternSource := FROM + ( fromAccumulate + | fromCollect + | fromEntryPoint + | fromWindow + | fromExpression ) +*/ +patternSource : fromAccumulate + | fromCollect + | fromEntryPoint + | fromExpression + ; + +fromExpression : conditionalOrExpression ; + + +/* +fromAccumulate := ACCUMULATE LEFT_PAREN lhsAnd (COMMA|SEMICOLON) + ( INIT chunk_(_) COMMA ACTION chunk_(_) COMMA + ( REVERSE chunk_(_) COMMA)? RESULT chunk_(_) + | accumulateFunction + ) RIGHT_PAREN +*/ +fromAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) + ( DRL_INIT LPAREN initBlockStatements=blockStatements RPAREN COMMA DRL_ACTION LPAREN actionBlockStatements=blockStatements RPAREN COMMA ( DRL_REVERSE LPAREN reverseBlockStatements=blockStatements RPAREN COMMA)? DRL_RESULT LPAREN expression RPAREN + | accumulateFunction + ) + RPAREN (SEMI)? + ; + +blockStatements : blockStatement* ; + +/* +accumulateFunction := label? ID parameters +*/ +accumulateFunction : label? IDENTIFIER LPAREN drlExpression RPAREN; + +// fromCollect := COLLECT LEFT_PAREN lhsPatternBind RIGHT_PAREN + +fromCollect : DRL_COLLECT LPAREN lhsPatternBind RPAREN ; + +fromEntryPoint : DRL_ENTRY_POINT stringId ; + +/* + lhsExists := EXISTS + ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or + | LEFT_PAREN lhsOr RIGHT_PAREN + | lhsPatternBind + ) +*/ +// Use lhsExpression instead of lhsOr because lhsExpression has good enough structure +lhsExists : DRL_EXISTS + ( LPAREN lhsExpression RPAREN + | lhsPatternBind + ) + ; + +/* + lhsNot := NOT + ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or + | LEFT_PAREN lhsOr RIGHT_PAREN + | lhsPatternBind + ) +*/ +// Use lhsExpression instead of lhsOr because lhsExpression has good enough structure +lhsNot : DRL_NOT + ( LPAREN lhsExpression RPAREN + | lhsPatternBind + ) + ; + +/** + * lhsEval := EVAL LEFT_PAREN conditionalExpression RIGHT_PAREN + */ +lhsEval : DRL_EVAL LPAREN conditionalOrExpression RPAREN ; + +/** + * lhsForall := FORALL LEFT_PAREN lhsPatternBind+ RIGHT_PAREN + */ + +lhsForall : DRL_FORALL LPAREN lhsPatternBind+ RPAREN ; + +/** + * lhsAccumulate := (ACCUMULATE|ACC) LEFT_PAREN lhsAnd (COMMA|SEMICOLON) + * accumulateFunctionBinding (COMMA accumulateFunctionBinding)* + * (SEMICOLON constraints)? + * RIGHT_PAREN SEMICOLON? + */ + +lhsAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) + accumulateFunction (COMMA accumulateFunction)* + (SEMI constraints)? + RPAREN (SEMI)? + ; + +rhs : DRL_THEN consequence ; + +consequence : RHS_CHUNK* ; + +stringId : ( IDENTIFIER | DRL_STRING_LITERAL ) ; + +type : (classOrInterfaceType | primitiveType) typeArguments? ( DOT IDENTIFIER typeArguments? )* (LBRACK RBRACK)* ; + +//typeArguments : LT typeArgument (COMMA typeArgument)* GT ; +//typeArgument : QUESTION (( EXTENDS | SUPER ) type )? | type ; + +drlArguments : LPAREN drlArgument (COMMA drlArgument)* RPAREN ; +drlArgument : ( stringId | floatLiteral | BOOL_LITERAL | NULL_LITERAL ) ; + +drlAnnotation : AT name=drlQualifiedName (LPAREN ( drlElementValuePairs | drlElementValue )? RPAREN)? ; + +drlElementValuePairs : drlElementValuePair (COMMA drlElementValuePair)* ; +drlElementValuePair : key=drlIdentifier ASSIGN value=drlElementValue ; + +drlElementValue + : drlExpression + | drlArrayInitializer + ; + +attributes : attribute ( COMMA? attribute )* ; +attribute : name=( 'salience' | 'enabled' ) conditionalOrExpression #expressionAttribute + | name=( 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOL_LITERAL? #booleanAttribute + | name=( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) DRL_STRING_LITERAL #stringAttribute + | name='calendars' DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* #stringListAttribute + | name='timer' ( DECIMAL_LITERAL | chunk ) #intOrChunkAttribute + | name='duration' ( DECIMAL_LITERAL | TIME_INTERVAL | LPAREN TIME_INTERVAL RPAREN ) #durationAttribute + ; + +chunk : LPAREN .+? RPAREN; + +assignmentOperator : ASSIGN + | ADD_ASSIGN + | SUB_ASSIGN + | MUL_ASSIGN + | DIV_ASSIGN + | AND_ASSIGN + | OR_ASSIGN + | XOR_ASSIGN + | MOD_ASSIGN + | LT LT ASSIGN ; + +label : IDENTIFIER COLON ; +unif : IDENTIFIER DRL_UNIFY ; + +/* extending JavaParser variableInitializer */ +drlVariableInitializer + : arrayInitializer + | drlExpression + ; + + drlCreator + : nonWildcardTypeArguments createdName classCreatorRest + | createdName (drlArrayCreatorRest | classCreatorRest) + ; + + drlArrayCreatorRest + : LBRACK (RBRACK (LBRACK RBRACK)* drlArrayInitializer | expression RBRACK (LBRACK expression RBRACK)* (LBRACK RBRACK)*) + ; + + drlArrayInitializer + : LBRACE (drlVariableInitializer (COMMA drlVariableInitializer)* (COMMA)? )? RBRACE + ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 new file mode 100644 index 00000000000..1af884db096 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 @@ -0,0 +1,245 @@ +/* + [The "BSD licence"] + Copyright (c) 2013 Terence Parr, Sam Harwell + Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) + Copyright (c) 2021 Michał Lorek (upgrade to Java 11) + Copyright (c) 2022 Michał Lorek (upgrade to Java 17) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// source: https://github.com/antlr/grammars-v4/tree/master/java/java + +lexer grammar JavaLexer; + +// Keywords + +ABSTRACT: 'abstract'; +ASSERT: 'assert'; +BOOLEAN: 'boolean'; +BREAK: 'break'; +BYTE: 'byte'; +CASE: 'case'; +CATCH: 'catch'; +CHAR: 'char'; +CLASS: 'class'; +CONST: 'const'; +CONTINUE: 'continue'; +DEFAULT: 'default'; +DO: 'do'; +DOUBLE: 'double'; +ELSE: 'else'; +ENUM: 'enum'; +EXTENDS: 'extends'; +FINAL: 'final'; +FINALLY: 'finally'; +FLOAT: 'float'; +FOR: 'for'; +IF: 'if'; +GOTO: 'goto'; +IMPLEMENTS: 'implements'; +IMPORT: 'import'; +INSTANCEOF: 'instanceof'; +INT: 'int'; +INTERFACE: 'interface'; +LONG: 'long'; +NATIVE: 'native'; +NEW: 'new'; +PACKAGE: 'package'; +PRIVATE: 'private'; +PROTECTED: 'protected'; +PUBLIC: 'public'; +RETURN: 'return'; +SHORT: 'short'; +STATIC: 'static'; +STRICTFP: 'strictfp'; +SUPER: 'super'; +SWITCH: 'switch'; +SYNCHRONIZED: 'synchronized'; +THIS: 'this'; +THROW: 'throw'; +THROWS: 'throws'; +TRANSIENT: 'transient'; +TRY: 'try'; +VOID: 'void'; +VOLATILE: 'volatile'; +WHILE: 'while'; + +// Module related keywords +MODULE: 'module'; +OPEN: 'open'; +REQUIRES: 'requires'; +EXPORTS: 'exports'; +OPENS: 'opens'; +TO: 'to'; +USES: 'uses'; +PROVIDES: 'provides'; +WITH: 'with'; +TRANSITIVE: 'transitive'; + +// Local Variable Type Inference +VAR: 'var'; // reserved type name + +// Switch Expressions +YIELD: 'yield'; + +// Records +RECORD: 'record'; + +// Sealed Classes +SEALED: 'sealed'; +PERMITS: 'permits'; +NON_SEALED: 'non-sealed'; + +// Literals + +DECIMAL_LITERAL: ('0' | [1-9] (Digits? | '_'+ Digits)) [lL]?; +HEX_LITERAL: '0' [xX] [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? [lL]?; +OCT_LITERAL: '0' '_'* [0-7] ([0-7_]* [0-7])? [lL]?; +BINARY_LITERAL: '0' [bB] [01] ([01_]* [01])? [lL]?; + +FLOAT_LITERAL: (Digits '.' Digits? | '.' Digits) ExponentPart? [fFdD]? + | Digits (ExponentPart [fFdD]? | [fFdD]) + ; + +HEX_FLOAT_LITERAL: '0' [xX] (HexDigits '.'? | HexDigits? '.' HexDigits) [pP] [+-]? Digits [fFdD]?; + +BOOL_LITERAL: 'true' + | 'false' + ; + +CHAR_LITERAL: '\'' (~['\\\r\n] | EscapeSequence) '\''; + +STRING_LITERAL: '"' (~["\\\r\n] | EscapeSequence)* '"'; + +TEXT_BLOCK: '"""' [ \t]* [\r\n] (. | EscapeSequence)*? '"""'; + +NULL_LITERAL: 'null'; + +// Separators + +LPAREN: '('; +RPAREN: ')'; +LBRACE: '{'; +RBRACE: '}'; +LBRACK: '['; +RBRACK: ']'; +SEMI: ';'; +COMMA: ','; +DOT: '.'; + +// Operators + +ASSIGN: '='; +GT: '>'; +LT: '<'; +BANG: '!'; +TILDE: '~'; +QUESTION: '?'; +COLON: ':'; +EQUAL: '=='; +LE: '<='; +GE: '>='; +NOTEQUAL: '!='; +AND: '&&'; +OR: '||'; +INC: '++'; +DEC: '--'; +ADD: '+'; +SUB: '-'; +MUL: '*'; +DIV: '/'; +BITAND: '&'; +BITOR: '|'; +CARET: '^'; +MOD: '%'; + +ADD_ASSIGN: '+='; +SUB_ASSIGN: '-='; +MUL_ASSIGN: '*='; +DIV_ASSIGN: '/='; +AND_ASSIGN: '&='; +OR_ASSIGN: '|='; +XOR_ASSIGN: '^='; +MOD_ASSIGN: '%='; +LSHIFT_ASSIGN: '<<='; +RSHIFT_ASSIGN: '>>='; +URSHIFT_ASSIGN: '>>>='; + +// Java 8 tokens + +ARROW: '->'; +COLONCOLON: '::'; + +// Additional symbols not defined in the lexical specification + +AT: '@'; +ELLIPSIS: '...'; + +// Whitespace and comments + +WS: [ \t\r\n\u000C]+ -> channel(HIDDEN); +COMMENT: '/*' .*? '*/' -> channel(HIDDEN); +LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN); + +// Identifiers + +IDENTIFIER: Letter LetterOrDigit*; + +// Fragment rules + +fragment ExponentPart + : [eE] [+-]? Digits + ; + +fragment EscapeSequence + : '\\' [btnfr"'\\] + | '\\' ([0-3]? [0-7])? [0-7] + | '\\' 'u'+ HexDigit HexDigit HexDigit HexDigit + ; + +fragment HexDigits + : HexDigit ((HexDigit | '_')* HexDigit)? + ; + +fragment HexDigit + : [0-9a-fA-F] + ; + +fragment Digits + : [0-9] ([0-9_]* [0-9])? + ; + +fragment LetterOrDigit + : Letter + | [0-9] + ; + +fragment Letter + : [a-zA-Z$_] // these are the "java letters" below 0x7F + | ~[\u0000-\u007F\uD800-\uDBFF] // covers all characters above 0x7F which are not a surrogate + | [\uD800-\uDBFF] [\uDC00-\uDFFF] // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF + ; + +TEXT : .+? ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 new file mode 100644 index 00000000000..9e9f0a68513 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 @@ -0,0 +1,752 @@ +/* + [The "BSD licence"] + Copyright (c) 2013 Terence Parr, Sam Harwell + Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) + Copyright (c) 2021 Michał Lorek (upgrade to Java 11) + Copyright (c) 2022 Michał Lorek (upgrade to Java 17) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// source: https://github.com/antlr/grammars-v4/tree/master/java/java + +parser grammar JavaParser; + +options { tokenVocab=JavaLexer; } + +compilationUnit + : packageDeclaration? importDeclaration* typeDeclaration* + | moduleDeclaration EOF + ; + +packageDeclaration + : annotation* PACKAGE qualifiedName SEMI + ; + +importDeclaration + : IMPORT STATIC? qualifiedName (DOT MUL)? SEMI + ; + +typeDeclaration + : classOrInterfaceModifier* + (classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration | recordDeclaration) + | SEMI + ; + +modifier + : classOrInterfaceModifier + | NATIVE + | SYNCHRONIZED + | TRANSIENT + | VOLATILE + ; + +classOrInterfaceModifier + : annotation + | PUBLIC + | PROTECTED + | PRIVATE + | STATIC + | ABSTRACT + | FINAL // FINAL for class only -- does not apply to interfaces + | STRICTFP + | SEALED // Java17 + | NON_SEALED // Java17 + ; + +variableModifier + : FINAL + | annotation + ; + +classDeclaration + : CLASS identifier typeParameters? + (EXTENDS typeType)? + (IMPLEMENTS typeList)? + (PERMITS typeList)? // Java17 + classBody + ; + +typeParameters + : LT typeParameter (COMMA typeParameter)* GT + ; + +typeParameter + : annotation* identifier (EXTENDS annotation* typeBound)? + ; + +typeBound + : typeType (BITAND typeType)* + ; + +enumDeclaration + : ENUM identifier (IMPLEMENTS typeList)? LBRACE enumConstants? COMMA? enumBodyDeclarations? RBRACE + ; + +enumConstants + : enumConstant (COMMA enumConstant)* + ; + +enumConstant + : annotation* identifier arguments? classBody? + ; + +enumBodyDeclarations + : SEMI classBodyDeclaration* + ; + +interfaceDeclaration + : INTERFACE identifier typeParameters? (EXTENDS typeList)? (PERMITS typeList)? interfaceBody + ; + +classBody + : LBRACE classBodyDeclaration* RBRACE + ; + +interfaceBody + : LBRACE interfaceBodyDeclaration* RBRACE + ; + +classBodyDeclaration + : SEMI + | STATIC? block + | modifier* memberDeclaration + ; + +memberDeclaration + : methodDeclaration + | genericMethodDeclaration + | fieldDeclaration + | constructorDeclaration + | genericConstructorDeclaration + | interfaceDeclaration + | annotationTypeDeclaration + | classDeclaration + | enumDeclaration + | recordDeclaration //Java17 + ; + +/* We use rule this even for void methods which cannot have [] after parameters. + This simplifies grammar and we can consider void to be a type, which + renders the [] matching as a context-sensitive issue or a semantic check + for invalid return type after parsing. + */ +methodDeclaration + : typeTypeOrVoid identifier formalParameters (LBRACK RBRACK)* + (THROWS qualifiedNameList)? + methodBody + ; + +methodBody + : block + | SEMI + ; + +typeTypeOrVoid + : typeType + | VOID + ; + +genericMethodDeclaration + : typeParameters methodDeclaration + ; + +genericConstructorDeclaration + : typeParameters constructorDeclaration + ; + +constructorDeclaration + : identifier formalParameters (THROWS qualifiedNameList)? constructorBody=block + ; + +fieldDeclaration + : typeType variableDeclarators SEMI + ; + +interfaceBodyDeclaration + : modifier* interfaceMemberDeclaration + | SEMI + ; + +interfaceMemberDeclaration + : constDeclaration + | interfaceMethodDeclaration + | genericInterfaceMethodDeclaration + | interfaceDeclaration + | annotationTypeDeclaration + | classDeclaration + | enumDeclaration + | recordDeclaration // Java17 + ; + +constDeclaration + : typeType constantDeclarator (COMMA constantDeclarator)* SEMI + ; + +constantDeclarator + : identifier (LBRACK RBRACK)* ASSIGN variableInitializer + ; + +// Early versions of Java allows brackets after the method name, eg. +// public int[] return2DArray() [] { ... } +// is the same as +// public int[][] return2DArray() { ... } +interfaceMethodDeclaration + : interfaceMethodModifier* interfaceCommonBodyDeclaration + ; + +// Java8 +interfaceMethodModifier + : annotation + | PUBLIC + | ABSTRACT + | DEFAULT + | STATIC + | STRICTFP + ; + +genericInterfaceMethodDeclaration + : interfaceMethodModifier* typeParameters interfaceCommonBodyDeclaration + ; + +interfaceCommonBodyDeclaration + : annotation* typeTypeOrVoid identifier formalParameters (LBRACK RBRACK)* (THROWS qualifiedNameList)? methodBody + ; + +variableDeclarators + : variableDeclarator (COMMA variableDeclarator)* + ; + +variableDeclarator + : variableDeclaratorId (ASSIGN variableInitializer)? + ; + +variableDeclaratorId + : identifier (LBRACK RBRACK)* + ; + +variableInitializer + : arrayInitializer + | expression + ; + +arrayInitializer + : LBRACE (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RBRACE + ; + +classOrInterfaceType + : identifier typeArguments? (DOT identifier typeArguments?)* + ; + +typeArgument + : typeType + | annotation* QUESTION ((EXTENDS | SUPER) typeType)? + ; + +qualifiedNameList + : qualifiedName (COMMA qualifiedName)* + ; + +formalParameters + : LPAREN ( receiverParameter? + | receiverParameter (COMMA formalParameterList)? + | formalParameterList? + ) RPAREN + ; + +receiverParameter + : typeType (identifier DOT)* THIS + ; + +formalParameterList + : formalParameter (COMMA formalParameter)* (COMMA lastFormalParameter)? + | lastFormalParameter + ; + +formalParameter + : variableModifier* typeType variableDeclaratorId + ; + +lastFormalParameter + : variableModifier* typeType annotation* ELLIPSIS variableDeclaratorId + ; + +// local variable type inference +lambdaLVTIList + : lambdaLVTIParameter (COMMA lambdaLVTIParameter)* + ; + +lambdaLVTIParameter + : variableModifier* VAR identifier + ; + +qualifiedName + : identifier (DOT identifier)* + ; + +literal + : integerLiteral + | floatLiteral + | CHAR_LITERAL + | STRING_LITERAL + | BOOL_LITERAL + | NULL_LITERAL + | TEXT_BLOCK // Java17 + ; + +integerLiteral + : DECIMAL_LITERAL + | HEX_LITERAL + | OCT_LITERAL + | BINARY_LITERAL + ; + +floatLiteral + : FLOAT_LITERAL + | HEX_FLOAT_LITERAL + ; + +// ANNOTATIONS +altAnnotationQualifiedName + : (identifier DOT)* AT identifier + ; + +annotation + : (AT qualifiedName | altAnnotationQualifiedName) (LPAREN ( elementValuePairs | elementValue )? RPAREN)? + ; + +elementValuePairs + : elementValuePair (COMMA elementValuePair)* + ; + +elementValuePair + : identifier ASSIGN elementValue + ; + +elementValue + : expression + | annotation + | elementValueArrayInitializer + ; + +elementValueArrayInitializer + : LBRACE (elementValue (COMMA elementValue)*)? (COMMA)? RBRACE + ; + +annotationTypeDeclaration + : AT INTERFACE identifier annotationTypeBody + ; + +annotationTypeBody + : LBRACE (annotationTypeElementDeclaration)* RBRACE + ; + +annotationTypeElementDeclaration + : modifier* annotationTypeElementRest + | SEMI // this is not allowed by the grammar, but apparently allowed by the actual compiler + ; + +annotationTypeElementRest + : typeType annotationMethodOrConstantRest SEMI + | classDeclaration SEMI? + | interfaceDeclaration SEMI? + | enumDeclaration SEMI? + | annotationTypeDeclaration SEMI? + | recordDeclaration SEMI? // Java17 + ; + +annotationMethodOrConstantRest + : annotationMethodRest + | annotationConstantRest + ; + +annotationMethodRest + : identifier LPAREN RPAREN defaultValue? + ; + +annotationConstantRest + : variableDeclarators + ; + +defaultValue + : DEFAULT elementValue + ; + +// MODULES - Java9 + +moduleDeclaration + : OPEN? MODULE qualifiedName moduleBody + ; + +moduleBody + : LBRACE moduleDirective* RBRACE + ; + +moduleDirective + : REQUIRES requiresModifier* qualifiedName SEMI + | EXPORTS qualifiedName (TO qualifiedName)? SEMI + | OPENS qualifiedName (TO qualifiedName)? SEMI + | USES qualifiedName SEMI + | PROVIDES qualifiedName WITH qualifiedName SEMI + ; + +requiresModifier + : TRANSITIVE + | STATIC + ; + +// RECORDS - Java 17 + +recordDeclaration + : RECORD identifier typeParameters? recordHeader + (IMPLEMENTS typeList)? + recordBody + ; + +recordHeader + : LPAREN recordComponentList? RPAREN + ; + +recordComponentList + : recordComponent (COMMA recordComponent)* + ; + +recordComponent + : typeType identifier + ; + +recordBody + : LBRACE classBodyDeclaration* RBRACE + ; + +// STATEMENTS / BLOCKS + +block + : LBRACE blockStatement* RBRACE + ; + +blockStatement + : localVariableDeclaration SEMI + | statement + | localTypeDeclaration + ; + +localVariableDeclaration + : variableModifier* (typeType variableDeclarators | VAR identifier ASSIGN expression) + ; + +identifier + : IDENTIFIER + | MODULE + | OPEN + | REQUIRES + | EXPORTS + | OPENS + | TO + | USES + | PROVIDES + | WITH + | TRANSITIVE + | YIELD + | SEALED + | PERMITS + | RECORD + | VAR + ; + +localTypeDeclaration + : classOrInterfaceModifier* + (classDeclaration | interfaceDeclaration | recordDeclaration) + | SEMI + ; + +statement + : blockLabel=block + | ASSERT expression (COLON expression)? SEMI + | IF parExpression statement (ELSE statement)? + | FOR LPAREN forControl RPAREN statement + | WHILE parExpression statement + | DO statement WHILE parExpression SEMI + | TRY block (catchClause+ finallyBlock? | finallyBlock) + | TRY resourceSpecification block catchClause* finallyBlock? + | SWITCH parExpression LBRACE switchBlockStatementGroup* switchLabel* RBRACE + | SYNCHRONIZED parExpression block + | RETURN expression? SEMI + | THROW expression SEMI + | BREAK identifier? SEMI + | CONTINUE identifier? SEMI + | YIELD expression SEMI // Java17 + | SEMI + | statementExpression=expression SEMI + | switchExpression SEMI? // Java17 + | identifierLabel=identifier COLON statement + ; + +catchClause + : CATCH LPAREN variableModifier* catchType identifier RPAREN block + ; + +catchType + : qualifiedName (BITOR qualifiedName)* + ; + +finallyBlock + : FINALLY block + ; + +resourceSpecification + : LPAREN resources SEMI? RPAREN + ; + +resources + : resource (SEMI resource)* + ; + +resource + : variableModifier* ( classOrInterfaceType variableDeclaratorId | VAR identifier ) ASSIGN expression + | identifier + ; + +/** Matches cases then statements, both of which are mandatory. + * To handle empty cases at the end, we add switchLabel* to statement. + */ +switchBlockStatementGroup + : switchLabel+ blockStatement+ + ; + +switchLabel + : CASE (constantExpression=expression | enumConstantName=IDENTIFIER | typeType varName=identifier) COLON + | DEFAULT COLON + ; + +forControl + : enhancedForControl + | forInit? SEMI expression? SEMI forUpdate=expressionList? + ; + +forInit + : localVariableDeclaration + | expressionList + ; + +enhancedForControl + : variableModifier* (typeType | VAR) variableDeclaratorId COLON expression + ; + +// EXPRESSIONS + +parExpression + : LPAREN expression RPAREN + ; + +expressionList + : expression (COMMA expression)* + ; + +methodCall + : identifier LPAREN expressionList? RPAREN + | THIS LPAREN expressionList? RPAREN + | SUPER LPAREN expressionList? RPAREN + ; + +expression + : primary + | expression bop=DOT + ( + identifier + | methodCall + | THIS + | NEW nonWildcardTypeArguments? innerCreator + | SUPER superSuffix + | explicitGenericInvocation + ) + | expression LBRACK expression RBRACK + | methodCall + | NEW creator + | LPAREN annotation* typeType (BITAND typeType)* RPAREN expression + | expression postfix=(INC | DEC) + | prefix=(ADD|SUB|INC|DEC) expression + | prefix=(TILDE|BANG) expression + | expression bop=(MUL|DIV|MOD) expression + | expression bop=(ADD|SUB) expression + | expression (LT LT | GT GT GT | GT GT) expression + | expression bop=(LE | GE | GT | LT) expression + | expression bop=INSTANCEOF (typeType | pattern) + | expression bop=(EQUAL | NOTEQUAL) expression + | expression bop=BITAND expression + | expression bop=CARET expression + | expression bop=BITOR expression + | expression bop=AND expression + | expression bop=OR expression + | expression bop=QUESTION expression COLON expression + | expression + bop=(ASSIGN | ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | RSHIFT_ASSIGN | URSHIFT_ASSIGN | LSHIFT_ASSIGN | MOD_ASSIGN) + expression + | lambdaExpression // Java8 + | switchExpression // Java17 + + // Java 8 methodReference + | expression COLONCOLON typeArguments? identifier + | typeType COLONCOLON (typeArguments? identifier | NEW) + | classType COLONCOLON typeArguments? NEW + ; + +// Java17 +pattern + : variableModifier* typeType annotation* identifier + ; + +// Java8 +lambdaExpression + : lambdaParameters ARROW lambdaBody + ; + +// Java8 +lambdaParameters + : identifier + | LPAREN formalParameterList? RPAREN + | LPAREN identifier (COMMA identifier)* RPAREN + | LPAREN lambdaLVTIList? RPAREN + ; + +// Java8 +lambdaBody + : expression + | block + ; + +primary + : LPAREN expression RPAREN + | THIS + | SUPER + | literal + | identifier + | typeTypeOrVoid DOT CLASS + | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) + ; + +// Java17 +switchExpression + : SWITCH parExpression LBRACE switchLabeledRule* RBRACE + ; + +// Java17 +switchLabeledRule + : CASE (expressionList | NULL_LITERAL | guardedPattern) (ARROW | COLON) switchRuleOutcome + | DEFAULT (ARROW | COLON) switchRuleOutcome + ; + +// Java17 +guardedPattern + : LPAREN guardedPattern RPAREN + | variableModifier* typeType annotation* identifier (AND expression)* + | guardedPattern AND expression + ; + +// Java17 +switchRuleOutcome + : block + | blockStatement* + ; + +classType + : (classOrInterfaceType DOT)? annotation* identifier typeArguments? + ; + +creator + : nonWildcardTypeArguments createdName classCreatorRest + | createdName (arrayCreatorRest | classCreatorRest) + ; + +createdName + : identifier typeArgumentsOrDiamond? (DOT identifier typeArgumentsOrDiamond?)* + | primitiveType + ; + +innerCreator + : identifier nonWildcardTypeArgumentsOrDiamond? classCreatorRest + ; + +arrayCreatorRest + : LBRACK (RBRACK (LBRACK RBRACK)* arrayInitializer | expression RBRACK (LBRACK expression RBRACK)* (LBRACK RBRACK)*) + ; + +classCreatorRest + : arguments classBody? + ; + +explicitGenericInvocation + : nonWildcardTypeArguments explicitGenericInvocationSuffix + ; + +typeArgumentsOrDiamond + : LT GT + | typeArguments + ; + +nonWildcardTypeArgumentsOrDiamond + : LT GT + | nonWildcardTypeArguments + ; + +nonWildcardTypeArguments + : LT typeList GT + ; + +typeList + : typeType (COMMA typeType)* + ; + +typeType + : annotation* (classOrInterfaceType | primitiveType) (annotation* LBRACK RBRACK)* + ; + +primitiveType + : BOOLEAN + | CHAR + | BYTE + | SHORT + | INT + | LONG + | FLOAT + | DOUBLE + ; + +typeArguments + : LT typeArgument (COMMA typeArgument)* GT + ; + +superSuffix + : arguments + | DOT typeArguments? identifier arguments? + ; + +explicitGenericInvocationSuffix + : SUPER superSuffix + | identifier arguments + ; + +arguments + : LPAREN expressionList? RPAREN + ; \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java index 15bf0addf05..71b23c2fdd3 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java @@ -25,6 +25,7 @@ import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognizerSharedState; import org.antlr.runtime.TokenStream; +import org.drools.drl.parser.lang.DRL10Lexer; import org.drools.drl.parser.lang.DRL5Expressions; import org.drools.drl.parser.lang.DRL5Lexer; import org.drools.drl.parser.lang.DRL5Parser; @@ -113,6 +114,8 @@ public static DRLLexer getDRLLexer(CharStream input, LanguageLevelOption languag case DRL6: case DRL6_STRICT: return new DRL6Lexer(input); + case DRL10: + return new DRL10Lexer(); } throw new RuntimeException("Unknown language level"); } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java new file mode 100644 index 00000000000..9fb0186afb7 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java @@ -0,0 +1,90 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser; + +import java.util.Collections; +import java.util.List; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.RecognizerSharedState; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.lang.DRLExpressions; +import org.drools.drl.parser.lang.DRLLexer; +import org.drools.drl.parser.lang.ParserHelper; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * This is a helper class that provides helper methods to parse expressions + * using both the DRLExpressions parser and the DRLExprTree parser. + */ +public class Drl6ExprParser implements DrlExprParser { + + private ParserHelper helper = null; + + private final LanguageLevelOption languageLevel; + + public Drl6ExprParser(LanguageLevelOption languageLevel) { + this.languageLevel = languageLevel; + } + + /** Parse an expression from text */ + public ConstraintConnectiveDescr parse( final String text ) { + ConstraintConnectiveDescr constraint = null; + try { + DRLLexer lexer = DRLFactory.getDRLLexer(new ANTLRStringStream(text), languageLevel); + CommonTokenStream input = new CommonTokenStream( lexer ); + RecognizerSharedState state = new RecognizerSharedState(); + helper = new ParserHelper( input, state, languageLevel ); + DRLExpressions parser = DRLFactory.getDRLExpressions(input, state, helper, languageLevel); + parser.setBuildDescr( true ); + parser.setLeftMostExpr( null ); // setting initial value just in case + BaseDescr expr = parser.conditionalOrExpression(); + if ( expr != null && !parser.hasErrors() ) { + constraint = ConstraintConnectiveDescr.newAnd(); + constraint.addOrMerge( expr ); + } + } catch ( RecognitionException e ) { + helper.reportError( e ); + } + return constraint; + } + + public String getLeftMostExpr() { + return helper != null ? helper.getLeftMostExpr() : null; + } + + /** + * @return true if there were parser errors. + */ + public boolean hasErrors() { + return helper != null && helper.hasErrors(); + } + + /** + * @return a list of errors found while parsing. + */ + @SuppressWarnings("unchecked") + public List getErrors() { + return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; + } + +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java index 60c61ac248d..0702a1d1461 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java @@ -18,73 +18,29 @@ */ package org.drools.drl.parser; -import java.util.Collections; import java.util.List; -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.RecognizerSharedState; -import org.drools.drl.parser.lang.DRLExpressions; -import org.drools.drl.parser.lang.DRLLexer; -import org.drools.drl.parser.lang.ParserHelper; -import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; -import org.kie.internal.builder.conf.LanguageLevelOption; /** * This is a helper class that provides helper methods to parse expressions * using both the DRLExpressions parser and the DRLExprTree parser. */ -public class DrlExprParser { - - private ParserHelper helper = null; - - private final LanguageLevelOption languageLevel; - - public DrlExprParser(LanguageLevelOption languageLevel) { - this.languageLevel = languageLevel; - } +public interface DrlExprParser { /** Parse an expression from text */ - public ConstraintConnectiveDescr parse( final String text ) { - ConstraintConnectiveDescr constraint = null; - try { - DRLLexer lexer = DRLFactory.getDRLLexer(new ANTLRStringStream(text), languageLevel); - CommonTokenStream input = new CommonTokenStream( lexer ); - RecognizerSharedState state = new RecognizerSharedState(); - helper = new ParserHelper( input, state, languageLevel ); - DRLExpressions parser = DRLFactory.getDRLExpressions(input, state, helper, languageLevel); - parser.setBuildDescr( true ); - parser.setLeftMostExpr( null ); // setting initial value just in case - BaseDescr expr = parser.conditionalOrExpression(); - if ( expr != null && !parser.hasErrors() ) { - constraint = ConstraintConnectiveDescr.newAnd(); - constraint.addOrMerge( expr ); - } - } catch ( RecognitionException e ) { - helper.reportError( e ); - } - return constraint; - } - - public String getLeftMostExpr() { - return helper != null ? helper.getLeftMostExpr() : null; - } + ConstraintConnectiveDescr parse( final String text ); + + String getLeftMostExpr(); /** * @return true if there were parser errors. */ - public boolean hasErrors() { - return helper != null && helper.hasErrors(); - } + boolean hasErrors(); /** * @return a list of errors found while parsing. */ @SuppressWarnings("unchecked") - public List getErrors() { - return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; - } - + List getErrors(); } 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 new file mode 100644 index 00000000000..9ee116faf37 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java @@ -0,0 +1,20 @@ +package org.drools.drl.parser; + +import org.drools.drl10.parser.Drl10ExprParser; +import org.kie.internal.builder.conf.LanguageLevelOption; + +public class DrlExprParserFactory { + + public static DrlExprParser getDrlExrParser(LanguageLevelOption languageLevel) { + switch (languageLevel) { + case DRL5: + case DRL6: + case DRL6_STRICT: + 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 7b852c8dce3..d6ee0c042bb 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 @@ -18,6 +18,8 @@ */ package org.drools.drl.parser; +import org.drools.drl10.parser.DRLParserError; +import org.drools.drl10.parser.DRLParserWrapper; import org.drools.io.InternalResource; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.parser.lang.DRLLexer; @@ -164,10 +166,35 @@ public PackageDescr parse(final boolean isEditor, final InputStream is) throws DroolsParserException, IOException { this.resource = resource; String encoding = resource instanceof InternalResource ? ((InternalResource) resource).getEncoding() : null; - - lexer = DRLFactory.buildLexer(is, encoding, languageLevel); - DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); - return compile(isEditor, parser); + System.out.println("### parse : languageLevel = " + languageLevel); + if (languageLevel == LanguageLevelOption.DRL10) { + // new parser based on antlr4 + try { + DRLParserWrapper parser = new DRLParserWrapper(); + PackageDescr packageDescr = parser.parse(is); + for (final DRLParserError drlParserError : parser.getErrors()) { + final ParserError err = new ParserError(resource, + drlParserError.getMessage(), + drlParserError.getLineNumber(), + drlParserError.getColumn()); + this.results.add(err); + } + return !this.hasErrors() ? packageDescr : null; + } catch (Exception e) { + LOG.error("Exception", e); + final ParserError err = new ParserError(resource, + GENERIC_ERROR_MESSAGE + e.toString() + "\n" + Arrays.toString(e.getStackTrace()), + -1, + 0); + this.results.add(err); + throw new DroolsParserException(GENERIC_ERROR_MESSAGE + e.getMessage(), e); + } + } else { + // old parsers based on antlr3 + lexer = DRLFactory.buildLexer(is, encoding, languageLevel); + DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); + return compile(isEditor, parser); + } } /** diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java new file mode 100644 index 00000000000..15f6157bd3e --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java @@ -0,0 +1,46 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.lang; + +import java.util.List; + +import org.antlr.runtime.Token; +import org.drools.drl.parser.DroolsParserException; + +/** + * No implementation because everything is handled by DRL10Parser + */ +public class DRL10Lexer implements DRLLexer { + + @Override + public String getSourceName() { + throw new UnsupportedOperationException("This method should not be called"); + } + + @Override + public Token nextToken() { + throw new UnsupportedOperationException("This method should not be called"); + } + + @Override + public List getErrors() { + throw new UnsupportedOperationException("This method should not be called"); + } + +} \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java new file mode 100644 index 00000000000..0e5b5985b6c --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java @@ -0,0 +1,49 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import java.util.ArrayList; +import java.util.List; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; + +/** + * Collect errors while parsing DRL + */ +public class DRLErrorListener extends BaseErrorListener { + + private final List errors = new ArrayList<>(); + + public List getErrors() { + return errors; + } + + @Override + public void syntaxError(Recognizer recognizer, + Object offendingSymbol, + int line, + int charPositionInLine, + String msg, + RecognitionException e) { + + errors.add(new DRLParserError(line, charPositionInLine, msg)); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java new file mode 100644 index 00000000000..e7aa8102c48 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java @@ -0,0 +1,61 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import java.util.LinkedList; +import java.util.List; + +import org.antlr.v4.runtime.Parser; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.TokenStream; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.lang.DroolsSentence; + +public abstract class DRLExpressions extends Parser { + public DRLExpressions(TokenStream input) { + super(input); + } + + public abstract void setBuildDescr( boolean build ); + public abstract boolean isBuildDescr(); + + public abstract void setLeftMostExpr( String value ); + public abstract String getLeftMostExpr(); + + public abstract void setHasBindings( boolean value ); + public abstract boolean hasBindings(); + + /* + * This is the original method signature in drools/drools-drl/drools-drl-parser: + * public abstract BaseDescr conditionalOrExpression() throws RecognitionException; + * I changed it here because the conditionalOrExpression() method generated by ANTLR 4 from the conditionalOrExpression rule + * returns ConditionalOrExpressionContext, so it has a return type that's different from what was originally expected here. + * The Descr object is of course inside that context (go to this method's impl to see). + */ + public abstract BaseDescr conditionalOrExpressionDescr() throws RecognitionException; + + public abstract ParserHelper getHelper(); + public abstract boolean hasErrors(); + public abstract List getErrors(); + public abstract List getErrorMessages(); + public abstract void enableEditorInterface(); + public abstract void disableEditorInterface(); + public abstract LinkedList getEditorInterface(); +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java new file mode 100644 index 00000000000..4b893e11e46 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java @@ -0,0 +1,75 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +/** + * Error information while parsing DRL + */ +public class DRLParserError { + + private int lineNumber; + private int column; + private String message; + + private Exception exception; + + public DRLParserError(int lineNumber, int column, String message) { + this.lineNumber = lineNumber; + this.column = column; + this.message = message; + } + + public DRLParserError(Exception exception) { + this.exception = exception; + } + + public int getLineNumber() { + return lineNumber; + } + + public void setLineNumber(int lineNumber) { + this.lineNumber = lineNumber; + } + + public int getColumn() { + return column; + } + + public void setColumn(int column) { + this.column = column; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return "DRLParserError{" + + "lineNumber=" + lineNumber + + ", column=" + column + + ", message='" + message + '\'' + + ", exception=" + exception + + '}'; + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java new file mode 100644 index 00000000000..833d1aa8df0 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +public class DRLParserException extends RuntimeException { + + public DRLParserException() { + super(); + } + + public DRLParserException(String message) { + super(message); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java new file mode 100644 index 00000000000..f4436bf44b0 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java @@ -0,0 +1,126 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; + +import org.antlr.v4.runtime.CharStream; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.TokenStream; +import org.antlr.v4.runtime.tree.ErrorNode; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.drools.drl.ast.descr.PackageDescr; + +/** + * Collection of static helper methods for DRLParser + */ +public class DRLParserHelper { + + private DRLParserHelper() { + } + + /** + * Entry point for parsing DRL. + * Unlike DRLParserWrapper.parse(), this method does not collect errors. + */ + public static PackageDescr parse(String drl) { + DRLParser drlParser = createDrlParser(drl); + return compilationUnitContext2PackageDescr(drlParser.compilationUnit(), drlParser.getTokenStream()); + } + + public static DRLParser createDrlParser(String drl) { + CharStream charStream = CharStreams.fromString(drl); + return createDrlParser(charStream); + } + + public static DRLParser createDrlParser(InputStream is) { + try { + CharStream charStream = CharStreams.fromStream(is); + return createDrlParser(charStream); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static DRLParser createDrlParser(CharStream charStream) { + DRLLexer drlLexer = new DRLLexer(charStream); + CommonTokenStream commonTokenStream = new CommonTokenStream(drlLexer); + return new DRLParser(commonTokenStream); + } + + /** + * DRLVisitorImpl visits a parse tree and creates a PackageDescr + */ + public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.CompilationUnitContext ctx, TokenStream tokenStream) { + DRLVisitorImpl visitor = new DRLVisitorImpl(tokenStream); + Object descr = visitor.visit(ctx); + if (descr instanceof PackageDescr) { + return (PackageDescr) descr; + } else { + throw new DRLParserException("CompilationUnitContext should produce PackageDescr. descr = " + descr.getClass()); + } + } + + /** + * 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) { + for (int i = 0; i < parser.getInputStream().size(); i++) { + Token token = parser.getInputStream().get(i); + int start = token.getCharPositionInLine(); + int stop = token.getCharPositionInLine() + token.getText().length(); + if (token.getLine() > row) { + return token.getTokenIndex() - 1; + } else if (token.getLine() == row && start >= col) { + return token.getTokenIndex() == 0 ? 0 : token.getTokenIndex() - 1; + } else if (token.getLine() == row && start < col && stop >= col) { + return token.getTokenIndex(); + } + } + return null; + } + + /** + * RuleContext.getText() connects all nodes including ErrorNode. This method appends texts only from valid nodes + */ + public static String getTextWithoutErrorNode(ParseTree tree) { + if (tree.getChildCount() == 0) { + return ""; + } + + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < tree.getChildCount(); i++) { + ParseTree child = tree.getChild(i); + if (!(child instanceof ErrorNode)) { + if (child instanceof TerminalNode) { + builder.append(child.getText()); + } else { + builder.append(getTextWithoutErrorNode(child)); + } + } + } + + return builder.toString(); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java new file mode 100644 index 00000000000..914255e1375 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java @@ -0,0 +1,85 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.drools.drl.ast.descr.PackageDescr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.drools.drl10.parser.DRLParserHelper.compilationUnitContext2PackageDescr; + +/** + * Wrapper for DRLParser. Somewhat duplicated from DRLParserHelper, but this class is instantiated and holds errors. + */ +public class DRLParserWrapper { + + private static final Logger LOGGER = LoggerFactory.getLogger(DRLParserWrapper.class); + + private final List errors = new ArrayList<>(); + + /** + * Main entry point for parsing DRL + */ + public PackageDescr parse(String drl) { + DRLParser drlParser = DRLParserHelper.createDrlParser(drl); + return parse(drlParser); + } + + /** + * Main entry point for parsing DRL + */ + public PackageDescr parse(InputStream is) { + DRLParser drlParser = DRLParserHelper.createDrlParser(is); + return parse(drlParser); + } + + private PackageDescr parse(DRLParser drlParser) { + DRLErrorListener errorListener = new DRLErrorListener(); + drlParser.addErrorListener(errorListener); + + DRLParser.CompilationUnitContext cxt = drlParser.compilationUnit(); + + errors.addAll(errorListener.getErrors()); + + try { + return compilationUnitContext2PackageDescr(cxt, drlParser.getTokenStream()); + } catch (Exception e) { + LOGGER.error("Exception while creating PackageDescr", e); + errors.add(new DRLParserError(e)); + return null; + } + } + + public List getErrors() { + return errors; + } + + public List getErrorMessages() { + return errors.stream().map(DRLParserError::getMessage).collect(Collectors.toList()); + } + + public boolean hasErrors() { + return !errors.isEmpty(); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java new file mode 100644 index 00000000000..a977fee9882 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java @@ -0,0 +1,845 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.TokenStream; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.RuleNode; +import org.drools.drl.ast.descr.AccumulateDescr; +import org.drools.drl.ast.descr.AccumulateImportDescr; +import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.BehaviorDescr; +import org.drools.drl.ast.descr.CollectDescr; +import org.drools.drl.ast.descr.EntryPointDeclarationDescr; +import org.drools.drl.ast.descr.EntryPointDescr; +import org.drools.drl.ast.descr.EvalDescr; +import org.drools.drl.ast.descr.ExistsDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.ForallDescr; +import org.drools.drl.ast.descr.FromDescr; +import org.drools.drl.ast.descr.FunctionDescr; +import org.drools.drl.ast.descr.FunctionImportDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.ImportDescr; +import org.drools.drl.ast.descr.MVELExprDescr; +import org.drools.drl.ast.descr.NotDescr; +import org.drools.drl.ast.descr.OrDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.PatternSourceDescr; +import org.drools.drl.ast.descr.QueryDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.TypeDeclarationDescr; +import org.drools.drl.ast.descr.TypeFieldDescr; +import org.drools.drl.ast.descr.UnitDescr; +import org.drools.drl.ast.descr.WindowDeclarationDescr; + +import static org.drools.drl10.parser.DRLParserHelper.getTextWithoutErrorNode; +import static org.drools.drl10.parser.ParserStringUtils.getTextPreservingWhitespace; +import static org.drools.drl10.parser.ParserStringUtils.getTokenTextPreservingWhitespace; +import static org.drools.drl10.parser.ParserStringUtils.safeStripStringDelimiters; +import static org.drools.drl10.parser.ParserStringUtils.trimThen; +import static org.drools.util.StringUtils.unescapeJava; + +/** + * Visitor implementation for DRLParser. + * 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 { + + private final TokenStream tokenStream; + + public DRLVisitorImpl(TokenStream tokenStream) { + this.tokenStream = tokenStream; + } + + /** + * Main entry point for creating PackageDescr from a parser tree. + */ + @Override + public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { + PackageDescr packageDescr = new PackageDescr(); + if (ctx.packagedef() != null) { + packageDescr.setName(getTextWithoutErrorNode(ctx.packagedef().name)); + } + List descrList = visitDescrChildren(ctx); + applyChildrenDescrs(packageDescr, descrList); + return packageDescr; + } + + /** + * Add all children Descr to PackageDescr + */ + private void applyChildrenDescrs(PackageDescr packageDescr, List descrList) { + // This bunch of if-blocks will be refactored by DROOLS-7564 + descrList.forEach(descr -> { + if (descr instanceof UnitDescr) { + packageDescr.setUnit((UnitDescr) descr); + } else if (descr instanceof GlobalDescr) { + packageDescr.addGlobal((GlobalDescr) descr); + } else if (descr instanceof FunctionImportDescr) { + packageDescr.addFunctionImport((FunctionImportDescr) descr); + } else if (descr instanceof AccumulateImportDescr) { + packageDescr.addAccumulateImport((AccumulateImportDescr) descr); + } else if (descr instanceof ImportDescr) { + packageDescr.addImport((ImportDescr) descr); + } else if (descr instanceof FunctionDescr) { + FunctionDescr functionDescr = (FunctionDescr) descr; + functionDescr.setNamespace(packageDescr.getNamespace()); + AttributeDescr dialect = packageDescr.getAttribute("dialect"); + if (dialect != null) { + functionDescr.setDialect(dialect.getValue()); + } + packageDescr.addFunction(functionDescr); + } else if (descr instanceof TypeDeclarationDescr) { + packageDescr.addTypeDeclaration((TypeDeclarationDescr) descr); + } else if (descr instanceof EntryPointDeclarationDescr) { + packageDescr.addEntryPointDeclaration((EntryPointDeclarationDescr) descr); + } else if (descr instanceof WindowDeclarationDescr) { + packageDescr.addWindowDeclaration((WindowDeclarationDescr) descr); + } else if (descr instanceof AttributeDescr) { + packageDescr.addAttribute((AttributeDescr) descr); + } else if (descr instanceof RuleDescr) { // QueryDescr extends RuleDescr + packageDescr.addRule((RuleDescr) descr); + packageDescr.afterRuleAdded((RuleDescr) descr); + } + }); + } + + @Override + public UnitDescr visitUnitdef(DRLParser.UnitdefContext ctx) { + return new UnitDescr(ctx.name.getText()); + } + + @Override + public GlobalDescr visitGlobaldef(DRLParser.GlobaldefContext ctx) { + GlobalDescr globalDescr = new GlobalDescr(ctx.drlIdentifier().getText(), ctx.type().getText()); + populateStartEnd(globalDescr, ctx); + return globalDescr; + } + + @Override + public ImportDescr visitImportStandardDef(DRLParser.ImportStandardDefContext ctx) { + String target = ctx.drlQualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); + if (ctx.DRL_FUNCTION() != null || ctx.STATIC() != null) { + FunctionImportDescr functionImportDescr = new FunctionImportDescr(); + functionImportDescr.setTarget(target); + populateStartEnd(functionImportDescr, ctx); + return functionImportDescr; + } else { + ImportDescr importDescr = new ImportDescr(); + importDescr.setTarget(target); + populateStartEnd(importDescr, ctx); + return importDescr; + } + } + + @Override + public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulateDefContext ctx) { + AccumulateImportDescr accumulateImportDescr = new AccumulateImportDescr(); + accumulateImportDescr.setTarget(ctx.drlQualifiedName().getText()); + accumulateImportDescr.setFunctionName(ctx.IDENTIFIER().getText()); + return accumulateImportDescr; + } + + @Override + public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { + FunctionDescr functionDescr = new FunctionDescr(); + if (ctx.typeTypeOrVoid() != null) { + functionDescr.setReturnType(ctx.typeTypeOrVoid().getText()); + } else { + functionDescr.setReturnType("void"); + } + functionDescr.setName(ctx.IDENTIFIER().getText()); + + // add function parameters + DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); + DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); + if (formalParameterListContext != null) { + List formalParameterContexts = formalParameterListContext.formalParameter(); + formalParameterContexts.forEach(formalParameterContext -> { + DRLParser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); + DRLParser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); + functionDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); + }); + } + functionDescr.setBody(getTextPreservingWhitespace(ctx.block())); + return functionDescr; + } + + @Override + public BaseDescr visitDeclaredef(DRLParser.DeclaredefContext ctx) { + return visitDescrChildren(ctx).get(0); // only one child + } + + @Override + public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContext ctx) { + TypeDeclarationDescr typeDeclarationDescr = new TypeDeclarationDescr(ctx.name.getText()); + if (ctx.EXTENDS() != null) { + typeDeclarationDescr.addSuperType(ctx.superType.getText()); + } + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(typeDeclarationDescr::addAnnotation); + ctx.field().stream() + .map(this::visitField) + .forEach(typeDeclarationDescr::addField); + return typeDeclarationDescr; + } + + @Override + public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPointDeclarationContext ctx) { + EntryPointDeclarationDescr entryPointDeclarationDescr = new EntryPointDeclarationDescr(); + entryPointDeclarationDescr.setEntryPointId(ctx.name.getText()); + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(entryPointDeclarationDescr::addAnnotation); + return entryPointDeclarationDescr; + } + + @Override + public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclarationContext ctx) { + WindowDeclarationDescr windowDeclarationDescr = new WindowDeclarationDescr(); + windowDeclarationDescr.setName(ctx.name.getText()); + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(windowDeclarationDescr::addAnnotation); + windowDeclarationDescr.setPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); + return windowDeclarationDescr; + } + + /** + * entry point for one rule + */ + @Override + public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { + RuleDescr ruleDescr = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); + + if (ctx.EXTENDS() != null) { + ruleDescr.setParentName(safeStripStringDelimiters(ctx.parentName.getText())); + } + + ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(ruleDescr::addAnnotation); + + if (ctx.attributes() != null) { + List descrList = visitDescrChildren(ctx.attributes()); + descrList.stream() + .filter(AttributeDescr.class::isInstance) + .map(AttributeDescr.class::cast) + .forEach(ruleDescr::addAttribute); + } + + if (ctx.lhs() != null) { + List lhsDescrList = visitLhs(ctx.lhs()); + lhsDescrList.forEach(descr -> ruleDescr.getLhs().addDescr(descr)); + slimLhsRootDescr(ruleDescr.getLhs()); + } + + if (ctx.rhs() != null) { + ruleDescr.setConsequenceLocation(ctx.rhs().getStart().getLine(), ctx.rhs().getStart().getCharPositionInLine()); // location of "then" + ruleDescr.setConsequence(trimThen(getTextPreservingWhitespace(ctx.rhs()))); // RHS is just a text + } + + return ruleDescr; + } + + private void slimLhsRootDescr(AndDescr root) { + // Root Descr is always AndDescr. + // For example, if there are nested AndDescr like + // AndDescr + // /\ + // P AndDescr + // /\ + // P P + // is slimmed down to + // AndDescr + // / | \ + // P P P + List descrList = new ArrayList<>(root.getDescrs()); + root.getDescrs().clear(); + descrList.forEach(root::addOrMerge); + } + + @Override + public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { + QueryDescr queryDescr = new QueryDescr(safeStripStringDelimiters(ctx.name.getText())); + + DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); + if (formalParametersContext != null) { + DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); + List formalParameterContexts = formalParameterListContext.formalParameter(); + formalParameterContexts.forEach(formalParameterContext -> { + DRLParser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); + DRLParser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); + queryDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); + }); + } + + ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(queryDescr::addAnnotation); + + ctx.lhsExpression().stream() + .flatMap(lhsExpressionContext -> visitDescrChildren(lhsExpressionContext).stream()) + .forEach(descr -> queryDescr.getLhs().addDescr(descr)); + + slimLhsRootDescr(queryDescr.getLhs()); + + return queryDescr; + } + + @Override + public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { + AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); + if (ctx.drlElementValue() != null) { + annotationDescr.setValue(getTextPreservingWhitespace(ctx.drlElementValue())); // single value + } else if (ctx.drlElementValuePairs() != null) { + visitDrlElementValuePairs(ctx.drlElementValuePairs(), annotationDescr); // multiple values + } + return annotationDescr; + } + + @Override + public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { + TypeFieldDescr typeFieldDescr = new TypeFieldDescr(); + typeFieldDescr.setFieldName(ctx.label().IDENTIFIER().getText()); + typeFieldDescr.setPattern(new PatternDescr(ctx.type().getText())); + if (ctx.ASSIGN() != null) { + typeFieldDescr.setInitExpr(getTextPreservingWhitespace(ctx.initExpr)); + } + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(typeFieldDescr::addAnnotation); + return typeFieldDescr; + } + + private void visitDrlElementValuePairs(DRLParser.DrlElementValuePairsContext ctx, AnnotationDescr annotationDescr) { + ctx.drlElementValuePair().forEach(pairCtx -> { + String key = pairCtx.key.getText(); + String value = getTextPreservingWhitespace(pairCtx.value); + annotationDescr.setKeyValue(key, value); + }); + } + + @Override + public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + attributeDescr.setValue(getTextPreservingWhitespace(ctx.conditionalOrExpression())); + attributeDescr.setType(AttributeDescr.Type.EXPRESSION); + return attributeDescr; + } + + @Override + public AttributeDescr visitBooleanAttribute(DRLParser.BooleanAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + attributeDescr.setValue(ctx.BOOL_LITERAL() != null ? ctx.BOOL_LITERAL().getText() : "true"); + attributeDescr.setType(AttributeDescr.Type.BOOLEAN); + return attributeDescr; + } + + @Override + public AttributeDescr visitStringAttribute(DRLParser.StringAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.DRL_STRING_LITERAL().getText()))); + attributeDescr.setType(AttributeDescr.Type.STRING); + return attributeDescr; + } + + @Override + public AttributeDescr visitStringListAttribute(DRLParser.StringListAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + List valueList = ctx.DRL_STRING_LITERAL().stream() + .map(ParseTree::getText) + .collect(Collectors.toList()); + attributeDescr.setValue(createStringList(valueList)); + attributeDescr.setType(AttributeDescr.Type.LIST); + return attributeDescr; + } + + private static String createStringList(List valueList) { + StringBuilder sb = new StringBuilder(); + sb.append("[ "); + for (int i = 0; i < valueList.size(); i++) { + sb.append(valueList.get(i)); + if (i < valueList.size() - 1) { + sb.append(", "); + } + } + sb.append(" ]"); + return sb.toString(); + } + + @Override + public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + if (ctx.DECIMAL_LITERAL() != null) { + attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); + attributeDescr.setType(AttributeDescr.Type.NUMBER); + } else { + attributeDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); + attributeDescr.setType(AttributeDescr.Type.EXPRESSION); + } + return attributeDescr; + } + + @Override + public AttributeDescr visitDurationAttribute(DRLParser.DurationAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + if (ctx.DECIMAL_LITERAL() != null) { + attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); + attributeDescr.setType(AttributeDescr.Type.NUMBER); + } else { + attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.TIME_INTERVAL().getText()))); + attributeDescr.setType(AttributeDescr.Type.EXPRESSION); + } + return attributeDescr; + } + + /** + * entry point for LHS + */ + @Override + public List visitLhs(DRLParser.LhsContext ctx) { + if (ctx.lhsExpression() != null) { + return visitDescrChildren(ctx); + } else { + return new ArrayList<>(); + } + } + + @Override + public BaseDescr visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { + if (ctx.lhsPattern().size() == 1) { + return getSinglePatternDescr(ctx); + } else if (ctx.lhsPattern().size() > 1) { + return getOrDescrWithMultiplePatternDescr(ctx); + } else { + throw new IllegalStateException("ctx.lhsPattern().size() == 0 : " + ctx.getText()); + } + } + + private PatternDescr getSinglePatternDescr(DRLParser.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()); + } + PatternDescr patternDescr = (PatternDescr)patternDescrList.get(0); + + if (ctx.label() != null) { + patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); + } else if (ctx.unif() != null) { + patternDescr.setIdentifier(ctx.unif().IDENTIFIER().getText()); + patternDescr.setUnification(true); + } + return patternDescr; + } + + private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindContext ctx) { + OrDescr orDescr = new OrDescr(); + List descrList = visitDescrChildren(ctx); + descrList.stream() + .filter(PatternDescr.class::isInstance) + .map(PatternDescr.class::cast) + .forEach(patternDescr -> { + if (ctx.label() != null) { + patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); + } + orDescr.addDescr(patternDescr); + }); + + return orDescr; + } + + /** + * entry point for a Pattern + */ + @Override + public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { + PatternDescr patternDescr = new PatternDescr(ctx.objectType.getText()); + if (ctx.QUESTION() != null) { + patternDescr.setQuery(true); + } + if (ctx.patternFilter() != null) { + patternDescr.addBehavior(visitPatternFilter(ctx.patternFilter())); + } + if (ctx.patternSource() != null) { + PatternSourceDescr patternSourceDescr = (PatternSourceDescr) visitPatternSource(ctx.patternSource()); + patternSourceDescr.setResource(patternDescr.getResource()); + patternDescr.setSource(patternSourceDescr); + } + List constraintDescrList = visitConstraints(ctx.positionalConstraints(), ctx.constraints()); + constraintDescrList.forEach(descr -> addToPatternDescr(patternDescr, descr)); + return patternDescr; + } + + private void addToPatternDescr(PatternDescr patternDescr, ExprConstraintDescr exprConstraintDescr) { + exprConstraintDescr.setResource(patternDescr.getResource()); + patternDescr.addConstraint(exprConstraintDescr); + } + + @Override + public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { + ForallDescr forallDescr = new ForallDescr(); + visitDescrChildren(ctx).forEach(forallDescr::addDescr); + return forallDescr; + } + + @Override + public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { + AccumulateDescr accumulateDescr = new AccumulateDescr(); + accumulateDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); + + // accumulate function + for (DRLParser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { + accumulateDescr.addFunction(visitAccumulateFunction(accumulateFunctionContext)); + } + + PatternDescr patternDescr = new PatternDescr("Object"); + patternDescr.setSource(accumulateDescr); + List constraintDescrList = visitConstraints(ctx.constraints()); + constraintDescrList.forEach(patternDescr::addConstraint); + return patternDescr; + } + + @Override + public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { + BehaviorDescr behaviorDescr = new BehaviorDescr(); + behaviorDescr.setType(ctx.DRL_WINDOW().getText()); + behaviorDescr.setSubType(ctx.IDENTIFIER().getText()); + List drlExpressionContexts = ctx.expressionList().drlExpression(); + List parameters = drlExpressionContexts.stream().map(ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); + behaviorDescr.setParameters(parameters); + return behaviorDescr; + } + + @Override + public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { + FromDescr fromDescr = new FromDescr(); + fromDescr.setDataSource(new MVELExprDescr(ctx.getText())); + return fromDescr; + } + + @Override + public CollectDescr visitFromCollect(DRLParser.FromCollectContext ctx) { + CollectDescr collectDescr = new CollectDescr(); + collectDescr.setInputPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); + return collectDescr; + } + + @Override + public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) { + AccumulateDescr accumulateDescr = new AccumulateDescr(); + accumulateDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); + if (ctx.DRL_INIT() != null) { + // inline custom accumulate + accumulateDescr.setInitCode(getTextPreservingWhitespace(ctx.initBlockStatements)); + accumulateDescr.setActionCode(getTextPreservingWhitespace(ctx.actionBlockStatements)); + if (ctx.DRL_REVERSE() != null) { + accumulateDescr.setReverseCode(getTextPreservingWhitespace(ctx.reverseBlockStatements)); + } + accumulateDescr.setResultCode(ctx.expression().getText()); + } else { + // accumulate function + accumulateDescr.addFunction(visitAccumulateFunction(ctx.accumulateFunction())); + } + return accumulateDescr; + } + + @Override + public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLParser.AccumulateFunctionContext ctx) { + String function = ctx.IDENTIFIER().getText(); + String bind = ctx.label() == null ? null : ctx.label().IDENTIFIER().getText(); + String[] params = new String[]{getTextPreservingWhitespace(ctx.drlExpression())}; + return new AccumulateDescr.AccumulateFunctionCallDescr(function, bind, false, params); + } + + @Override + public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) { + return new EntryPointDescr(safeStripStringDelimiters(ctx.stringId().getText())); + } + + /** + * Collect constraints in a Pattern + */ + @Override + public List visitConstraints(DRLParser.ConstraintsContext ctx) { + List exprConstraintDescrList = new ArrayList<>(); + populateExprConstraintDescrList(ctx, exprConstraintDescrList); + return exprConstraintDescrList; + } + + /** + * Collect constraints in a Pattern. Positional constraints comes first with semicolon. + */ + private List visitConstraints(DRLParser.PositionalConstraintsContext positionalCtx, DRLParser.ConstraintsContext ctx) { + List exprConstraintDescrList = new ArrayList<>(); + populateExprConstraintDescrList(positionalCtx, exprConstraintDescrList); + populateExprConstraintDescrList(ctx, exprConstraintDescrList); + return exprConstraintDescrList; + } + + private void populateExprConstraintDescrList(ParserRuleContext ctx, List exprConstraintDescrList) { + if (ctx == null) { + return; + } + List descrList = visitDescrChildren(ctx); + for (BaseDescr descr : descrList) { + if (descr instanceof ExprConstraintDescr) { + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) descr; + exprConstraintDescr.setType(ctx instanceof DRLParser.PositionalConstraintsContext ? ExprConstraintDescr.Type.POSITIONAL : ExprConstraintDescr.Type.NAMED); + exprConstraintDescr.setPosition(exprConstraintDescrList.size()); + exprConstraintDescrList.add(exprConstraintDescr); + } + } + } + + /** + * Takes one constraint as String and create ExprConstraintDescr + */ + @Override + public ExprConstraintDescr visitConstraint(DRLParser.ConstraintContext ctx) { + String constraint = visitConstraintChildren(ctx); + if (!constraint.isEmpty()) { + ExprConstraintDescr constraintDescr = new ExprConstraintDescr(constraint); + constraintDescr.setType(ExprConstraintDescr.Type.NAMED); + return constraintDescr; + } + return null; + } + + @Override + public String visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { + return ctx.getText(); + } + + @Override + public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { + ExistsDescr existsDescr = new ExistsDescr(); + if (ctx.lhsExpression() != null) { + // exists( A() or B() ) + List baseDescrs = visitDescrChildren(ctx); + if (baseDescrs.size() == 1) { + existsDescr.addDescr(baseDescrs.get(0)); + } else { + throw new IllegalStateException("'exists()' children descr size must be 1 : " + ctx.getText()); + } + } else { + // exists A() + BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); + existsDescr.addDescr(descr); + } + return existsDescr; + } + + @Override + public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { + NotDescr notDescr = new NotDescr(); + if (ctx.lhsExpression() != null) { + // not ( A() or B() ) + List baseDescrs = visitDescrChildren(ctx); + if (baseDescrs.size() == 1) { + notDescr.addDescr(baseDescrs.get(0)); + } else { + throw new IllegalStateException("'not()' children descr size must be 1 : " + ctx.getText()); + } + } else { + // not A() + BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); + notDescr.addDescr(descr); + } + return notDescr; + } + + @Override + public EvalDescr visitLhsEval(DRLParser.LhsEvalContext ctx) { + return new EvalDescr(getTextPreservingWhitespace(ctx.conditionalOrExpression())); + } + + @Override + public BaseDescr visitLhsExpressionEnclosed(DRLParser.LhsExpressionEnclosedContext ctx) { + // enclosed expression is simply stripped because Descr itself is encapsulated + return (BaseDescr) visit(ctx.lhsExpression()); + } + + @Override + public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { + // For flatten nested OrDescr logic, we call visitDescrChildrenForDescrNodePair instead of usual visitDescrChildren + List descrList = visitDescrChildrenForDescrNodePair(ctx); + if (descrList.size() == 1) { + // Avoid nested OrDescr + return descrList.get(0).getDescr(); + } else { + OrDescr orDescr = new OrDescr(); + // For example, in case of A() or B() or C(), + // Parser creates AST like this: + // lhsOr + // / \ + // A() lhsOr + // / \ + // B() C() + // So, we need to flatten it so that OrDescr has A(), B() and C() as children. + List flattenedDescrs = flattenOrDescr(descrList); + flattenedDescrs.forEach(orDescr::addDescr); + return orDescr; + } + } + + private List flattenOrDescr(List descrList) { + List flattenedDescrs = new ArrayList<>(); + for (DescrNodePair descrNodePair : descrList) { + BaseDescr descr = descrNodePair.getDescr(); + ParseTree node = descrNodePair.getNode(); // parser node corresponding to the descr + if (descr instanceof OrDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { + // sibling OrDescr should be flattened unless it's explicitly enclosed by parenthesis + flattenedDescrs.addAll(((OrDescr) descr).getDescrs()); + } else { + flattenedDescrs.add(descr); + } + } + return flattenedDescrs; + } + + @Override + public BaseDescr visitLhsAnd(DRLParser.LhsAndContext ctx) { + return createAndDescr(ctx); + } + + private BaseDescr createAndDescr(ParserRuleContext ctx) { + // For flatten nested AndDescr logic, we call visitDescrChildrenForDescrNodePair instead of usual visitDescrChildren + List descrList = visitDescrChildrenForDescrNodePair(ctx); + if (descrList.size() == 1) { + // Avoid nested AndDescr + return descrList.get(0).getDescr(); + } else { + AndDescr andDescr = new AndDescr(); + // For example, in case of A() and B() and C(), + // Parser creates AST like this: + // lhsAnd + // / \ + // A() lhsAnd + // / \ + // B() C() + // So, we need to flatten it so that AndDescr has A(), B() and C() as children. + List flattenedDescrs = flattenAndDescr(descrList); + flattenedDescrs.forEach(andDescr::addDescr); + return andDescr; + } + } + + private List flattenAndDescr(List descrList) { + List flattenedDescrs = new ArrayList<>(); + for (DescrNodePair descrNodePair : descrList) { + BaseDescr descr = descrNodePair.getDescr(); + ParseTree node = descrNodePair.getNode(); // parser node corresponding to the descr + if (descr instanceof AndDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { + // sibling AndDescr should be flattened unless it's explicitly enclosed by parenthesis + flattenedDescrs.addAll(((AndDescr) descr).getDescrs()); + } else { + flattenedDescrs.add(descr); + } + } + return flattenedDescrs; + } + + @Override + public BaseDescr visitLhsAndDef(DRLParser.LhsAndDefContext ctx) { + return createAndDescr(ctx); + } + + @Override + public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { + return visitDescrChildren(ctx).get(0); // lhsUnary has only one child + } + + private void populateStartEnd(BaseDescr descr, ParserRuleContext ctx) { + descr.setStartCharacter(ctx.getStart().getStartIndex()); + // TODO: Current DRL6Parser adds +1 for EndCharacter but it doesn't look reasonable. At the moment, I don't add. Instead, I fix unit tests. + // I will revisit if this is the right approach. + descr.setEndCharacter(ctx.getStop().getStopIndex()); + } + + /** + * This is a special version of visitChildren(). + * This collects children BaseDescr objects and returns them as a list. + */ + private List visitDescrChildren(RuleNode node) { + List aggregator = new ArrayList<>(); + int n = node.getChildCount(); + + for (int i = 0; i < n && this.shouldVisitNextChild(node, aggregator); ++i) { + ParseTree c = node.getChild(i); + Object childResult = c.accept(this); + if (childResult instanceof BaseDescr) { + aggregator.add((BaseDescr) childResult); + } + } + return aggregator; + } + + // This method is used when the parent descr requires children parser node information for composing the descr. + // Ideally, we should use visitDescrChildren as possible and use the returned Descr object to compose the parent descr. + // However, for example, in flatten OrDescr/AndDescr logic, + // enhancing the returned Descr object of visitLhsExpressionEnclosed() (e.g. adding 'enclosed' flag to OrDescr/AndDescr) could be intrusive just for composing the parent descr. + private List visitDescrChildrenForDescrNodePair(RuleNode node) { + List aggregator = new ArrayList<>(); + int n = node.getChildCount(); + + for (int i = 0; i < n && this.shouldVisitNextChild(node, aggregator); ++i) { + ParseTree c = node.getChild(i); + Object childResult = c.accept(this); + if (childResult instanceof BaseDescr) { + aggregator.add(new DescrNodePair((BaseDescr) childResult, c)); // pairing the returned Descr and the parser node + } + } + return aggregator; + } + + private static class DescrNodePair { + private final BaseDescr descr; // returned Descr object + private final ParseTree node; // parser node corresponding to the descr. This is used for composing the parent descr. + + private DescrNodePair(BaseDescr descr, ParseTree node) { + this.descr = descr; + this.node = node; + } + + public BaseDescr getDescr() { + return descr; + } + + public ParseTree getNode() { + return node; + } + } + + /** + * Return the text of constraint as-is + */ + private String visitConstraintChildren(ParserRuleContext ctx) { + return getTokenTextPreservingWhitespace(ctx, tokenStream); + } +} \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md new file mode 100644 index 00000000000..c521ee6d14f --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md @@ -0,0 +1,38 @@ +## drools-parser + +This module is a reimplementation of the DRL (Drools Rule Language) parser based on ANTLR4. + +The current [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java) is based on ANTLR3 and contains a lot of custom modifications, which is hard to maintain. This new module should keep the separation between the parser syntax (`DRLParser.g4`) and the Descr generation (`DRLVisitorImpl.java`). + +This module started with a part of LSP to develop DRL editors, but it is not limited to that. This module will also replace DRL6Parser in the drools code base. + +### How is this developed? + +1. The starting point is [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java). While it contains lots of customizations, we can map its javadoc (e.g. `packageStatement := PACKAGE qualifiedIdentifier SEMICOLON?`) to `DRLParser.g4` (e.g. `packagedef : PACKAGE name=drlQualifiedName SEMI? ;`). +2. `DRLLexer.g4` is written to define tokens for DRL. +3. `DRLLexer.g4` imports `JavaLexer.g4` to reuse Java tokens. `DRLParser.g4` imports `JavaParser.g4` to reuse Java grammar. These Java parser files are distributed by ANTLR4 under BSD license. +4. In `DRLLexer.g4`, basically define tokens with a prefix "DRL_" to clarify they are DRL keywords. +5. In `DRLParser.g4`, define parser rules with a prefix "drl" if the rule name conflicts with `JavaParser.g4`. Sometimes we need to do that, because such a rule may contain DRL keywords. +6. (As of 2023/10/31) this parser doesn't deeply parse rule RHS (just multiple `RHS_CHUNK`s), because Drools passes RHS text to drools-compiler as-is. In case of developing DRL editors, we may need to integrate another Java LSP to support RHS code completion, etc. +7. LHS constraint (e.g. `age > 30`) is also handled as text. Further processing will be done in the later compiler phase. +8. `DRLParser` processes a DRL text and produces an AST(abstract syntax tree). Then apply `DRLVisitorImpl` to generate PackageDescr following the visitor pattern. So the main work would be implementing `DRLParser.g4` and `DRLVisitorImpl`. +9. Errors are handled by `DRLErrorListener` +10. (As of 2023/10/31) We have 2 test classes. `DRLParserTest` is a very basic test to check if the parser can parse DRL. `MiscDRLParserTest` contains various DRL syntax to check if the parser generates correct Descr objects. `MiscDRLParserTest` was ported from [RuleParserTest](https://github.com/apache/incubator-kie-drools/blob/main/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java) so that we can ensure the compatibility of generated Descr objects between the current implementation and the new one. +11. As `DRL6Parser` contains hard-coded customizations, sometimes we need to read and understand the `DRL6Parser` source codes to meet the compatibility. +12. (As of 2023/10/31) `MiscDRLParserTest` still has several test cases with `@Disabled` which are relatively lower priority or edge cases. They need to be resolved at some point in the future. To fix the issues, file a JIRA, remove the `@Disabled` annotation, and fix the implementation to pass the test case. + +### Next steps + +1. Create a feature branch in drools repo and replace `DRL6Parser` with this new parser. +2. We will detect issues in the new parser by running the existing tests in drools repo. If we find any issues, we will fix them in the new parser and add new tests to cover them. Such tests would be more or less Descr comparison tests, so we would add a new test class which is similar to `MiscDRLParserTest`. + +### Refactoring candidates +- `DRLParserHelper` and `DRLParserWrapper` have some duplicated code and purpose. We can merge them into one class. +- `MiscDRLParserTest` can be cleaner and fixed to align with SonarLint suggestions. +- Constraint related parser rules after `conditionalOrExpression` are written in antlr3 style. They could be refactored to antlr4 style (like `lhsExpression`). + +### Development tips +- IntelliJ IDEA has an ANTLR4 plugin, which "ANTLR Preview" window displays a parse tree. It is very useful to debug the parser rules. + +### Resources +[The Definitive ANTLR 4 Reference](https://pragprog.com/titles/tpantlr2/the-definitive-antlr-4-reference/) \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java new file mode 100644 index 00000000000..19ec4735363 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java @@ -0,0 +1,87 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import java.util.Collections; +import java.util.List; + +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.RecognitionException; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.DrlExprParser; +import org.drools.drl.parser.DroolsParserException; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * This is a helper class that provides helper methods to parse expressions + * using both the DRLExpressions parser and the DRLExprTree parser. + */ +public class Drl10ExprParser implements DrlExprParser { + + private ParserHelper helper = null; + + private final LanguageLevelOption languageLevel; + + public Drl10ExprParser(LanguageLevelOption languageLevel) { + this.languageLevel = languageLevel; + } + + /** Parse an expression from text */ + public ConstraintConnectiveDescr parse(final String text) { + ConstraintConnectiveDescr constraint = null; + try { + DRLLexer lexer = new DRLLexer(CharStreams.fromString(text)); + CommonTokenStream input = new CommonTokenStream(lexer); + helper = new ParserHelper(input, null, languageLevel); + DRLExpressions parser = new DRL6Expressions(input, helper); + 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); + } + } catch (RecognitionException e) { + helper.reportError(e); + } + return constraint; + } + + public String getLeftMostExpr() { + return helper != null ? helper.getLeftMostExpr() : null; + } + + /** + * @return true if there were parser errors. + */ + public boolean hasErrors() { + return helper != null && helper.hasErrors(); + } + + /** + * @return a list of errors found while parsing. + */ + @SuppressWarnings("unchecked") + public List getErrors() { + return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; + } + +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java new file mode 100644 index 00000000000..abf586c55d0 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java @@ -0,0 +1,250 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.antlr.v4.runtime.FailedPredicateException; +import org.antlr.v4.runtime.NoViableAltException; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Token; +import org.drools.drl.parser.DRLFactory; +import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.lang.DroolsParaphraseTypes; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * Helper class that generates DroolsParserException with user friendly error + * messages. + * + * @see DroolsParserException + */ +public class DroolsParserExceptionFactory { + public final static String NO_VIABLE_ALT_MESSAGE = "Line %1$d:%2$d no viable alternative at input '%3$s'%4$s"; + public final static String FAILED_PREDICATE_MESSAGE = "Line %1$d:%2$d rule '%3$s' failed predicate: {%4$s}?%5$s"; + public final static String TRAILING_SEMI_COLON_NOT_ALLOWED_MESSAGE = "Line %1$d:%2$d trailing semi-colon not allowed%3$s"; + public final static String PARSER_LOCATION_MESSAGE_COMPLETE = " in %1$s %2$s"; + public final static String PARSER_LOCATION_MESSAGE_PART = " in %1$s"; + public final static String UNEXPECTED_EXCEPTION = "Line %1$d:%2$d unexpected exception at input '%3$s'. Exception: %4$s. Stack trace:\n %5$s"; + + private final Collection> paraphrases; + + // TODO: need to deal with this array + private String[] tokenNames = null; + + private final LanguageLevelOption languageLevel; + + /** + * DroolsParserErrorMessages constructor. + * + * @param tokenNames + * tokenNames generated by ANTLR + * @param paraphrases + * paraphrases parser structure + */ + public DroolsParserExceptionFactory(Collection> paraphrases, + LanguageLevelOption languageLevel) { + this.paraphrases = paraphrases; + this.languageLevel = languageLevel; + } + + /** + * This method creates a DroolsParserException for trailing semicolon + * exception, full of information. + * + * @param line + * line number + * @param column + * column position + * @param offset + * char offset + * @return DroolsParserException filled. + */ + public DroolsParserException createTrailingSemicolonException( int line, + int column, + int offset ) { + String message = String + .format( + TRAILING_SEMI_COLON_NOT_ALLOWED_MESSAGE, + line, + column, + formatParserLocation() ); + + return new DroolsParserException( "ERR 104", + message, + line, + column, + offset, + null ); + } + + /** + * This method creates a DroolsParserException full of information. + * + * @param e + * original exception + * @return DroolsParserException filled. + */ + public DroolsParserException createDroolsException( RecognitionException e ) { + List codeAndMessage = createErrorMessage( e ); + return new DroolsParserException( codeAndMessage.get( 1 ), + codeAndMessage + .get( 0 ), + // TODO verify this is correct + e.getOffendingToken().getLine(), + e.getOffendingToken().getCharPositionInLine(), + e.getOffendingToken().getStartIndex(), + e ); + } + + /** + * This will take a RecognitionException, and create a sensible error + * message out of it + */ + private List createErrorMessage( RecognitionException e ) { + List codeAndMessage = new ArrayList<>( 2 ); + String message; + if ( e instanceof NoViableAltException ) { + // NoViableAltException nvae = (NoViableAltException) e; + message = String.format( + NO_VIABLE_ALT_MESSAGE, + // TODO verify this is correct + e.getOffendingToken().getLine(), + e.getOffendingToken().getCharPositionInLine(), + getBetterToken( e.getOffendingToken() ), + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 101" ); + } else if ( e instanceof FailedPredicateException ) { + FailedPredicateException fpe = (FailedPredicateException) e; + String ruleName = fpe.getRecognizer().getRuleNames()[fpe.getRuleIndex()]; + message = String.format( + FAILED_PREDICATE_MESSAGE, + // TODO verify this is correct + e.getOffendingToken().getLine(), + e.getOffendingToken().getCharPositionInLine(), + ruleName, + fpe.getPredicate(), + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 103" ); + } + if ( codeAndMessage.get( 0 ).length() == 0 ) { + codeAndMessage.add( "?????" ); + } + return codeAndMessage; + } + + public DroolsParserException createDroolsException( Exception e, + Token token ) { + StringWriter sw = new StringWriter(); + e.printStackTrace( new PrintWriter(sw) ); + return new DroolsParserException( String.format( + DroolsParserExceptionFactory.UNEXPECTED_EXCEPTION, + token.getLine(), + token.getCharPositionInLine(), + getBetterToken( token ), + e.toString(), + sw.toString() ), + e ); + + } + + /** + * This will take Paraphrases stack, and create a sensible location + */ + private String formatParserLocation() { + StringBuilder sb = new StringBuilder(); + if ( paraphrases != null ) { + for ( Map map : paraphrases ) { + for ( Entry activeEntry : map.entrySet() ) { + if ( activeEntry.getValue().length() == 0 ) { + String kStr = getLocationName( activeEntry.getKey() ); + if( kStr.length() > 0 ){ + sb.append( String.format( PARSER_LOCATION_MESSAGE_PART, kStr ) ); + } + } else { + sb.append( String.format( PARSER_LOCATION_MESSAGE_COMPLETE, + getLocationName( activeEntry.getKey() ), + activeEntry.getValue() ) ); + } + } + } + } + return sb.toString(); + } + + /** + * Returns a string based on Paraphrase Type + * + * @param type + * Paraphrase Type + * @return a string representing the + */ + private String getLocationName( DroolsParaphraseTypes type ) { + switch ( type ) { + case PACKAGE : + return "package"; + case IMPORT : + return "import"; + case FUNCTION_IMPORT : + return "function import"; + case ACCUMULATE_IMPORT : + return "accumulate import"; + case GLOBAL : + return "global"; + case FUNCTION : + return "function"; + case QUERY : + return "query"; + case TEMPLATE : + return "template"; + case RULE : + return "rule"; + case RULE_ATTRIBUTE : + return "rule attribute"; + case PATTERN : + return "pattern"; + case EVAL : + return "eval"; + default : + return ""; + } + } + + /** + * Helper method that creates a user friendly token definition + * + * @param token + * token + * @return user friendly token definition + */ + private String getBetterToken( Token token ) { + if ( token == null ) { + return ""; + } + return DRLFactory.getBetterToken(token.getType(), token.getText(), languageLevel); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java new file mode 100644 index 00000000000..f729115b7ca --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java @@ -0,0 +1,678 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.drools.drl10.parser; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.antlr.runtime.RecognizerSharedState; +import org.antlr.v4.runtime.CommonToken; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.TokenStream; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.dsl.AbstractClassTypeDeclarationBuilder; +import org.drools.drl.ast.dsl.AccumulateDescrBuilder; +import org.drools.drl.ast.dsl.AccumulateImportDescrBuilder; +import org.drools.drl.ast.dsl.AttributeDescrBuilder; +import org.drools.drl.ast.dsl.AttributeSupportBuilder; +import org.drools.drl.ast.dsl.BehaviorDescrBuilder; +import org.drools.drl.ast.dsl.CEDescrBuilder; +import org.drools.drl.ast.dsl.CollectDescrBuilder; +import org.drools.drl.ast.dsl.ConditionalBranchDescrBuilder; +import org.drools.drl.ast.dsl.DeclareDescrBuilder; +import org.drools.drl.ast.dsl.DescrBuilder; +import org.drools.drl.ast.dsl.DescrFactory; +import org.drools.drl.ast.dsl.EntryPointDeclarationDescrBuilder; +import org.drools.drl.ast.dsl.EnumDeclarationDescrBuilder; +import org.drools.drl.ast.dsl.EnumLiteralDescrBuilder; +import org.drools.drl.ast.dsl.EvalDescrBuilder; +import org.drools.drl.ast.dsl.FieldDescrBuilder; +import org.drools.drl.ast.dsl.ForallDescrBuilder; +import org.drools.drl.ast.dsl.FunctionDescrBuilder; +import org.drools.drl.ast.dsl.GlobalDescrBuilder; +import org.drools.drl.ast.dsl.GroupByDescrBuilder; +import org.drools.drl.ast.dsl.ImportDescrBuilder; +import org.drools.drl.ast.dsl.NamedConsequenceDescrBuilder; +import org.drools.drl.ast.dsl.PackageDescrBuilder; +import org.drools.drl.ast.dsl.PatternContainerDescrBuilder; +import org.drools.drl.ast.dsl.PatternDescrBuilder; +import org.drools.drl.ast.dsl.QueryDescrBuilder; +import org.drools.drl.ast.dsl.RuleDescrBuilder; +import org.drools.drl.ast.dsl.TypeDeclarationDescrBuilder; +import org.drools.drl.ast.dsl.UnitDescrBuilder; +import org.drools.drl.ast.dsl.WindowDeclarationDescrBuilder; +import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.lang.DroolsEditorType; +import org.drools.drl.parser.lang.DroolsParaphraseTypes; +import org.drools.drl.parser.lang.DroolsSentence; +import org.drools.drl.parser.lang.DroolsSentenceType; +import org.drools.drl.parser.lang.DroolsSoftKeywords; +import org.drools.drl.parser.lang.DroolsToken; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * This is a class to hold all the helper functions/methods used + * by the DRL parser + */ +public class ParserHelper { + public final String[] statementKeywords = new String[]{ + DroolsSoftKeywords.PACKAGE, + DroolsSoftKeywords.UNIT, + DroolsSoftKeywords.IMPORT, + DroolsSoftKeywords.GLOBAL, + DroolsSoftKeywords.DECLARE, + DroolsSoftKeywords.FUNCTION, + DroolsSoftKeywords.RULE, + DroolsSoftKeywords.QUERY + }; + + public List errors = new ArrayList<>(); + public LinkedList editorInterface = null; + public boolean isEditorInterfaceEnabled = false; + private Deque> paraphrases = new ArrayDeque<>(); + + // parameters from parser + private DroolsParserExceptionFactory errorMessageFactory = null; + private TokenStream input = null; + private RecognizerSharedState state = null; + + private String leftMostExpr = null; + + // helper attribute + private boolean hasOperator = false; + + private final LanguageLevelOption languageLevel; + + public ParserHelper(TokenStream input, + RecognizerSharedState state, + LanguageLevelOption languageLevel) { + this.errorMessageFactory = new DroolsParserExceptionFactory( paraphrases, languageLevel ); + this.input = input; + this.state = state; + this.languageLevel = languageLevel; + } + + public LinkedList getEditorInterface() { + return editorInterface; + } + + public void setLeftMostExpr( String value ) { + this.leftMostExpr = value; + } + + public String getLeftMostExpr() { + return this.leftMostExpr; + } + + public void enableEditorInterface() { + isEditorInterfaceEnabled = true; + } + + public void disableEditorInterface() { + isEditorInterfaceEnabled = false; + } + + public void setHasOperator( boolean hasOperator ) { + this.hasOperator = hasOperator; + } + + public boolean getHasOperator() { + return hasOperator; + } + + public void beginSentence( DroolsSentenceType sentenceType ) { + if ( isEditorInterfaceEnabled ) { + if ( null == editorInterface ) { + editorInterface = new LinkedList<>(); + } + if (editorInterface.isEmpty()){ + DroolsSentence sentence = new DroolsSentence(); + sentence.setType( sentenceType ); + editorInterface.add( sentence ); + } + } + } + + public DroolsSentence getActiveSentence() { + return editorInterface.getLast(); + } + + public void emit( List< ? > tokens, + DroolsEditorType editorType ) { + if ( isEditorInterfaceEnabled && tokens != null ) { + for ( Object activeObject : tokens ) { + emit( (Token) activeObject, + editorType ); + } + } + } + + public void emit( Token token, + DroolsEditorType editorType ) { + if ( isEditorInterfaceEnabled && token != null && editorType != null ) { + ((DroolsToken) token).setEditorType( editorType ); + getActiveSentence().addContent( (DroolsToken) token ); + } + } + + public void emit( int activeContext ) { + if ( isEditorInterfaceEnabled ) { + getActiveSentence().addContent( activeContext ); + } + } + + public DroolsToken getLastTokenOnList( LinkedList< ? > list ) { + DroolsToken lastToken = null; + for ( Object object : list ) { + if ( object instanceof DroolsToken ) { + lastToken = (DroolsToken) object; + } + } + return lastToken; + } + + public String retrieveLT( int LTNumber ) { + if ( null == input ) return null; + if ( null == input.LT( LTNumber ) ) return null; + if ( null == input.LT( LTNumber ).getText() ) return null; + + return input.LT( LTNumber ).getText(); + } + + public boolean validateLT( int LTNumber, + String text ) { + String text2Validate = retrieveLT( LTNumber ); + return validateText( text, text2Validate ); + } + + private boolean validateText( String text, String text2Validate ) { + return text2Validate != null && text2Validate.equals( text ); + } + + public boolean isPluggableEvaluator( int offset, + boolean negated ) { + String text2Validate = retrieveLT( offset ); + return text2Validate != null && DroolsSoftKeywords.isOperator(text2Validate, negated); + } + + public boolean isPluggableEvaluator( boolean negated ) { + return isPluggableEvaluator( 1, + negated ); + } + + public boolean validateIdentifierKey( String text ) { + return validateLT( 1, + text ); + } + + public boolean validateCEKeyword( int index ) { + String text2Validate = retrieveLT( index ); + return validateText( text2Validate, + DroolsSoftKeywords.NOT ) || + validateText( text2Validate, + DroolsSoftKeywords.EXISTS ) || + validateText( text2Validate, + DroolsSoftKeywords.FORALL ) || + validateText( text2Validate, + DroolsSoftKeywords.AND ) || + validateText( text2Validate, + DroolsSoftKeywords.OR ) || + validateText( text2Validate, + DroolsSoftKeywords.COLLECT ) || + validateText( text2Validate, + DroolsSoftKeywords.FROM ) || + validateText( text2Validate, + DroolsSoftKeywords.END ) || + validateText( text2Validate, + DroolsSoftKeywords.EVAL ) || + validateText( text2Validate, + DroolsSoftKeywords.OVER ) || + validateText( text2Validate, + DroolsSoftKeywords.THEN ); + } + + public boolean validateStatement( int index ) { + boolean ret = false; + String text2Validate = retrieveLT( index ); + for ( String st : statementKeywords ) { + if ( validateText( text2Validate, + st ) ) { + ret = true; + break; + } + } + return ret || validateAttribute( index ); + } + + public boolean validateAttribute( int index ) { + String text2Validate = retrieveLT( index ); + return validateText( text2Validate, + DroolsSoftKeywords.SALIENCE ) || + validateText( text2Validate, + DroolsSoftKeywords.ENABLED ) || + (validateText( text2Validate, + DroolsSoftKeywords.NO ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.LOOP )) || + (validateText( text2Validate, + DroolsSoftKeywords.AUTO ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.FOCUS )) || + (validateText( text2Validate, + DroolsSoftKeywords.LOCK ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.ON ) && + validateLT( index + 3, + "-" ) && + validateLT( index + 4, + DroolsSoftKeywords.ACTIVE )) || + (validateText( text2Validate, + DroolsSoftKeywords.AGENDA ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.GROUP )) || + (validateText( text2Validate, + DroolsSoftKeywords.ACTIVATION ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.GROUP )) || + (validateText( text2Validate, + DroolsSoftKeywords.RULEFLOW ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.GROUP )) || + (validateText( text2Validate, + DroolsSoftKeywords.DATE ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.EFFECTIVE )) || + (validateText( text2Validate, + DroolsSoftKeywords.DATE ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.EXPIRES )) || + validateText( text2Validate, + DroolsSoftKeywords.DIALECT ) || + validateText( text2Validate, + DroolsSoftKeywords.CALENDARS ) || + validateText( text2Validate, + DroolsSoftKeywords.TIMER ) || + validateText( text2Validate, + DroolsSoftKeywords.DURATION ) || + validateText( text2Validate, + DroolsSoftKeywords.REFRACT ) || + validateText( text2Validate, + DroolsSoftKeywords.DIRECT ); + } + + public void reportError( RecognitionException ex ) { + // if we've already reported an error and have not matched a token + // yet successfully, don't report any errors. + if ( state.errorRecovery ) { + return; + } + state.errorRecovery = true; + + errors.add( errorMessageFactory.createDroolsException( ex ) ); + } + + public void reportError( Exception e ) { + try { + errors.add( errorMessageFactory.createDroolsException( e, + input.LT( 1 ) ) ); + } catch (Exception ignored) { + errors.add(new DroolsParserException( "Unexpected error: " + e.getMessage(), e )); + } + } + + /** return the raw DroolsParserException errors */ + public List getErrors() { + return errors; + } + + /** Return a list of pretty strings summarising the errors */ + public List getErrorMessages() { + List messages = new ArrayList<>( errors.size() ); + + for ( DroolsParserException activeException : errors ) { + messages.add( activeException.getMessage() ); + } + + return messages; + } + + /** return true if any parser errors were accumulated */ + public boolean hasErrors() { + return !errors.isEmpty(); + } + + /** + * Method that adds a paraphrase type into paraphrases stack. + * + * @param type + * paraphrase type + */ + public void pushParaphrases( DroolsParaphraseTypes type ) { + Map activeMap = new HashMap<>(); + activeMap.put( type, + "" ); + paraphrases.push( activeMap ); + } + + public Map popParaphrases() { + return paraphrases.pop(); + } + + /** + * Method that sets paraphrase value for a type into paraphrases stack. + * + * @param type + * paraphrase type + * @param value + * paraphrase value + */ + public void setParaphrasesValue( DroolsParaphraseTypes type, + String value ) { + paraphrases.peek().put( type, + value ); + } + + void setStart( DescrBuilder< ? , ? > db ) { + setStart( db, + input.LT( 1 ) ); + } + + void setStart( DescrBuilder< ? , ? > db, + Token first ) { + if ( db != null && first != null ) { + db.startCharacter( ((CommonToken) first).getStartIndex() ).startLocation( first.getLine(), + first.getCharPositionInLine() ); + } + } + + void setStart( BaseDescr descr, + Token first ) { + if ( descr != null && first != null ) { + descr.setLocation( first.getLine(), + first.getCharPositionInLine() ); + descr.setStartCharacter( ((CommonToken) first).getStartIndex() ); + } + } + + void setEnd( BaseDescr descr ) { + Token last = input.LT( -1 ); + if ( descr != null && last != null ) { + int endLocation = last.getText() != null ? last.getCharPositionInLine() + last.getText().length() - 1 : last.getCharPositionInLine(); + descr.setEndCharacter( ((CommonToken) last).getStopIndex() + 1 ); + descr.setEndLocation( last.getLine(), + endLocation ); + } + } + + void setEnd( DescrBuilder< ? , ? > db ) { + Token last = input.LT( -1 ); + if ( db != null && last != null ) { + int endLocation = last.getText() != null ? last.getCharPositionInLine() + last.getText().length() - 1 : last.getCharPositionInLine(); + db.endCharacter( ((CommonToken) last).getStopIndex() + 1 ).endLocation( last.getLine(), + endLocation ); + } + } + + @SuppressWarnings("unchecked") + public > T start( DescrBuilder< ? , ? > ctxBuilder, + Class clazz, + String param ) { + if ( state.backtracking == 0 ) { + if ( PackageDescrBuilder.class.isAssignableFrom( clazz ) ) { + pushParaphrases( DroolsParaphraseTypes.PACKAGE ); + beginSentence( DroolsSentenceType.PACKAGE ); + setStart( ctxBuilder ); + } else if ( ImportDescrBuilder.class.isAssignableFrom( clazz ) ) { + ImportDescrBuilder imp; + if ( validateLT( 2, + DroolsSoftKeywords.FUNCTION ) || + validateLT( 2, + DroolsSoftKeywords.STATIC ) ) { + imp = ctxBuilder == null ? + DescrFactory.newPackage().newFunctionImport() : + ((PackageDescrBuilder) ctxBuilder).newFunctionImport(); + } else { + imp = ctxBuilder == null ? + DescrFactory.newPackage().newImport() : + ((PackageDescrBuilder) ctxBuilder).newImport(); + } + pushParaphrases( DroolsParaphraseTypes.IMPORT ); + beginSentence( DroolsSentenceType.IMPORT_STATEMENT ); + setStart( imp ); + return (T) imp; + } else if ( UnitDescrBuilder.class.isAssignableFrom( clazz ) ) { + UnitDescrBuilder imp = ctxBuilder == null ? + DescrFactory.newPackage().newUnit() : + ((PackageDescrBuilder) ctxBuilder).newUnit(); + pushParaphrases( DroolsParaphraseTypes.UNIT ); + beginSentence( DroolsSentenceType.UNIT ); + setStart( imp ); + return (T) imp; + } else if ( AccumulateImportDescrBuilder.class.isAssignableFrom( clazz ) ) { + AccumulateImportDescrBuilder imp = ctxBuilder == null ? + DescrFactory.newPackage().newAccumulateImport() : + ((PackageDescrBuilder) ctxBuilder).newAccumulateImport(); + pushParaphrases( DroolsParaphraseTypes.ACCUMULATE_IMPORT ); + beginSentence( DroolsSentenceType.ACCUMULATE_IMPORT_STATEMENT ); + setStart( imp ); + return (T) imp; + } else if ( GlobalDescrBuilder.class.isAssignableFrom( clazz ) ) { + GlobalDescrBuilder global = ctxBuilder == null ? + DescrFactory.newPackage().newGlobal() : + ((PackageDescrBuilder) ctxBuilder).newGlobal(); + pushParaphrases( DroolsParaphraseTypes.GLOBAL ); + beginSentence( DroolsSentenceType.GLOBAL ); + setStart( global ); + return (T) global; + } else if ( DeclareDescrBuilder.class.isAssignableFrom( clazz ) ) { + DeclareDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare() : + ((PackageDescrBuilder) ctxBuilder).newDeclare(); + return (T) declare; + } else if ( TypeDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + TypeDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().type() : + ((DeclareDescrBuilder) ctxBuilder).type(); + pushParaphrases( DroolsParaphraseTypes.TYPE_DECLARE ); + beginSentence( DroolsSentenceType.TYPE_DECLARATION ); + setStart( declare ); + return (T) declare; + } else if ( EnumDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + EnumDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().enumerative() : + ((DeclareDescrBuilder) ctxBuilder).enumerative(); + pushParaphrases( DroolsParaphraseTypes.ENUM_DECLARE ); + beginSentence( DroolsSentenceType.ENUM_DECLARATION ); + setStart( declare ); + return (T) declare; + }else if ( EntryPointDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + EntryPointDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().entryPoint() : + ((DeclareDescrBuilder) ctxBuilder).entryPoint(); + pushParaphrases( DroolsParaphraseTypes.ENTRYPOINT_DECLARE ); + beginSentence( DroolsSentenceType.ENTRYPOINT_DECLARATION ); + setStart( declare ); + return (T) declare; + } else if ( WindowDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + WindowDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().window() : + ((DeclareDescrBuilder) ctxBuilder).window(); + pushParaphrases( DroolsParaphraseTypes.WINDOW_DECLARE ); + beginSentence( DroolsSentenceType.WINDOW_DECLARATION ); + setStart( declare ); + return (T) declare; + } else if ( FieldDescrBuilder.class.isAssignableFrom( clazz ) ) { + FieldDescrBuilder field = ((AbstractClassTypeDeclarationBuilder) ctxBuilder).newField( param ); + setStart( field ); + return (T) field; + } else if ( EnumLiteralDescrBuilder.class.isAssignableFrom( clazz ) ) { + EnumLiteralDescrBuilder literal = ((EnumDeclarationDescrBuilder) ctxBuilder).newEnumLiteral( param ); + setStart( literal ); + return (T) literal; + } else if ( FunctionDescrBuilder.class.isAssignableFrom( clazz ) ) { + FunctionDescrBuilder function; + if ( ctxBuilder == null ) { + function = DescrFactory.newPackage().newFunction(); + } else { + PackageDescrBuilder pkg = (PackageDescrBuilder) ctxBuilder; + function = pkg.newFunction().namespace( pkg.getDescr().getName() ); + AttributeDescr attribute = pkg.getDescr().getAttribute( "dialect" ); + if ( attribute != null ) { + function.dialect( attribute.getValue() ); + } + } + pushParaphrases( DroolsParaphraseTypes.FUNCTION ); + beginSentence( DroolsSentenceType.FUNCTION ); + setStart( function ); + return (T) function; + } else if ( RuleDescrBuilder.class.isAssignableFrom( clazz ) ) { + RuleDescrBuilder rule = ctxBuilder == null ? + DescrFactory.newPackage().newRule() : + ((PackageDescrBuilder) ctxBuilder).newRule(); + pushParaphrases( DroolsParaphraseTypes.RULE ); + beginSentence( DroolsSentenceType.RULE ); + setStart( rule ); + return (T) rule; + } else if ( QueryDescrBuilder.class.isAssignableFrom( clazz ) ) { + QueryDescrBuilder query = ctxBuilder == null ? + DescrFactory.newPackage().newQuery() : + ((PackageDescrBuilder) ctxBuilder).newQuery(); + pushParaphrases( DroolsParaphraseTypes.QUERY ); + beginSentence( DroolsSentenceType.QUERY ); + setStart( query ); + return (T) query; + } else if ( AttributeDescrBuilder.class.isAssignableFrom( clazz ) ) { + AttributeDescrBuilder< ? > attribute = ((AttributeSupportBuilder< ? >) ctxBuilder).attribute(param); + setStart( attribute ); + return (T) attribute; + } else if ( EvalDescrBuilder.class.isAssignableFrom( clazz ) ) { + EvalDescrBuilder< ? > eval = ((CEDescrBuilder< ? , ? >) ctxBuilder).eval(); + pushParaphrases( DroolsParaphraseTypes.EVAL ); + beginSentence( DroolsSentenceType.EVAL ); + setStart( eval ); + return (T) eval; + } else if ( ForallDescrBuilder.class.isAssignableFrom( clazz ) ) { + ForallDescrBuilder< ? > forall = ((CEDescrBuilder< ? , ? >) ctxBuilder).forall(); + setStart( forall ); + return (T) forall; + } else if ( CEDescrBuilder.class.isAssignableFrom( clazz ) ) { + setStart( ctxBuilder ); + return (T) ctxBuilder; + } else if ( PatternDescrBuilder.class.isAssignableFrom( clazz ) ) { + PatternDescrBuilder< ? > pattern = ((PatternContainerDescrBuilder< ? , ? >) ctxBuilder).pattern(); + pushParaphrases( DroolsParaphraseTypes.PATTERN ); + setStart( pattern ); + return (T) pattern; + } else if ( CollectDescrBuilder.class.isAssignableFrom( clazz ) ) { + CollectDescrBuilder< ? > collect = ((PatternDescrBuilder< ? >) ctxBuilder).from().collect(); + setStart( collect ); + return (T) collect; + } else if ( GroupByDescrBuilder.class.isAssignableFrom(clazz) ) { + // GroupBy extends Accumulate and thus need to be before it + GroupByDescrBuilder< ? > groupBy = ((PatternDescrBuilder< ? >) ctxBuilder).from().groupBy(); + setStart( groupBy ); + return (T) groupBy; + } else if ( AccumulateDescrBuilder.class.isAssignableFrom( clazz ) ) { + AccumulateDescrBuilder< ? > accumulate = ((PatternDescrBuilder< ? >) ctxBuilder).from().accumulate(); + setStart( accumulate ); + return (T) accumulate; + } else if ( BehaviorDescrBuilder.class.isAssignableFrom( clazz ) ) { + BehaviorDescrBuilder< ? > behavior = ((PatternDescrBuilder< ? >) ctxBuilder).behavior(); + setStart( behavior ); + return (T) behavior; + } else if ( NamedConsequenceDescrBuilder.class.isAssignableFrom( clazz ) ) { + NamedConsequenceDescrBuilder< ? > namedConsequence = ((CEDescrBuilder< ? , ? >) ctxBuilder).namedConsequence(); + setStart( namedConsequence ); + return (T) namedConsequence; + } else if ( ConditionalBranchDescrBuilder.class.isAssignableFrom( clazz ) ) { + ConditionalBranchDescrBuilder< ? > conditionalBranch = ((CEDescrBuilder< ? , ? >) ctxBuilder).conditionalBranch(); + setStart( conditionalBranch ); + return (T) conditionalBranch; + } + } + return null; + } + + @SuppressWarnings("unchecked") + public > T end( Class clazz, + DescrBuilder< ? , ? > builder ) { + if ( state.backtracking == 0 ) { + if ( !(FieldDescrBuilder.class.isAssignableFrom( clazz ) || + AttributeDescrBuilder.class.isAssignableFrom( clazz ) || + CEDescrBuilder.class.isAssignableFrom( clazz ) || + CollectDescrBuilder.class.isAssignableFrom( clazz ) || + AccumulateDescrBuilder.class.isAssignableFrom( clazz ) || + ForallDescrBuilder.class.isAssignableFrom( clazz ) || + BehaviorDescrBuilder.class.isAssignableFrom( clazz ) || + ConditionalBranchDescrBuilder.class.isAssignableFrom( clazz ) || + NamedConsequenceDescrBuilder.class.isAssignableFrom( clazz )) ) { + popParaphrases(); + } + + if (RuleDescrBuilder.class.isAssignableFrom(clazz)) { + RuleDescrBuilder ruleDescrBuilder = (RuleDescrBuilder)builder; + ruleDescrBuilder.end().getDescr().afterRuleAdded(ruleDescrBuilder.getDescr()); + } + + setEnd( builder ); + return (T) builder; + } + return null; + } + + public String[] getStatementKeywords() { + return statementKeywords; + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java new file mode 100644 index 00000000000..ef22da2dce3 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java @@ -0,0 +1,81 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.TokenStream; +import org.antlr.v4.runtime.misc.Interval; + +/** + * Collection of String utilities used by DRLParser. + * This may be merged in drools-util + */ +public class ParserStringUtils { + + private ParserStringUtils() { + } + + /** + * Strip string delimiters (e.g. "foo" -> foo) + */ + public static String safeStripStringDelimiters(String value) { + if (value != null) { + value = value.trim(); + if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { + value = value.substring(1, value.length() - 1); + } + } + return value; + } + + /** + * Get text from ParserRuleContext's CharStream without trimming whitespace + */ + public static String getTextPreservingWhitespace(ParserRuleContext ctx) { + // Using raw CharStream + int startIndex = ctx.start.getStartIndex(); + int stopIndex = ctx.stop.getStopIndex(); + if (startIndex > stopIndex) { + // no text + return ""; + } + Interval interval = new Interval(startIndex, stopIndex); + return ctx.start.getTokenSource().getInputStream().getText(interval); + } + + /** + * Get text from ParserRuleContext's CharStream without trimming whitespace + * tokenStream is required to get hidden channel token (e.g. whitespace). + * Unlike getTextPreservingWhitespace, this method reflects Lexer normalizeString + */ + public static String getTokenTextPreservingWhitespace(ParserRuleContext ctx, TokenStream tokenStream) { + return tokenStream.getText(ctx.start, ctx.stop); + } + + /** + * Just remove leading "then" + */ + public static String trimThen(String rhs) { + if (rhs.startsWith("then")) { + return rhs.substring("then".length()); + } else { + throw new DRLParserException("rhs has to start with 'then' : rhs = " + rhs); + } + } +} diff --git a/drools-drl/pom.xml b/drools-drl/pom.xml index 91f12f3d758..2fb61bb3006 100644 --- a/drools-drl/pom.xml +++ b/drools-drl/pom.xml @@ -39,6 +39,7 @@ drools-drl-ast drools-drl-extensions drools-drl-parser + drools-drl-parser-tests diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java index 08eeb33edae..c7357aad4de 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java @@ -25,6 +25,7 @@ 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.junit.After; import org.junit.Before; import org.junit.Test; @@ -42,7 +43,7 @@ public class DRLExprParserTest { @Before public void setUp() throws Exception { new EvaluatorRegistry(); - this.parser = new DrlExprParser(LanguageLevelOption.DRL6); + this.parser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL6); } @After diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java index 649b43c37fe..5eb52e62830 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java @@ -24,6 +24,7 @@ import org.drools.drl.ast.descr.AtomicExprDescr; import org.drools.drl.ast.descr.BindingDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.DrlExprParserFactory; import org.drools.mvel.evaluators.MatchesEvaluatorsDefinition; import org.drools.mvel.evaluators.SetEvaluatorsDefinition; import org.junit.Before; @@ -358,7 +359,7 @@ public void testProcessImplicitConstraints() throws Exception { } public ConstraintConnectiveDescr parse( final String constraint ) { - DrlExprParser parser = new DrlExprParser(LanguageLevelOption.DRL6); + DrlExprParser parser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL6); ConstraintConnectiveDescr result = parser.parse( constraint ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java index d4089c34601..6d14f2355c6 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java @@ -48,6 +48,8 @@ public static Collection getParameters() { @Test public void testAlpha() { + + String str = "import " + Person.class.getCanonicalName() + "\n" + "rule R1 when\n" + diff --git a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java index ba67c653c3e..6e6ef96a82a 100644 --- a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java +++ b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java @@ -20,6 +20,7 @@ import java.util.List; +import org.drools.drl.parser.DrlExprParserFactory; import org.drools.drl.parser.impl.Operator; import org.drools.drl.parser.DrlExprParser; import org.drools.drl.ast.descr.AtomicExprDescr; @@ -57,7 +58,7 @@ public ExprConstraintDescrVisitor(Pattern pattern, VerifierData data, OrderNumbe public void visit(ExprConstraintDescr descr) { - DrlExprParser drlExprParser = new DrlExprParser(LanguageLevelOption.DRL5); + DrlExprParser drlExprParser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL5); ConstraintConnectiveDescr constraintConnectiveDescr = drlExprParser.parse(descr.getExpression()); visit(constraintConnectiveDescr.getDescrs()); 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; diff --git a/pom.xml b/pom.xml index 5fae74ed325..40f4d9d7240 100644 --- a/pom.xml +++ b/pom.xml @@ -310,6 +310,28 @@ + + + DRL10 + + + DRL10 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + DRL10 + + + + + + From 7943061af00e008ac5b48d8c2712db8118a264ae Mon Sep 17 00:00:00 2001 From: Mario Fusco Date: Wed, 14 Feb 2024 12:42:05 +0100 Subject: [PATCH 005/141] =?UTF-8?q?Revert=20"[DROOLS-7591]=20Experiment=20?= =?UTF-8?q?branch=20:=20migrate=20a=20new=20drools-lsp=20parser=20int?= =?UTF-8?q?=E2=80=A6"=20(#5689)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 3699d67543dcaf4e8e7527f017f44dd9b9564f24. --- ...nowledgeBuilderRulesConfigurationImpl.java | 1 + .../org/drools/compiler/lang/DescrDumper.java | 3 +- .../compiler/rule/builder/PatternBuilder.java | 3 +- .../rule/builder/QueryElementBuilder.java | 5 +- drools-drl/drools-drl-parser-tests/pom.xml | 81 - .../drl10/parser/DRLExprParserTest.java | 271 -- .../drools/drl10/parser/DRLParserTest.java | 95 - .../drools/drl10/parser/DescrDumperTest.java | 368 -- .../drl10/parser/MiscDRLParserTest.java | 3443 ----------------- .../src/test/resources/logback-test.xml | 16 - .../drools/drl10/parser/Rule_with_Extends.drl | 25 - .../drl10/parser/Rule_with_Metadata.drl | 27 - .../drl10/parser/Rule_with_nested_LHS.drl | 28 - .../org/drools/drl10/parser/accumulate.drl | 25 - .../parser/accumulateExternalFunction.drl | 23 - .../parser/accumulateMultipleFunctions.drl | 30 - .../accumulateMultipleFunctionsConstraint.drl | 32 - .../drools/drl10/parser/accumulateReverse.drl | 26 - .../drl10/parser/accumulate_multi_pattern.drl | 25 - .../drl10/parser/accumulate_with_bindings.drl | 25 - .../parser/accumulate_with_nested_from.drl | 25 - .../drools/drl10/parser/almost_empty_rule.drl | 22 - .../org/drools/drl10/parser/and_or_rule.drl | 27 - .../org/drools/drl10/parser/autofocus.drl | 25 - .../org/drools/drl10/parser/basic_binding.drl | 27 - .../org/drools/drl10/parser/bindings.drl | 29 - .../drl10/parser/brackets_precedence.drl | 23 - .../org/drools/drl10/parser/collect.drl | 22 - .../drl10/parser/collect_with_nested_from.drl | 24 - .../org/drools/drl10/parser/comment.drl | 32 - .../org/drools/drl10/parser/complex.dsl | 5 - .../parser/declaration-in-consequence.drl | 48 - .../drl10/parser/declare_type_with_fields.drl | 35 - .../org/drools/drl10/parser/empty_rule.drl | 23 - .../org/drools/drl10/parser/enumeration.drl | 23 - .../drl10/parser/eol_funny_business.drl | 37 - .../drools/drl10/parser/escaped-string.drl | 23 - .../org/drools/drl10/parser/eval_multiple.drl | 26 - .../org/drools/drl10/parser/eval_parsing.drl | 26 - .../drools/drl10/parser/eval_with_newline.drl | 38 - .../parser/expander_multiple_constraints.dslr | 18 - .../expander_multiple_constraints_flush.dslr | 17 - .../drl10/parser/expander_spread_lines.dslr | 19 - .../drools/drl10/parser/extra_lhs_newline.drl | 27 - .../org/drools/drl10/parser/forall.drl | 23 - .../drools/drl10/parser/forallwithfrom.drl | 23 - .../org/drools/drl10/parser/from.drl | 31 - .../drools/drl10/parser/function_arrays.drl | 31 - .../org/drools/drl10/parser/functions.drl | 43 - .../org/drools/drl10/parser/globals.drl | 30 - .../drools/drl10/parser/in_operator_test.drl | 26 - .../drl10/parser/lhs_semicolon_delim.drl | 29 - .../parser/literal_bool_and_negative.drl | 27 - .../drl10/parser/multiple_constraints.dsl | 6 - .../drools/drl10/parser/multiple_rules.drl | 34 - .../parser/nested_conditional_elements.drl | 27 - .../org/drools/drl10/parser/no-loop.drl | 25 - .../drl10/parser/not_exist_with_brackets.drl | 26 - .../drl10/parser/not_with_constraint.drl | 31 - .../drl10/parser/notin_operator_test.drl | 26 - .../org/drools/drl10/parser/or_binding.drl | 27 - .../drl10/parser/or_binding_complex.drl | 27 - .../drl10/parser/or_binding_with_brackets.drl | 25 - .../org/drools/drl10/parser/or_ce.drl | 26 - .../org/drools/drl10/parser/or_nesting.drl | 27 - .../drl10/parser/package_attributes.drl | 40 - .../drl10/parser/pluggable_operators.drl | 28 - .../drl10/parser/qualified_classname.drl | 25 - .../drools/drl10/parser/query_and_rule.drl | 47 - .../drl10/parser/quoted_string_name_rule.drl | 21 - .../drools/drl10/parser/restrictions_test.drl | 26 - .../drools/drl10/parser/rule_attributes.drl | 33 - .../drools/drl10/parser/rule_attributes2.drl | 46 - .../drl10/parser/rule_attributes_alt.drl | 28 - .../drl10/parser/rule_calendars_attribute.drl | 26 - .../parser/rule_calendars_attribute2.drl | 26 - .../drl10/parser/rule_duration_expression.drl | 26 - .../drl10/parser/rule_enabled_expression.drl | 27 - .../drl10/parser/rule_names_number_prefix.drl | 27 - .../org/drools/drl10/parser/rule_not.drl | 24 - .../org/drools/drl10/parser/ruleflowgroup.drl | 25 - .../org/drools/drl10/parser/semicolon.drl | 43 - .../org/drools/drl10/parser/simple_query.drl | 25 - .../org/drools/drl10/parser/simple_rule.drl | 29 - .../drl10/parser/soundslike_operator.drl | 30 - .../drl10/parser/statement_ordering_1.drl | 45 - .../drl10/parser/ternary_expression.drl | 26 - .../test_CommentLineNumbersInConsequence.drl | 34 - .../test_ComplexChainedCallWithFrom.drl | 24 - .../drools/drl10/parser/test_EmptyPattern.drl | 26 - .../drools/drl10/parser/test_EndPosition.drl | 27 - .../drl10/parser/test_FunctionImport.drl | 29 - .../parser/test_SimpleAccessorArgWithFrom.drl | 27 - .../parser/test_SimpleAccessorWithFrom.drl | 27 - .../test_SimpleFunctionCallWithFrom.drl | 27 - .../parser/test_SimpleMethodCallWithFrom.drl | 27 - .../drools/drl10/parser/type_with_meta.drl | 48 - .../org/drools/drl10/parser/with_eval.drl | 26 - .../drools/drl10/parser/with_predicate.drl | 23 - .../org/drools/drl10/parser/with_retval.drl | 23 - drools-drl/drools-drl-parser/pom.xml | 45 - .../drools/drl10/parser/DRL6Expressions.g4 | 847 ---- .../org/drools/drl10/parser/DRLLexer.g4 | 161 - .../org/drools/drl10/parser/DRLParser.g4 | 495 --- .../org/drools/drl10/parser/JavaLexer.g4 | 245 -- .../org/drools/drl10/parser/JavaParser.g4 | 752 ---- .../org/drools/drl/parser/DRLFactory.java | 3 - .../org/drools/drl/parser/Drl6ExprParser.java | 90 - .../org/drools/drl/parser/DrlExprParser.java | 56 +- .../drl/parser/DrlExprParserFactory.java | 20 - .../java/org/drools/drl/parser/DrlParser.java | 35 +- .../drools/drl/parser/lang/DRL10Lexer.java | 46 - .../drools/drl10/parser/DRLErrorListener.java | 49 - .../drools/drl10/parser/DRLExpressions.java | 61 - .../drools/drl10/parser/DRLParserError.java | 75 - .../drl10/parser/DRLParserException.java | 30 - .../drools/drl10/parser/DRLParserHelper.java | 126 - .../drools/drl10/parser/DRLParserWrapper.java | 85 - .../drools/drl10/parser/DRLVisitorImpl.java | 845 ---- .../drools/drl10/parser/Developer_Notes.md | 38 - .../drools/drl10/parser/Drl10ExprParser.java | 87 - .../parser/DroolsParserExceptionFactory.java | 250 -- .../org/drools/drl10/parser/ParserHelper.java | 678 ---- .../drl10/parser/ParserStringUtils.java | 81 - drools-drl/pom.xml | 1 - .../mvel/compiler/lang/DRLExprParserTest.java | 3 +- .../mvel/compiler/lang/DescrDumperTest.java | 3 +- .../mvel/integrationtests/AlphaNodeTest.java | 2 - .../visitor/ExprConstraintDescrVisitor.java | 3 +- .../builder/conf/LanguageLevelOption.java | 2 +- pom.xml | 22 - 131 files changed, 63 insertions(+), 11957 deletions(-) delete mode 100644 drools-drl/drools-drl-parser-tests/pom.xml delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declare_type_with_fields.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/empty_rule.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/enumeration.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eol_funny_business.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/escaped-string.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_multiple.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_parsing.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_with_newline.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints.dslr delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints_flush.dslr delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_spread_lines.dslr delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/extra_lhs_newline.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forall.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl delete mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl delete mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl delete mode 100644 drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 delete mode 100644 drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 delete mode 100644 drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 delete mode 100644 drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 delete mode 100644 drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java diff --git a/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java b/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java index 48e3e4971f1..0c90262aa28 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java @@ -127,6 +127,7 @@ public KnowledgeBuilderRulesConfigurationImpl(CompositeConfiguration - - - - 4.0.0 - - org.drools - drools-drl - 999-SNAPSHOT - - - org.drools - drools-drl-parser-tests - - Drools :: DRL :: Parser :: Tests - - - org.drools.drl.parser.tests - - - - - - org.assertj - assertj-core - test - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - ch.qos.logback - logback-classic - test - - - - org.drools - drools-drl-parser - test - - - org.drools - drools-compiler - test - - - org.drools - drools-mvel - test - - - - diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java deleted file mode 100644 index 1f27a9c861e..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java +++ /dev/null @@ -1,271 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.drools.drl.ast.descr.AtomicExprDescr; -import org.drools.drl.ast.descr.BindingDescr; -import org.drools.drl.ast.descr.ConnectiveType; -import org.drools.drl.ast.descr.ConstraintConnectiveDescr; -import org.drools.drl.ast.descr.RelationalExprDescr; -import org.drools.drl.parser.DrlExprParser; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; -import org.kie.internal.builder.conf.LanguageLevelOption; - -/** - * DRLExprTreeTest - */ -public class DRLExprParserTest { - - DrlExprParser parser; - - @BeforeEach - public void setUp() throws Exception { - this.parser = new Drl10ExprParser(LanguageLevelOption.DRL6); - } - - @AfterEach - public void tearDown() throws Exception { - this.parser = null; - } - - @Test - public void testSimpleExpression() throws Exception { - String source = "a > b"; - ConstraintConnectiveDescr result = parser.parse( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); - - RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); - assertThat(expr.getOperator()).isEqualTo(">"); - - AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); - AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); - - assertThat(left.getExpression()).isEqualTo("a"); - assertThat(right.getExpression()).isEqualTo("b"); - } - - @Test - public void testAndConnective() throws Exception { - String source = "a > b && 10 != 20"; - ConstraintConnectiveDescr result = parser.parse( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); - - RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); - assertThat(expr.getOperator()).isEqualTo(">"); - AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); - AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); - assertThat(left.getExpression()).isEqualTo("a"); - assertThat(right.getExpression()).isEqualTo("b"); - - expr = (RelationalExprDescr) result.getDescrs().get( 1 ); - assertThat(expr.getOperator()).isEqualTo("!="); - left = (AtomicExprDescr) expr.getLeft(); - right = (AtomicExprDescr) expr.getRight(); - assertThat(left.getExpression()).isEqualTo("10"); - assertThat(right.getExpression()).isEqualTo("20"); - } - - @Test - public void testConnective2() throws Exception { - String source = "(a > b || 10 != 20) && someMethod(10) == 20"; - ConstraintConnectiveDescr result = parser.parse( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); - - ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get( 0 ); - assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); - assertThat(or.getDescrs().size()).isEqualTo(2); - - RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get( 0 ); - assertThat(expr.getOperator()).isEqualTo(">"); - AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); - AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); - assertThat(left.getExpression()).isEqualTo("a"); - assertThat(right.getExpression()).isEqualTo("b"); - - expr = (RelationalExprDescr) or.getDescrs().get( 1 ); - assertThat(expr.getOperator()).isEqualTo("!="); - left = (AtomicExprDescr) expr.getLeft(); - right = (AtomicExprDescr) expr.getRight(); - assertThat(left.getExpression()).isEqualTo("10"); - assertThat(right.getExpression()).isEqualTo("20"); - - expr = (RelationalExprDescr) result.getDescrs().get( 1 ); - assertThat(expr.getOperator()).isEqualTo("=="); - left = (AtomicExprDescr) expr.getLeft(); - right = (AtomicExprDescr) expr.getRight(); - assertThat(left.getExpression()).isEqualTo("someMethod(10)"); - assertThat(right.getExpression()).isEqualTo("20"); - - } - - @Test - public void testBinding() throws Exception { - String source = "$x : property"; - ConstraintConnectiveDescr result = parser.parse( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); - - BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); - assertThat(bind.getVariable()).isEqualTo("$x"); - assertThat(bind.getExpression()).isEqualTo("property"); - } - - @Test - public void testBindingConstraint() throws Exception { - String source = "$x : property > value"; - ConstraintConnectiveDescr result = parser.parse( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); - - RelationalExprDescr rel = (RelationalExprDescr) result.getDescrs().get( 0 ); - assertThat(rel.getOperator()).isEqualTo(">"); - - BindingDescr bind = (BindingDescr) rel.getLeft(); - assertThat(bind.getVariable()).isEqualTo("$x"); - assertThat(bind.getExpression()).isEqualTo("property"); - - AtomicExprDescr right = (AtomicExprDescr) rel.getRight(); - assertThat(right.getExpression()).isEqualTo("value"); - } - - @Test - public void testBindingWithRestrictions() throws Exception { - String source = "$x : property > value && < 20"; - ConstraintConnectiveDescr result = parser.parse( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); - - RelationalExprDescr rel = (RelationalExprDescr) result.getDescrs().get( 0 ); - assertThat(rel.getOperator()).isEqualTo(">"); - - BindingDescr bind = (BindingDescr) rel.getLeft(); - assertThat(bind.getVariable()).isEqualTo("$x"); - assertThat(bind.getExpression()).isEqualTo("property"); - - AtomicExprDescr right = (AtomicExprDescr) rel.getRight(); - assertThat(right.getExpression()).isEqualTo("value"); - - rel = (RelationalExprDescr) result.getDescrs().get( 1 ); - assertThat(rel.getOperator()).isEqualTo("<"); - - AtomicExprDescr left = (AtomicExprDescr) rel.getLeft(); - assertThat(left.getExpression()).isEqualTo("property"); - - right = (AtomicExprDescr) rel.getRight(); - assertThat(right.getExpression()).isEqualTo("20"); - } - - @Test - public void testDoubleBinding() throws Exception { - String source = "$x : x.m( 1, a ) && $y : y[z].foo"; - ConstraintConnectiveDescr result = parser.parse( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); - - BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); - assertThat(bind.getVariable()).isEqualTo("$x"); - assertThat(bind.getExpression()).isEqualTo("x.m( 1, a )"); - - bind = (BindingDescr) result.getDescrs().get( 1 ); - assertThat(bind.getVariable()).isEqualTo("$y"); - assertThat(bind.getExpression()).isEqualTo("y[z].foo"); - } - - @Test - public void testDeepBinding() throws Exception { - String source = "($a : a > $b : b[10].prop || 10 != 20) && $x : someMethod(10) == 20"; - ConstraintConnectiveDescr result = parser.parse( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); - - ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get( 0 ); - assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); - assertThat(or.getDescrs().size()).isEqualTo(2); - - RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get( 0 ); - assertThat(expr.getOperator()).isEqualTo(">"); - BindingDescr leftBind = (BindingDescr) expr.getLeft(); - BindingDescr rightBind = (BindingDescr) expr.getRight(); - assertThat(leftBind.getVariable()).isEqualTo("$a"); - assertThat(leftBind.getExpression()).isEqualTo("a"); - assertThat(rightBind.getVariable()).isEqualTo("$b"); - assertThat(rightBind.getExpression()).isEqualTo("b[10].prop"); - - expr = (RelationalExprDescr) or.getDescrs().get( 1 ); - assertThat(expr.getOperator()).isEqualTo("!="); - AtomicExprDescr leftExpr = (AtomicExprDescr) expr.getLeft(); - AtomicExprDescr rightExpr = (AtomicExprDescr) expr.getRight(); - assertThat(leftExpr.getExpression()).isEqualTo("10"); - assertThat(rightExpr.getExpression()).isEqualTo("20"); - - expr = (RelationalExprDescr) result.getDescrs().get( 1 ); - assertThat(expr.getOperator()).isEqualTo("=="); - leftBind = (BindingDescr) expr.getLeft(); - rightExpr = (AtomicExprDescr) expr.getRight(); - assertThat(leftBind.getVariable()).isEqualTo("$x"); - assertThat(leftBind.getExpression()).isEqualTo("someMethod(10)"); - assertThat(rightExpr.getExpression()).isEqualTo("20"); - - } - - @Test - @Timeout(10000L) - public void testNestedExpression() throws Exception { - // DROOLS-982 - String source = "(((((((((((((((((((((((((((((((((((((((((((((((((( a > b ))))))))))))))))))))))))))))))))))))))))))))))))))"; - ConstraintConnectiveDescr result = parser.parse( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); - - RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); - assertThat(expr.getOperator()).isEqualTo(">"); - - AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); - AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); - - assertThat(left.getExpression()).isEqualTo("a"); - assertThat(right.getExpression()).isEqualTo("b"); - } -} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java deleted file mode 100644 index 35c4638ebc1..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.drools.drl10.parser; - -import java.util.List; - -import org.drools.drl.ast.descr.AnnotationDescr; -import org.drools.drl.ast.descr.AttributeDescr; -import org.drools.drl.ast.descr.BaseDescr; -import org.drools.drl.ast.descr.ExprConstraintDescr; -import org.drools.drl.ast.descr.GlobalDescr; -import org.drools.drl.ast.descr.PackageDescr; -import org.drools.drl.ast.descr.PatternDescr; -import org.drools.drl.ast.descr.RuleDescr; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.drools.drl10.parser.DRLParserHelper.computeTokenIndex; -import static org.drools.drl10.parser.DRLParserHelper.createDrlParser; -import static org.drools.drl10.parser.DRLParserHelper.parse; - -class DRLParserTest { - - private static final String drl = - "package org.test;\n" + - "import org.test.model.Person;\n" + - "global String result;\n" + - "rule TestRule @Test(true) no-loop salience 15 when \n" + - " $p:Person( age >= 18 )\n" + - "then\n" + - " int a = 4;\n" + - " System.out.println($p.getName());\n" + - "end\n"; - - @Test - void parse_basicRule() { - PackageDescr packageDescr = parse(drl); - assertThat(packageDescr.getName()).isEqualTo("org.test"); - - assertThat(packageDescr.getImports().size()).isEqualTo(1); - assertThat(packageDescr.getImports().get(0).getTarget()).isEqualTo("org.test.model.Person"); - - assertThat(packageDescr.getGlobals().size()).isEqualTo(1); - GlobalDescr globalDescr = packageDescr.getGlobals().get(0); - assertThat(globalDescr.getType()).isEqualTo("String"); - assertThat(globalDescr.getIdentifier()).isEqualTo("result"); - - assertThat(packageDescr.getRules().size()).isEqualTo(1); - RuleDescr ruleDescr = packageDescr.getRules().get(0); - - AnnotationDescr annotationDescr = ruleDescr.getAnnotation("Test"); - assertThat(annotationDescr).isNotNull(); - assertThat(annotationDescr.getValue()).isEqualTo("true"); - - assertThat(ruleDescr.getAttributes().size()).isEqualTo(2); - assertThat(ruleDescr.getAttributes().get("no-loop")).isNotNull(); - AttributeDescr salience = ruleDescr.getAttributes().get("salience"); - assertThat(salience).isNotNull(); - assertThat(salience.getValue()).isEqualTo("15"); - - assertThat(ruleDescr.getName()).isEqualTo("TestRule"); - - assertThat(ruleDescr.getLhs().getDescrs().size()).isEqualTo(1); - PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); - assertThat(patternDescr.getIdentifier()).isEqualTo("$p"); - assertThat(patternDescr.getObjectType()).isEqualTo("Person"); - - List constraints = patternDescr.getConstraint().getDescrs(); - assertThat(constraints.size()).isEqualTo(1); - ExprConstraintDescr expr = (ExprConstraintDescr) constraints.get(0); - assertThat(expr.getExpression()).isEqualTo("age >= 18"); - - assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int a = 4; System.out.println($p.getName());"); - } - - @Test - void computeTokenIndex_basicRule() { - DRLParser parser = createDrlParser(drl); - parser.compilationUnit(); - - assertThat((int) computeTokenIndex(parser, 1, 0)).isEqualTo(0); - assertThat((int) computeTokenIndex(parser, 1, 1)).isEqualTo(0); - assertThat((int) computeTokenIndex(parser, 1, 7)).isEqualTo(0); - assertThat((int) computeTokenIndex(parser, 1, 8)).isEqualTo(1); - assertThat((int) computeTokenIndex(parser, 1, 9)).isEqualTo(2); - assertThat((int) computeTokenIndex(parser, 1, 9)).isEqualTo(2); - assertThat((int) computeTokenIndex(parser, 1, 12)).isEqualTo(3); - assertThat((int) computeTokenIndex(parser, 1, 13)).isEqualTo(4); - assertThat((int) computeTokenIndex(parser, 1, 17)).isEqualTo(5); - assertThat((int) computeTokenIndex(parser, 1, 18)).isEqualTo(6); - assertThat((int) computeTokenIndex(parser, 2, 0)).isEqualTo(6); - assertThat((int) computeTokenIndex(parser, 2, 1)).isEqualTo(7); - assertThat((int) computeTokenIndex(parser, 2, 6)).isEqualTo(7); - assertThat((int) computeTokenIndex(parser, 2, 7)).isEqualTo(8); - // Skip RHS token assertion as it is fluid part at the moment. - } -} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java deleted file mode 100644 index d98ec8ec895..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java +++ /dev/null @@ -1,368 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.drools.compiler.lang.DescrDumper; -import org.drools.compiler.lang.DumperContext; -import org.drools.drl.ast.descr.AtomicExprDescr; -import org.drools.drl.ast.descr.BindingDescr; -import org.drools.drl.ast.descr.ConstraintConnectiveDescr; -import org.drools.drl.parser.DrlExprParser; -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; - -public class DescrDumperTest { - - private DescrDumper dumper; - - @BeforeEach - public void setUp() throws Exception { - // configure operators - new SetEvaluatorsDefinition(); - new MatchesEvaluatorsDefinition(); - - dumper = new DescrDumper(); - } - - @Test - public void testDump() throws Exception { - String input = "price > 10 && < 20 || == $val || == 30"; - String expected = "( price > 10 && price < 20 || price == $val || price == 30 )"; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpMatches() throws Exception { - String input = "type.toString matches \"something\\swith\\tsingle escapes\""; - String expected = "type.toString ~= \"something\\swith\\tsingle escapes\""; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpMatches2() throws Exception { - String input = "type.toString matches 'something\\swith\\tsingle escapes'"; - String expected = "type.toString ~= \"something\\swith\\tsingle escapes\""; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpMatches3() throws Exception { - String input = "this[\"content\"] matches \"hello ;=\""; - String expected = "this[\"content\"] ~= \"hello ;=\""; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpContains() throws Exception { - String input = "list contains \"b\""; - String expected = "list contains \"b\""; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpContains2() throws Exception { - String input = "list not contains \"b\""; - String expected = "!( list contains \"b\" )"; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpExcludes() throws Exception { - String input = "list excludes \"b\""; - String expected = "!( list contains \"b\" )"; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpExcludes2() throws Exception { - String input = "list not excludes \"b\""; - String expected = "list contains \"b\""; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test @Disabled - public void testDumpWithDateAttr() throws Exception { - String input = "son.birthDate == \"01-jan-2000\""; - String expected = "son.birthDate == org.drools.util.DateUtils.parseDate( \"01-jan-2000\" )"; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpComplex() throws Exception { - String input = "a ( > 60 && < 70 ) || ( > 50 && < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\""; - String expected = "( ( a > 60 && a < 70 || a > 50 && a < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\" )"; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpBindings() throws Exception { - String input = "$x : property > value"; - String expected = "property > value"; - - ConstraintConnectiveDescr descr = parse( input ); - DumperContext ctx = new DumperContext(); - String result = dumper.dump( descr, - ctx ); - - assertThat(result).isEqualTo(expected); - assertThat(ctx.getBindings().size()).isEqualTo(1); - BindingDescr bind = ctx.getBindings().get( 0 ); - assertThat(bind.getVariable()).isEqualTo("$x"); - assertThat(bind.getExpression()).isEqualTo("property"); - } - - @Test - public void testDumpBindings2() throws Exception { - String input = "( $a : a > $b : b[10].prop || 10 != 20 ) && $x : someMethod(10) == 20"; - String expected = "( a > b[10].prop || 10 != 20 ) && someMethod(10) == 20"; - - ConstraintConnectiveDescr descr = parse( input ); - DumperContext ctx = new DumperContext(); - String result = dumper.dump( descr, - ctx ); - - assertThat(result).isEqualTo(expected); - assertThat(ctx.getBindings().size()).isEqualTo(3); - BindingDescr bind = ctx.getBindings().get( 0 ); - assertThat(bind.getVariable()).isEqualTo("$a"); - assertThat(bind.getExpression()).isEqualTo("a"); - bind = ctx.getBindings().get( 1 ); - assertThat(bind.getVariable()).isEqualTo("$b"); - assertThat(bind.getExpression()).isEqualTo("b[10].prop"); - bind = ctx.getBindings().get( 2 ); - assertThat(bind.getVariable()).isEqualTo("$x"); - assertThat(bind.getExpression()).isEqualTo("someMethod(10)"); - } - - @Test - public void testDumpBindings3() throws Exception { - String input = "( $a : a > $b : b[10].prop || 10 != 20 ) && $x : someMethod(10)"; - String expected = "( a > b[10].prop || 10 != 20 )"; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpBindings4() throws Exception { - String input = "( $a : a > $b : b[10].prop || $x : someMethod(10) ) && 10 != 20"; - String expected = "( a > b[10].prop ) && 10 != 20"; - - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); - - assertThat(result).isEqualTo(expected); - } - - @Test - public void testDumpBindingsWithRestriction() throws Exception { - String input = "$x : age > 10 && < 20 || > 30"; - String expected = "( age > 10 && age < 20 || age > 30 )"; - - ConstraintConnectiveDescr descr = parse( input ); - DumperContext ctx = new DumperContext(); - String result = dumper.dump( descr, - ctx ); - - assertThat(result).isEqualTo(expected); - assertThat(ctx.getBindings().size()).isEqualTo(1); - BindingDescr bind = ctx.getBindings().get( 0 ); - assertThat(bind.getVariable()).isEqualTo("$x"); - assertThat(bind.getExpression()).isEqualTo("age"); - } - - @Test - public void testDumpBindingsComplexOp() throws Exception { - String input = "$x : age in (10, 20, $someVal)"; - String expected = "( age == 10 || age == 20 || age == $someVal )"; - - ConstraintConnectiveDescr descr = parse( input ); - DumperContext ctx = new DumperContext(); - String result = dumper.dump( descr, - ctx ); - - assertThat(result).isEqualTo(expected); - assertThat(ctx.getBindings().size()).isEqualTo(1); - BindingDescr bind = ctx.getBindings().get( 0 ); - assertThat(bind.getVariable()).isEqualTo("$x"); - assertThat(bind.getExpression()).isEqualTo("age"); - } - - @Test - public void testDumpBindingsComplexOp2() throws Exception { - String input = "$x : age not in (10, 20, $someVal)"; - String expected = "age != 10 && age != 20 && age != $someVal"; - - ConstraintConnectiveDescr descr = parse( input ); - DumperContext ctx = new DumperContext(); - String result = dumper.dump( descr, - ctx ); - - assertThat(result).isEqualTo(expected); - assertThat(ctx.getBindings().size()).isEqualTo(1); - BindingDescr bind = ctx.getBindings().get( 0 ); - assertThat(bind.getVariable()).isEqualTo("$x"); - assertThat(bind.getExpression()).isEqualTo("age"); - } - - @Test - public void testProcessInlineCast() throws Exception { - String expr = "field1#Class.field2"; - String expectedInstanceof = "field1 instanceof Class"; - String expectedcasted = "((Class)field1).field2"; - AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); - ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); - ccd.addDescr( atomicExpr ); - String[] instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null); - assertThat(ccd.getDescrs().size()).isEqualTo(2); - assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedInstanceof); - assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedcasted); - - expr = "field1#Class1.field2#Class2.field3"; - String expectedInstanceof1 = "field1 instanceof Class1"; - String expectedInstanceof2 = "((Class1)field1).field2 instanceof Class2"; - expectedcasted = "((Class2)((Class1)field1).field2).field3"; - atomicExpr = new AtomicExprDescr(expr); - ccd = new ConstraintConnectiveDescr( ); - instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null); - assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedInstanceof1); - assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedInstanceof2); - assertThat(instanceofAndCastedExpr[1]).isEqualTo(expectedcasted); - assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedcasted); - } - - @Test - public void testProcessNullSafeDereferencing() throws Exception { - String expr = "field1!.field2"; - String expectedNullCheck = "field1 != null"; - String expectedExpr = "field1.field2"; - AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); - ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); - String[] nullCheckAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); - assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedNullCheck); - assertThat(nullCheckAndExpr[1]).isEqualTo(expectedExpr); - assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); - - expr = "field1!.field2!.field3"; - String expectedNullCheck1 = "field1 != null"; - String expectedNullCheck2 = "field1.field2 != null"; - expectedExpr = "field1.field2.field3"; - atomicExpr = new AtomicExprDescr(expr); - ccd = new ConstraintConnectiveDescr( ); - nullCheckAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); - assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedNullCheck1); - assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedNullCheck2); - assertThat(nullCheckAndExpr[1]).isEqualTo(expectedExpr); - assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); - } - - @Test - public void testProcessImplicitConstraints() throws Exception { - String expr = "field1#Class!.field2"; - String expectedConstraints = "field1 instanceof Class"; - String expectedExpr = "((Class)field1).field2"; - AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); - ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); - String[] constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); - assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints); - assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); - assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); - - expr = "field1!.field2#Class.field3"; - String expectedConstraints1 = "field1 != null"; - String expectedConstraints2 = "field1.field2 instanceof Class"; - expectedExpr = "((Class)field1.field2).field3"; - atomicExpr = new AtomicExprDescr(expr); - ccd = new ConstraintConnectiveDescr( ); - constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); - assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints1); - assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedConstraints2); - assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); - assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); - - expr = "field1#Class.field2!.field3"; - expectedConstraints1 = "field1 instanceof Class"; - expectedConstraints2 = "((Class)field1).field2 != null"; - expectedExpr = "((Class)field1).field2.field3"; - atomicExpr = new AtomicExprDescr(expr); - ccd = new ConstraintConnectiveDescr( ); - constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); - assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints1); - assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedConstraints2); - assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); - assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); - } - - public ConstraintConnectiveDescr parse( final String constraint ) { - DrlExprParser parser = new Drl10ExprParser(LanguageLevelOption.DRL6); - ConstraintConnectiveDescr result = parser.parse( constraint ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - return result; - } - -} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java deleted file mode 100644 index 6353be53ac7..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java +++ /dev/null @@ -1,3443 +0,0 @@ -package org.drools.drl10.parser; - -import java.io.BufferedReader; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.regex.Pattern; - -import org.drools.drl.ast.descr.AccumulateDescr; -import org.drools.drl.ast.descr.AccumulateImportDescr; -import org.drools.drl.ast.descr.AndDescr; -import org.drools.drl.ast.descr.AnnotationDescr; -import org.drools.drl.ast.descr.AttributeDescr; -import org.drools.drl.ast.descr.BaseDescr; -import org.drools.drl.ast.descr.BehaviorDescr; -import org.drools.drl.ast.descr.CollectDescr; -import org.drools.drl.ast.descr.EntryPointDeclarationDescr; -import org.drools.drl.ast.descr.EntryPointDescr; -import org.drools.drl.ast.descr.EvalDescr; -import org.drools.drl.ast.descr.ExistsDescr; -import org.drools.drl.ast.descr.ExprConstraintDescr; -import org.drools.drl.ast.descr.ForallDescr; -import org.drools.drl.ast.descr.FromDescr; -import org.drools.drl.ast.descr.FunctionDescr; -import org.drools.drl.ast.descr.GlobalDescr; -import org.drools.drl.ast.descr.ImportDescr; -import org.drools.drl.ast.descr.MVELExprDescr; -import org.drools.drl.ast.descr.NotDescr; -import org.drools.drl.ast.descr.OrDescr; -import org.drools.drl.ast.descr.PackageDescr; -import org.drools.drl.ast.descr.PatternDescr; -import org.drools.drl.ast.descr.QueryDescr; -import org.drools.drl.ast.descr.RuleDescr; -import org.drools.drl.ast.descr.TypeDeclarationDescr; -import org.drools.drl.ast.descr.TypeFieldDescr; -import org.drools.drl.ast.descr.WindowDeclarationDescr; -import org.drools.drl10.parser.DRLParserWrapper; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/* - * This test class is ported from org.drools.mvel.compiler.lang.RuleParserTest - */ -class MiscDRLParserTest { - - private DRLParserWrapper parser; - - @BeforeEach - public void setUp() { - parser = new DRLParserWrapper(); - } - - @AfterEach - public void tearDown() { - } - - private String readResource(final String filename) throws Exception { - Path path = Paths.get(getClass().getResource(filename).toURI()); - final StringBuilder sb = new StringBuilder(); - try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { - for (String line; (line = br.readLine()) != null; ) { - sb.append(line); - sb.append("\n"); - } - } catch (IOException e) { - e.printStackTrace(); - } - return sb.toString(); - } - - private RuleDescr parseAndGetFirstRuleDescr(String drl) { - PackageDescr pkg = parser.parse(drl); - assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); - assertThat(pkg.getRules()).isNotEmpty(); - return pkg.getRules().get(0); - } - - private RuleDescr parseAndGetFirstRuleDescrFromFile(String filename) throws Exception { - return parseAndGetFirstRuleDescr(readResource(filename)); - } - - private PackageDescr parseAndGetPackageDescrFromFile(String filename) throws Exception { - return parser.parse(readResource(filename)); - } - - private QueryDescr parseAndGetFirstQueryDescr(String drl) { - PackageDescr pkg = parser.parse(drl); - assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); - assertThat(pkg.getRules()).isNotEmpty(); - Optional optQuery = pkg.getRules().stream().filter(QueryDescr.class::isInstance).map(QueryDescr.class::cast).findFirst(); - assertThat(optQuery).isPresent(); - return optQuery.get(); - } - - private QueryDescr parseAndGetFirstQueryDescrFromFile(String filename) throws Exception { - return parseAndGetFirstQueryDescr(readResource(filename)); - } - - @Test - void parse_validPackage() { - final String source = "package foo.bar.baz"; - final PackageDescr pkg = parser.parse(source); - assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); - } - - @Test - void parse_packageWithErrorNode() { - final String source = "package 12 foo.bar.baz"; - final PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).isTrue(); - assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); - } - - @Test - void parse_packageWithAllErrorNode() { - final String source = "package 12 12312 231"; - final PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).isTrue(); - assertThat(pkg.getName()).isEmpty(); - } - - @Test - void parse_import() { - final String source = "package foo; import com.foo.Bar; import com.foo.Baz;"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertThat(pkg.getName()).isEqualTo("foo"); - assertThat(pkg.getImports()).hasSize(2); - ImportDescr impdescr = pkg.getImports().get(0); - assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); - assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); - - impdescr = pkg.getImports().get(1); - assertThat(impdescr.getTarget()).isEqualTo("com.foo.Baz"); - assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); - } - - @Test - void parse_functionImport() { - final String source = "package foo\n" + - "import function java.lang.Math.max\n" + - "import function java.lang.Math.min;\n" + - "import foo.bar.*\n" + - "import baz.Baz"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertThat(pkg.getName()).isEqualTo("foo"); - assertThat(pkg.getImports()).hasSize(2); - ImportDescr impdescr = pkg.getImports().get(0); - assertThat(impdescr.getTarget()).isEqualTo("foo.bar.*"); - assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); - - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); - - impdescr = pkg.getImports().get(1); - assertThat(impdescr.getTarget()).isEqualTo("baz.Baz"); - assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); - - assertThat(pkg.getFunctionImports()).hasSize(2); - impdescr = pkg.getFunctionImports().get(0); - assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.max"); - assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget())); - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length() - 1); - - impdescr = pkg.getFunctionImports().get(1); - assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.min"); - assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget())); - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length()); - } - - @Test - void parse_globalWithComplexType() { - final String source = "package foo.bar.baz\n" + - "import com.foo.Bar\n" + - "global java.util.List> aList;\n" + - "global Integer aNumber"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); - assertThat(pkg.getImports()).hasSize(1); - - ImportDescr impdescr = pkg.getImports().get(0); - assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); - assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); - - assertThat(pkg.getGlobals()).hasSize(2); - - GlobalDescr global = pkg.getGlobals().get(0); - assertThat(global.getType()).isEqualTo("java.util.List>"); - assertThat(global.getIdentifier()).isEqualTo("aList"); - assertThat(global.getStartCharacter()).isEqualTo(source.indexOf("global " + global.getType())); - assertThat(global.getEndCharacter()).isEqualTo(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + - ("global " + global.getType() + " " + global.getIdentifier()).length()); - - global = pkg.getGlobals().get(1); - assertThat(global.getType()).isEqualTo("Integer"); - assertThat(global.getIdentifier()).isEqualTo("aNumber"); - assertThat(global.getStartCharacter()).isEqualTo(source.indexOf("global " + global.getType())); - assertThat(global.getEndCharacter()).isEqualTo(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + - ("global " + global.getType() + " " + global.getIdentifier()).length() - 1); - } - - @Test - void parse_globalWithOrWithoutSemi() throws Exception { - String source = readResource("globals.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(pkg.getRules()).hasSize(1); - - final RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getLhs().getDescrs()).hasSize(1); - - assertThat(pkg.getImports()).hasSize(1); - assertThat(pkg.getGlobals()).hasSize(2); - - final GlobalDescr foo = pkg.getGlobals().get(0); - assertThat(foo.getType()).isEqualTo("java.lang.String"); - assertThat(foo.getIdentifier()).isEqualTo("foo"); - final GlobalDescr bar = pkg.getGlobals().get(1); - assertThat(bar.getType()).isEqualTo("java.lang.Integer"); - assertThat(bar.getIdentifier()).isEqualTo("bar"); - } - - @Test - void parse_functionImportWithNotExist() throws Exception { - String source = readResource("test_FunctionImport.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(pkg.getFunctionImports()).hasSize(2); - - assertThat(pkg.getFunctionImports().get(0).getTarget()).isEqualTo("abd.def.x"); - assertThat(pkg.getFunctionImports().get(0).getStartCharacter()).isNotSameAs(-1); - assertThat(pkg.getFunctionImports().get(0).getEndCharacter()).isNotSameAs(-1); - assertThat(pkg.getFunctionImports().get(1).getTarget()).isEqualTo("qed.wah.*"); - assertThat(pkg.getFunctionImports().get(1).getStartCharacter()).isNotSameAs(-1); - assertThat(pkg.getFunctionImports().get(1).getEndCharacter()).isNotSameAs(-1); - } - - @Test - void parse_fromComplexAccessor() { - String source = "rule \"Invalid customer id\" ruleflow-group \"validate\" lock-on-active true \n" + - " when \n" + - " o: Order( ) \n" + - " not( Customer( ) from customerService.getCustomer(o.getCustomerId()) ) \n" + - " then \n" + - " System.err.println(\"Invalid customer id found!\"); " + - "\n" + - " o.addError(\"Invalid customer id\"); \n" + - "end \n"; - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getName()).isEqualTo("Invalid customer id"); - - assertThat(rule.getLhs().getDescrs()).hasSize(2); - - NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(1); - PatternDescr customer = (PatternDescr) not.getDescrs().get(0); - - assertThat(customer.getObjectType()).isEqualTo("Customer"); - assertThat(((FromDescr) customer.getSource()).getDataSource().getText()).isEqualTo("customerService.getCustomer(o.getCustomerId())"); - } - - @Test - void parse_fromWithInlineList() { - String source = "rule XYZ \n" + - " when \n" + - " o: Order( ) \n" + - " not( Number( ) from [1, 2, 3] ) \n" + - " then \n" + - " System.err.println(\"Invalid customer id found!\"); \n" + - " o.addError(\"Invalid customer id\"); \n" + - "end \n"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getName()).isEqualTo("XYZ"); - - PatternDescr number = (PatternDescr) ((NotDescr) rule.getLhs().getDescrs().get(1)).getDescrs().get(0); - assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3]"); - } - - @Test - void parse_fromWithInlineListMethod() { - String source = "rule XYZ \n" + - " when \n" + - " o: Order( ) \n" + - " Number( ) from [1, 2, 3].sublist(1, 2) \n" + - " then \n" + - " System.err.println(\"Invalid customer id found!\"); \n" + - " o.addError(\"Invalid customer id\"); \n" + - "end \n"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getName()).isEqualTo("XYZ"); - - assertThat(parser.hasErrors()).isFalse(); - PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); - - assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3].sublist(1, 2)"); - } - - @Test - void parse_fromWithInlineListIndex() { - String source = "rule XYZ \n" + - " when \n" + - " o: Order( ) \n" + - " Number( ) from [1, 2, 3][1] \n" + - " then \n" + - " System.err.println(\"Invalid customer id found!\"); \n" + - " o.addError(\"Invalid customer id\"); \n" + - "end \n"; - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getName()).isEqualTo("XYZ"); - - assertThat(parser.hasErrors()).isFalse(); - PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); - assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3][1]"); - } - - @Test - void parse_ruleWithoutEnd() { - String source = "rule \"Invalid customer id\" \n" + - " when \n" + - " o: Order( ) \n" + - " then \n" + - " System.err.println(\"Invalid customer id found!\"); \n"; - parser.parse(source); - assertThat(parser.hasErrors()).isTrue(); - } - - @Test - void parse_orWithSpecialBind() { - String source = "rule \"A and (B or C or D)\" \n" + - " when \n" + - " pdo1 : ParametricDataObject( paramID == 101, stringValue == \"1000\" ) and \n" + - " pdo2 :(ParametricDataObject( paramID == 101, stringValue == \"1001\" ) or \n" + - " ParametricDataObject( paramID == 101, stringValue == \"1002\" ) or \n" + - " ParametricDataObject( paramID == 101, stringValue == \"1003\" )) \n" + - " then \n" + - " System.out.println( \"Rule: A and (B or C or D) Fired. pdo1: \" + pdo1 + \" pdo2: \"+ pdo2); \n" + - "end\n"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get(0); - AndDescr lhs = rule.getLhs(); - assertThat(lhs.getDescrs()).hasSize(2); - - PatternDescr pdo1 = (PatternDescr) lhs.getDescrs().get(0); - assertThat(pdo1.getIdentifier()).isEqualTo("pdo1"); - - OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(1); - assertThat(or.getDescrs()).hasSize(3); - for (BaseDescr pdo2 : or.getDescrs()) { - assertThat(((PatternDescr) pdo2).getIdentifier()).isEqualTo("pdo2"); - } - } - - @Test - void parse_compatibleRestriction() { - String source = "package com.sample rule test when Test( ( text == null || text2 matches \"\" ) ) then end"; - PackageDescr pkg = parser.parse(source); - - assertThat(pkg.getName()).isEqualTo("com.sample"); - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getName()).isEqualTo("test"); - ExprConstraintDescr expr = (ExprConstraintDescr) ((PatternDescr) rule.getLhs().getDescrs().get(0)).getDescrs().get(0); - assertThat(expr.getText()).isEqualTo("( text == null || text2 matches \"\" )"); - } - - @Test - void parse_simpleConstraint() { - String source = "package com.sample rule test when Cheese( type == 'stilton', price > 10 ) then end"; - PackageDescr pkg = parser.parse(source); - - assertThat(pkg.getName()).isEqualTo("com.sample"); - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getName()).isEqualTo("test"); - - assertThat(rule.getLhs().getDescrs()).hasSize(1); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); - - AndDescr constraint = (AndDescr) pattern.getConstraint(); - assertThat(constraint.getDescrs()).hasSize(2); - assertThat(constraint.getDescrs().get(0)).hasToString("type == \"stilton\""); - assertThat(constraint.getDescrs().get(1)).hasToString("price > 10"); - } - - @Test - void parse_stringEscapes() { - String source = "package com.sample rule test when Cheese( type matches \"\\..*\\\\.\" ) then end"; - PackageDescr pkg = parser.parse(source); - assertThat(pkg.getName()).isEqualTo("com.sample"); - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getName()).isEqualTo("test"); - - assertThat(rule.getLhs().getDescrs()).hasSize(1); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); - - AndDescr constraint = (AndDescr) pattern.getConstraint(); - assertThat(constraint.getDescrs()).hasSize(1); - assertThat(constraint.getDescrs().get(0)).hasToString("type matches \"\\..*\\\\.\""); - } - - @Test - void parse_dialectWithSingleQuotation() { - final String source = "dialect 'mvel'"; - PackageDescr pkg = parser.parse(source); - AttributeDescr attr = pkg.getAttributes().get(0); - assertThat(attr.getName()).isEqualTo("dialect"); - assertThat(attr.getValue()).isEqualTo("mvel"); - } - - @Test - void parse_dialectWithDoubleQuotation() { - final String source = "dialect \"mvel\""; - PackageDescr pkg = parser.parse(source); - AttributeDescr attr = pkg.getAttributes().get(0); - assertThat(attr.getName()).isEqualTo("dialect"); - assertThat(attr.getValue()).isEqualTo("mvel"); - } - - @Test - void parse_emptyRuleWithoutWhen() throws Exception { - String source = readResource("empty_rule.drl"); // without WHEN - parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isTrue(); - - // Note : RuleParserTest.testEmptyRule allows this DRL, but I think is doesn't make sense to pass this DRL - } - - @Test - void parse_keywordCollisions() throws Exception { - String source = readResource("eol_funny_business.drl"); // keywords everywhere - - // Note: eol_funny_business.drl is modified from the one under drools-test-coverage to be more realistic. - // e.g. "package" is not allowed in a package value in Java, so it doesn't make sense to test. (Right to raise a parser error) - - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(pkg.getRules()).hasSize(1); - } - - @Test - void parse_ternaryExpression() throws Exception { - String source = readResource("ternary_expression.drl"); - PackageDescr pkg = parser.parse(source); - - final RuleDescr rule = pkg.getRules().get(0); - assertThat(pkg.getRules()).hasSize(1); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if (speed > speedLimit ? true : false;) pullEmOver();"); - } - - @Test - void parse_functionWithArrays() throws Exception { - String source = readResource("function_arrays.drl"); - - // Note: function_arrays.drl is modified from the one under drools-test-coverage to be more realistic. - // new String[3] {"a","b","c"} is invalid in Java (Cannot define dimension expressions when an array initializer is provided) - // , so it doesn't make sense to test. (Right to raise a parser error) - - PackageDescr pkg = parser.parse(source); - - assertThat(pkg.getName()).isEqualTo("foo"); - assertThat(pkg.getRules()).hasSize(1); - - final RuleDescr rule = pkg.getRules().get(0); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("yourFunction(new String[] {\"a\",\"b\",\"c\"});"); - - final FunctionDescr func = pkg.getFunctions().get(0); - - assertThat(func.getReturnType()).isEqualTo("String[]"); - assertThat(func.getParameterNames().get(0)).isEqualTo("args[]"); - assertThat(func.getParameterTypes().get(0)).isEqualTo("String"); - } - - @Test - void parse_almostEmptyRule() throws Exception { - String source = readResource("almost_empty_rule.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertThat(pkg).isNotNull(); - - RuleDescr rule = pkg.getRules().get(0); - - assertThat(rule.getName()).isEqualTo("almost_empty"); - assertThat(rule.getLhs()).isNotNull(); - assertThat(((String) rule.getConsequence()).trim()).isEmpty(); - } - - @Test - void parse_quotedStringNameRule() throws Exception { - String source = readResource("quoted_string_name_rule.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("quoted string name"); - assertThat(rule.getLhs()).isNotNull(); - assertThat(((String) rule.getConsequence()).trim()).isEmpty(); - } - - @Test - void parse_noLoop() throws Exception { - String source = readResource("no-loop.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("rule1"); - final AttributeDescr att = rule.getAttributes().get("no-loop"); - assertThat(att.getValue()).isEqualTo("false"); - assertThat(att.getName()).isEqualTo("no-loop"); - } - - @Test - void parse_autofocus() throws Exception { - String source = readResource("autofocus.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("rule1"); - final AttributeDescr att = rule.getAttributes().get("auto-focus"); - assertThat(att.getValue()).isEqualTo("true"); - assertThat(att.getName()).isEqualTo("auto-focus"); - } - - @Test - void parse_ruleFlowGroup() throws Exception { - String source = readResource("ruleflowgroup.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("rule1"); - final AttributeDescr att = rule.getAttributes().get("ruleflow-group"); - assertThat(att.getValue()).isEqualTo("a group"); - assertThat(att.getName()).isEqualTo("ruleflow-group"); - } - - @Test - void parse_consequenceWithDeclaration() throws Exception { - String source = readResource("declaration-in-consequence.drl"); - PackageDescr pkg = parser.parse(source); - - // Note : Removed "i\i;" from the original declaration-in-consequence.drl under drools-test-coverage - // because it's not a valid java expression and doesn't make sense to test. (Right to raise a parser error) - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get(0); - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("myrule"); - - final String expected = "int i = 0; i = 1; i / 1; i == 1; i(i); i = 'i'; i.i.i; ii; i=\"i\"; ++i;" + - "i++; --i; i--; i += i; i -= i; i *= i; i /= i;" + - "int i = 5;" + "for(int j; j 0).isTrue(); - assertThat(((String) rule.getConsequence()).indexOf("--") > 0).isTrue(); - assertThat(((String) rule.getConsequence()).indexOf("+=") > 0).isTrue(); - assertThat(((String) rule.getConsequence()).indexOf("==") > 0).isTrue(); - assertThat(((String) rule.getConsequence()).indexOf("i++") > 0).isTrue(); - // note, need to assert that "i++" is preserved as is, no extra spaces. - } - - @Test - void parse_or() { - final String text = "rule X when Person(age < 42, location==\"atlanta\") \nor\nPerson(name==\"bob\") then end"; - PackageDescr pkg = parser.parse(text); - RuleDescr rule = pkg.getRules().get(0); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(rule).isNotNull(); - - AndDescr lhs = rule.getLhs(); - assertThat(lhs.getDescrs()).hasSize(1); - assertThat(((OrDescr) lhs.getDescrs().get(0)).getDescrs()).hasSize(2); - } - - @Test - void parse_lhsWithStringQuotes() { - final String text = "rule X when Person( location==\"atlanta\\\"\") then end\n"; - PackageDescr pkg = parser.parse(text); - RuleDescr rule = pkg.getRules().get(0); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(rule).isNotNull(); - - AndDescr lhs = rule.getLhs(); - ExprConstraintDescr constr = (ExprConstraintDescr) ((PatternDescr) lhs.getDescrs().get(0)).getDescrs().get(0); - - assertThat(constr.getText()).isEqualToIgnoringWhitespace("location==\"atlanta\\\"\""); - } - - @Test - void parse_lhsWithStringQuotesEscapeChars() { - final String text = "rule X when Cheese( $x: type, type == \"s\\tti\\\"lto\\nn\" ) then end\n"; - PackageDescr pkg = parser.parse(text); - RuleDescr rule = pkg.getRules().get(0); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(rule).isNotNull(); - - AndDescr lhs = rule.getLhs(); - ExprConstraintDescr constr = (ExprConstraintDescr) ((PatternDescr) lhs.getDescrs().get(0)).getDescrs().get(1); - - assertThat(constr.getText()).isEqualToIgnoringWhitespace("type == \"s\\tti\\\"lto\\nn\""); - } - - @Test - void parse_literalBoolAndNegativeNumbersRule() throws Exception { - RuleDescr rule = parseAndGetFirstRuleDescrFromFile("literal_bool_and_negative.drl"); - - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat(rule.getLhs()).isNotNull(); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("cons();"); - - final AndDescr lhs = rule.getLhs(); - assertThat(lhs.getDescrs()).hasSize(3); - - PatternDescr pattern = (PatternDescr) lhs.getDescrs().get(0); - assertThat(pattern.getConstraint().getDescrs()).hasSize(1); - AndDescr fieldAnd = (AndDescr) pattern.getConstraint(); - ExprConstraintDescr fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); - assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == false"); - - pattern = (PatternDescr) lhs.getDescrs().get(1); - assertThat(pattern.getConstraint().getDescrs()).hasSize(1); - - fieldAnd = (AndDescr) pattern.getConstraint(); - fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); - - assertThat(fld.getText()).isEqualToIgnoringWhitespace("boo > -42"); - - pattern = (PatternDescr) lhs.getDescrs().get(2); - assertThat(pattern.getConstraint().getDescrs()).hasSize(1); - - fieldAnd = (AndDescr) pattern.getConstraint(); - fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); - - assertThat(fld.getText()).isEqualToIgnoringWhitespace("boo > -42.42"); - } - - @Test - void parse_emptyPattern() throws Exception { - String source = readResource("test_EmptyPattern.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(pkg.getRules()).hasSize(1); - final RuleDescr ruleDescr = pkg.getRules().get(0); - assertThat(ruleDescr.getName()).isEqualTo("simple rule"); - assertThat(ruleDescr.getLhs()).isNotNull(); - assertThat(ruleDescr.getLhs().getDescrs()).hasSize(1); - final PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); - assertThat(patternDescr.getConstraint().getDescrs()).isEmpty(); // this - assertThat(patternDescr.getObjectType()).isEqualTo("Cheese"); - } - - @Test - void parse_simpleMethodCallWithFrom() throws Exception { - RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleMethodCallWithFrom.drl"); - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); - final FromDescr from = (FromDescr) pattern.getSource(); - final MVELExprDescr method = (MVELExprDescr) from.getDataSource(); - - assertThat(method.getExpression()).isEqualToIgnoringWhitespace("something.doIt( foo,bar,42,\"hello\",[ a : \"b\", \"something\" : 42, \"a\" : foo, x : [x:y]],\"end\", [a, \"b\", 42] )"); - } - - @Test - void parse_simpleFunctionCallWithFrom() throws Exception { - RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleFunctionCallWithFrom.drl"); - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); - final FromDescr from = (FromDescr) pattern.getSource(); - final MVELExprDescr func = (MVELExprDescr) from.getDataSource(); - - assertThat(func.getExpression()).isEqualToIgnoringWhitespace("doIt( foo,bar,42,\"hello\",[ a : \"b\", \"something\" : 42, \"a\" : foo, x : [x:y]],\"end\", [a, \"b\", 42] )"); - } - - @Test - void parse_simpleAccessorWithFrom() throws Exception { - RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleAccessorWithFrom.drl"); - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final FromDescr from = (FromDescr) pattern.getSource(); - final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); - - assertThat(accessor.getExpression()).isEqualTo("something.doIt"); - } - - @Test - void parse_simpleAccessorAndArgWithFrom() throws Exception { - RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleAccessorArgWithFrom.drl"); - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final FromDescr from = (FromDescr) pattern.getSource(); - final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); - - assertThat(accessor.getExpression()).isEqualTo("something.doIt[\"key\"]"); - } - - @Test - void parse_complexChainedAccessor() throws Exception { - RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_ComplexChainedCallWithFrom.drl"); - - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final FromDescr from = (FromDescr) pattern.getSource(); - final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); - - assertThat(accessor.getExpression()).isEqualToIgnoringWhitespace("doIt1( foo,bar,42,\"hello\",[ a : \"b\"], [a, \"b\", 42] ).doIt2(bar, [a, \"b\", 42]).field[\"key\"]"); - } - - @Test - void parse_from() throws Exception { - RuleDescr rule = parseAndGetFirstRuleDescrFromFile("from.drl"); - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("using_from"); - - assertThat(rule.getLhs().getDescrs()).hasSize(9); - } - - @Test - void parse_simpleRuleWithBindings() throws Exception { - RuleDescr rule = parseAndGetFirstRuleDescrFromFile("simple_rule.drl"); - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("simple_rule"); - - assertThat(rule.getConsequenceLine()).isEqualTo(22); - assertThat(rule.getConsequencePattern()).isEqualTo(2); - - final AndDescr lhs = rule.getLhs(); - - assertThat(lhs).isNotNull(); - - assertThat(lhs.getDescrs()).hasSize(3); - - // Check first pattern - final PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); - assertThat(first.getIdentifier()).isEqualTo("foo3"); - assertThat(first.getObjectType()).isEqualTo("Bar"); - - assertThat(first.getConstraint().getDescrs()).hasSize(1); - - AndDescr fieldAnd = (AndDescr) first.getConstraint(); - ExprConstraintDescr constraint = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); - assertThat(constraint).isNotNull(); - - assertThat(constraint.getExpression()).isEqualToIgnoringWhitespace("a==3"); - - // Check second pattern - final PatternDescr second = (PatternDescr) lhs.getDescrs().get(1); - assertThat(second.getIdentifier()).isEqualTo("foo4"); - assertThat(second.getObjectType()).isEqualTo("Bar"); - - // no constraints, only a binding - fieldAnd = (AndDescr) second.getConstraint(); - assertThat(fieldAnd.getDescrs()).hasSize(1); - - final ExprConstraintDescr binding = (ExprConstraintDescr) second.getConstraint().getDescrs().get(0); - assertThat(binding.getExpression()).isEqualToIgnoringWhitespace("a4:a==4"); - - // Check third pattern - final PatternDescr third = (PatternDescr) lhs.getDescrs().get(2); - assertThat(third.getIdentifier()).isNull(); - assertThat(third.getObjectType()).isEqualTo("Baz"); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if ( a == b ) { " + " assert( foo3 );" + "} else {" + " retract( foo4 );" + "}" + " System.out.println( a4 );"); - } - - @Test - void parse_multipleRestrictionsConstraint() throws Exception { - RuleDescr rule = parseAndGetFirstRuleDescrFromFile("restrictions_test.drl"); - assertThat(rule).isNotNull(); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("consequence();"); - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat(rule.getLhs().getDescrs()).hasSize(2); - - // The first pattern, with 2 restrictions on a single field (plus a - // connective) - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat( pattern.getConstraint().getDescrs()).hasSize(1); - - AndDescr and = (AndDescr) pattern.getConstraint(); - ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); - assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); - - // the second col, with 2 fields, the first with 2 restrictions, the - // second field with one - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); - assertThat(pattern.getConstraint().getDescrs()).hasSize(2); - - and = (AndDescr) pattern.getConstraint(); - fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); - assertThat(fld.getExpression()).isEqualToIgnoringWhitespace( "type == \"sedan\" || == \"wagon\""); - - // now the second field - fld = (ExprConstraintDescr) and.getDescrs().get( 1 ); - assertThat(fld.getExpression()).isEqualToIgnoringWhitespace( "age < 3"); - } - -//------------------------------------------------------------------------- -// DROOLS-7271 : ported from RuleParserTest -// Failing tests are annotated with @Disabled. We can fix issues one by one -//------------------------------------------------------------------------- - - @Disabled("Priority : Mid | implement Descr lineNumber") - @Test - public void parse_LineNumberInAST() throws Exception { - // also see testSimpleExpander to see how this works with an expander - // (should be the same). - - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "simple_rule.drl" ); - - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("simple_rule"); - - assertThat(rule.getConsequenceLine()).isEqualTo(22); - assertThat(rule.getConsequencePattern()).isEqualTo(2); - - final AndDescr lhs = rule.getLhs(); - - assertThat(lhs).isNotNull(); - - assertThat(lhs.getDescrs().size()).isEqualTo(3); - - // Check first pattern - final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); - assertThat(first.getIdentifier()).isEqualTo("foo3"); - assertThat(first.getObjectType()).isEqualTo("Bar"); - assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); - - // Check second pattern - final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); - assertThat(second.getIdentifier()).isEqualTo("foo4"); - assertThat(second.getObjectType()).isEqualTo("Bar"); - - final PatternDescr third = (PatternDescr) lhs.getDescrs().get( 2 ); - assertThat(third.getObjectType()).isEqualTo("Baz"); - - assertThat(first.getLine()).isEqualTo(19); - assertThat(second.getLine()).isEqualTo(20); - assertThat(third.getLine()).isEqualTo(21); - } - - @Test - public void parse_LineNumberIncludingCommentsInRHS() throws Exception { - PackageDescr pkg = parseAndGetPackageDescrFromFile( - "test_CommentLineNumbersInConsequence.drl" ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - final String rhs = (String) ((RuleDescr) pkg.getRules().get( 0 )).getConsequence(); - String expected = "\\s*//woot$\\s*first;$\\s*$\\s*//$\\s*$\\s*/\\* lala$\\s*$\\s*\\*/$\\s*second;$\\s*"; - assertThat(Pattern.compile(expected, - Pattern.DOTALL | Pattern.MULTILINE).matcher(rhs).matches()).isTrue(); - } - - @Test - public void parse_LhsSemicolonDelim() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "lhs_semicolon_delim.drl" ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("simple_rule"); - - final AndDescr lhs = rule.getLhs(); - - assertThat(lhs).isNotNull(); - - assertThat(lhs.getDescrs().size()).isEqualTo(3); - - // System.err.println( lhs.getDescrs() ); - - // Check first pattern - final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); - assertThat(first.getIdentifier()).isEqualTo("foo3"); - assertThat(first.getObjectType()).isEqualTo("Bar"); - - assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); - - // LiteralDescr constraint = (LiteralDescr) first.getDescrs().get( 0 ); - AndDescr and = (AndDescr) first.getConstraint(); - ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); - assertThat(fld).isNotNull(); - - assertThat(fld.getExpression()).isEqualTo("a==3"); - - // Check second pattern - final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); - assertThat(second.getIdentifier()).isEqualTo("foo4"); - assertThat(second.getObjectType()).isEqualTo("Bar"); - - assertThat(second.getDescrs().size()).isEqualTo(1); - - final ExprConstraintDescr fieldBindingDescr = (ExprConstraintDescr) second.getDescrs().get( 0 ); - assertThat(fieldBindingDescr.getExpression()).isEqualTo("a4:a==4"); - - // Check third pattern - final PatternDescr third = (PatternDescr) lhs.getDescrs().get( 2 ); - assertThat(third.getIdentifier()).isNull(); - assertThat(third.getObjectType()).isEqualTo("Baz"); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if ( a == b ) { " + " assert( foo3 );" + "} else {" + " retract( foo4 );" + "}" + " System.out.println( a4 );"); - } - - @Test - public void parse_NotNode() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_not.drl" ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(rule).isNotNull(); - assertThat(rule.getName()).isEqualTo("simple_rule"); - - final AndDescr lhs = rule.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); - final NotDescr not = (NotDescr) lhs.getDescrs().get( 0 ); - assertThat(not.getDescrs().size()).isEqualTo(1); - final PatternDescr pattern = (PatternDescr) not.getDescrs().get( 0 ); - - assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); - - final AndDescr and = (AndDescr) pattern.getConstraint(); - final ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); - - assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); - } - - @Test - public void parse_NotExistWithBrackets() throws Exception { - - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "not_exist_with_brackets.drl" ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - - assertThat(rule).isNotNull(); - assertThat(rule.getName()).isEqualTo("simple_rule"); - - final AndDescr lhs = rule.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(2); - final NotDescr not = (NotDescr) lhs.getDescrs().get( 0 ); - assertThat(not.getDescrs().size()).isEqualTo(1); - final PatternDescr pattern = (PatternDescr) not.getDescrs().get( 0 ); - - assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - - final ExistsDescr ex = (ExistsDescr) lhs.getDescrs().get(1 ); - assertThat(ex.getDescrs().size()).isEqualTo(1); - final PatternDescr exPattern = (PatternDescr) ex.getDescrs().get( 0 ); - assertThat(exPattern.getObjectType()).isEqualTo("Foo"); - } - - @Test - public void parse_SimpleQuery() throws Exception { - final QueryDescr query = parseAndGetFirstQueryDescrFromFile( - "simple_query.drl" ); - - assertThat(query).isNotNull(); - - assertThat(query.getName()).isEqualTo("simple_query"); - - final AndDescr lhs = query.getLhs(); - - assertThat(lhs).isNotNull(); - - assertThat(lhs.getDescrs().size()).isEqualTo(3); - - // Check first pattern - final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); - assertThat(first.getIdentifier()).isEqualTo("foo3"); - assertThat(first.getObjectType()).isEqualTo("Bar"); - - assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); - - AndDescr and = (AndDescr) first.getConstraint(); - ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); - assertThat(fld).isNotNull(); - - assertThat(fld.getExpression()).isEqualTo("a==3"); - - // Check second pattern - final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); - assertThat(second.getIdentifier()).isEqualTo("foo4"); - assertThat(second.getObjectType()).isEqualTo("Bar"); - - assertThat(second.getDescrs().size()).isEqualTo(1); - // check it has field bindings. - final ExprConstraintDescr bindingDescr = (ExprConstraintDescr) second.getDescrs().get( 0 ); - assertThat(bindingDescr.getExpression()).isEqualTo("a4:a==4"); - } - - @Test - public void parse_QueryRuleMixed() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "query_and_rule.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(4); // as queries are rules - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getName()).isEqualTo("bar"); - - QueryDescr query = (QueryDescr) pkg.getRules().get( 1 ); - assertThat(query.getName()).isEqualTo("simple_query"); - - rule = (RuleDescr) pkg.getRules().get( 2 ); - assertThat(rule.getName()).isEqualTo("bar2"); - - query = (QueryDescr) pkg.getRules().get( 3 ); - assertThat(query.getName()).isEqualTo("simple_query2"); - } - - @Test - public void parse_MultipleRules() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "multiple_rules.drl" ); - - final List rules = pkg.getRules(); - - assertThat(rules.size()).isEqualTo(2); - - final RuleDescr rule0 = rules.get( 0 ); - assertThat(rule0.getName()).isEqualTo("Like Stilton"); - - final RuleDescr rule1 = rules.get( 1 ); - assertThat(rule1.getName()).isEqualTo("Like Cheddar"); - - // checkout the first rule - AndDescr lhs = rule1.getLhs(); - assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); - assertThat((String) rule0.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"I like \" + t);"); - - // Check first pattern - PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); - assertThat(first.getObjectType()).isEqualTo("Cheese"); - - // checkout the second rule - lhs = rule1.getLhs(); - assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); - assertThat((String) rule1.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"I like \" + t);"); - - // Check first pattern - first = (PatternDescr) lhs.getDescrs().get( 0 ); - assertThat(first.getObjectType()).isEqualTo("Cheese"); - } - - @Disabled("Priority : low | Not yet support DSL") - @Test - public void parse_ExpanderLineSpread() throws Exception { -// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); -// final PackageDescr pkg = parser.parse( this.getReader( "expander_spread_lines.dslr" ), -// this.getReader( "complex.dsl" ) ); -// -// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); -// -// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); -// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); -// -// final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); -// assertThat(or.getDescrs().size()).isEqualTo(2); -// assertThat( (String) rule.getConsequence() ).isNotNull(); - - } - - @Disabled("Priority : low | Not yet support DSL") - @Test - public void parse_ExpanderMultipleConstraints() throws Exception { -// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); -// final PackageDescr pkg = parser.parse( this.getReader( "expander_multiple_constraints.dslr" ), -// this.getReader( "multiple_constraints.dsl" ) ); -// -// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); -// -// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); -// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); -// -// PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); -// assertThat(pattern.getObjectType()).isEqualTo("Person"); -// -// assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); -// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); -// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); -// -// pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); -// assertThat(pattern.getObjectType()).isEqualTo("Bar"); -// -// assertThat( (String) rule.getConsequence() ).isNotNull(); - - } - - @Disabled("Priority : low | Not yet support DSL") - @Test - public void parse_ExpanderMultipleConstraintsFlush() throws Exception { -// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); -// // this is similar to the other test, but it requires a flush to add the -// // constraints -// final PackageDescr pkg = parser.parse( this.getReader( "expander_multiple_constraints_flush.dslr" ), -// this.getReader( "multiple_constraints.dsl" ) ); -// -// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); -// -// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); -// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); -// -// final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); -// assertThat(pattern.getObjectType()).isEqualTo("Person"); -// -// assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); -// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); -// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); -// -// assertThat( (String) rule.getConsequence() ).isNotNull(); - - } - - @Test - public void parse_BasicBinding() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "basic_binding.drl" ); - - final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get( 0 ); - - final AndDescr lhs = ruleDescr.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); - final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get( 0 ); - assertThat(cheese.getObjectType()).isEqualTo("Cheese"); - assertThat(cheese.getConstraint().getDescrs().size()).isEqualTo(1); - final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get( 0 ); - assertThat(fieldBinding.getExpression()).isEqualToIgnoringWhitespace("$type:type"); - } - - @Test - public void parse_BoundVariables() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "bindings.drl" ); - - final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get( 0 ); - - final AndDescr lhs = ruleDescr.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(2); - final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get( 0 ); - assertThat(cheese.getObjectType()).isEqualTo("Cheese"); - assertThat(cheese.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get( 0 ); - assertThat(fieldBinding.getExpression()).isEqualTo("$type : type == \"stilton\""); - - final PatternDescr person = (PatternDescr) lhs.getDescrs().get( 1 ); - assertThat(person.getDescrs().size()).isEqualTo(2); - fieldBinding = (ExprConstraintDescr) person.getDescrs().get( 0 ); - assertThat(fieldBinding.getExpression()).isEqualTo("$name : name == \"bob\""); - - ExprConstraintDescr fld = (ExprConstraintDescr) person.getDescrs().get( 1 ); - assertThat(fld.getExpression()).isEqualTo("likes == $type"); - } - - @Test - public void parse_OrNesting() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "or_nesting.drl" ); - - assertThat(pkg).isNotNull(); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getName()).isEqualTo("simple_rule"); - - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(or.getDescrs().size()).isEqualTo(2); - - final PatternDescr first = (PatternDescr) or.getDescrs().get( 0 ); - assertThat(first.getObjectType()).isEqualTo("Person"); - - final AndDescr and = (AndDescr) or.getDescrs().get( 1 ); - assertThat(and.getDescrs().size()).isEqualTo(2); - - final PatternDescr left = (PatternDescr) and.getDescrs().get( 0 ); - assertThat(left.getObjectType()).isEqualTo("Person"); - - final PatternDescr right = (PatternDescr) and.getDescrs().get( 1 ); - assertThat(right.getObjectType()).isEqualTo("Cheese"); - } - - /** Test that explicit "&&", "||" works as expected */ - @Test - public void parse_AndOrRules() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "and_or_rule.drl" ); - - assertThat(pkg).isNotNull(); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getName()).isEqualTo("simple_rule"); - - // we will have 3 children under the main And node - final AndDescr and = rule.getLhs(); - assertThat(and.getDescrs().size()).isEqualTo(3); - - PatternDescr left = (PatternDescr) and.getDescrs().get( 0 ); - PatternDescr right = (PatternDescr) and.getDescrs().get( 1 ); - assertThat(left.getObjectType()).isEqualTo("Person"); - assertThat(right.getObjectType()).isEqualTo("Cheese"); - - assertThat(left.getConstraint().getDescrs().size()).isEqualTo(1); - - ExprConstraintDescr fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get( 0 ); - - assertThat(fld.getExpression()).isEqualTo("name == \"mark\""); - - assertThat(right.getConstraint().getDescrs().size()).isEqualTo(1); - - fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get( 0 ); - - assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); - - // now the "||" part - final OrDescr or = (OrDescr) and.getDescrs().get( 2 ); - assertThat(or.getDescrs().size()).isEqualTo(2); - left = (PatternDescr) or.getDescrs().get( 0 ); - right = (PatternDescr) or.getDescrs().get( 1 ); - assertThat(left.getObjectType()).isEqualTo("Person"); - assertThat(right.getObjectType()).isEqualTo("Cheese"); - assertThat(left.getConstraint().getDescrs().size()).isEqualTo(1); - - fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get( 0 ); - - assertThat(fld.getExpression()).isEqualTo("name == \"mark\""); - - assertThat(right.getConstraint().getDescrs().size()).isEqualTo(1); - - fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get( 0 ); - - assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" );"); - } - - /** test basic foo : Fact() || Fact() stuff */ - @Test - public void parse_OrWithBinding() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "or_binding.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); - - final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(or.getDescrs().size()).isEqualTo(2); - - final PatternDescr leftPattern = (PatternDescr) or.getDescrs().get( 0 ); - assertThat(leftPattern.getObjectType()).isEqualTo("Person"); - assertThat(leftPattern.getIdentifier()).isEqualTo("foo"); - - final PatternDescr rightPattern = (PatternDescr) or.getDescrs().get( 1 ); - assertThat(rightPattern.getObjectType()).isEqualTo("Person"); - assertThat(rightPattern.getIdentifier()).isEqualTo("foo"); - - final PatternDescr cheeseDescr = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(cheeseDescr.getObjectType()).isEqualTo("Cheese"); - assertThat(cheeseDescr.getIdentifier()).isEqualTo(null); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); - } - - /** test basic foo : Fact() || Fact() stuff binding to an "or" */ - @Test - public void parse_OrBindingComplex() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "or_binding_complex.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(or.getDescrs().size()).isEqualTo(2); - - // first fact - final PatternDescr firstFact = (PatternDescr) or.getDescrs().get( 0 ); - assertThat(firstFact.getObjectType()).isEqualTo("Person"); - assertThat(firstFact.getIdentifier()).isEqualTo("foo"); - - // second "option" - final PatternDescr secondFact = (PatternDescr) or.getDescrs().get( 1 ); - assertThat(secondFact.getObjectType()).isEqualTo("Person"); - assertThat(secondFact.getConstraint().getDescrs().size()).isEqualTo(1); - assertThat(secondFact.getIdentifier()).isEqualTo("foo"); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); - } - - @Test - public void parse_OrBindingWithBrackets() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "or_binding_with_brackets.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(or.getDescrs().size()).isEqualTo(2); - - // first fact - final PatternDescr firstFact = (PatternDescr) or.getDescrs().get( 0 ); - assertThat(firstFact.getObjectType()).isEqualTo("Person"); - assertThat(firstFact.getIdentifier()).isEqualTo("foo"); - - // second "option" - final PatternDescr secondFact = (PatternDescr) or.getDescrs().get( 0 ); - assertThat(secondFact.getObjectType()).isEqualTo("Person"); - assertThat(secondFact.getIdentifier()).isEqualTo("foo"); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); - } - - @Test - void parenthesesOrAndOr() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "brackets_precedence.drl" ); - - assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - - final AndDescr rootAnd = (AndDescr) rule.getLhs(); - - assertThat(rootAnd.getDescrs()).hasSize(2); - - final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get( 0 ); - - assertThat(leftOr.getDescrs()).hasSize(2); - final NotDescr not = (NotDescr) leftOr.getDescrs().get( 0 ); - final PatternDescr foo1 = (PatternDescr) not.getDescrs().get( 0 ); - assertThat(foo1.getObjectType()).isEqualTo("Foo"); - final PatternDescr foo2 = (PatternDescr) leftOr.getDescrs().get( 1 ); - assertThat(foo2.getObjectType()).isEqualTo("Foo"); - - final OrDescr rightOr = (OrDescr) rootAnd.getDescrs().get( 1 ); - - assertThat(rightOr.getDescrs()).hasSize(2); - final PatternDescr shoes = (PatternDescr) rightOr.getDescrs().get( 0 ); - assertThat(shoes.getObjectType()).isEqualTo("Shoes"); - final PatternDescr butt = (PatternDescr) rightOr.getDescrs().get( 1 ); - assertThat(butt.getObjectType()).isEqualTo("Butt"); - } - - @Test - void parenthesesAndOrOr() { - final String drl = "rule and_or_or\n" + - " when\n" + - " (Foo(x == 1) and Bar(x == 2)) or (Foo(x == 3) or Bar(x == 4))\n" + - " then\n" + - "end"; - PackageDescr pkg = parser.parse(drl); - - assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - final AndDescr rootAnd = (AndDescr) rule.getLhs(); - assertThat(rootAnd.getDescrs()).hasSize(1); - - final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); - assertThat(topOr.getDescrs()).hasSize(2); - - final AndDescr leftAnd = (AndDescr) topOr.getDescrs().get(0); - assertThat(leftAnd.getDescrs()).hasSize(2); - final PatternDescr foo1 = (PatternDescr) leftAnd.getDescrs().get(0); - assertThat(foo1.getObjectType()).isEqualTo("Foo"); - final PatternDescr bar1 = (PatternDescr) leftAnd.getDescrs().get(1); - assertThat(bar1.getObjectType()).isEqualTo("Bar"); - - final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); - assertThat(rightOr.getDescrs()).hasSize(2); - final PatternDescr foo2 = (PatternDescr) rightOr.getDescrs().get(0); - assertThat(foo2.getObjectType()).isEqualTo("Foo"); - final PatternDescr bar2 = (PatternDescr) rightOr.getDescrs().get(1); - assertThat(bar2.getObjectType()).isEqualTo("Bar"); - } - - @Test - void parenthesesOrAndAnd() { - final String drl = "rule or_and_and\n" + - " when\n" + - " (Foo(x == 1) or Bar(x == 2)) and (Foo(x == 3) and Bar(x == 4))\n" + - " then\n" + - "end"; - PackageDescr pkg = parser.parse(drl); - - assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - final AndDescr rootAnd = (AndDescr) rule.getLhs(); - assertThat(rootAnd.getDescrs()).hasSize(2); - - final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get(0); - assertThat(leftOr.getDescrs()).hasSize(2); - final PatternDescr foo1 = (PatternDescr) leftOr.getDescrs().get(0); - assertThat(foo1.getObjectType()).isEqualTo("Foo"); - final PatternDescr bar1 = (PatternDescr) leftOr.getDescrs().get(1); - assertThat(bar1.getObjectType()).isEqualTo("Bar"); - - final AndDescr rightAnd = (AndDescr) rootAnd.getDescrs().get(1); - assertThat(rightAnd.getDescrs()).hasSize(2); - final PatternDescr foo2 = (PatternDescr) rightAnd.getDescrs().get(0); - assertThat(foo2.getObjectType()).isEqualTo("Foo"); - final PatternDescr bar2 = (PatternDescr) rightAnd.getDescrs().get(1); - assertThat(bar2.getObjectType()).isEqualTo("Bar"); - } - - @Test - void multipleLevelNestAndOrOrOrAnd() throws Exception { - final String drl = "rule and_or_or_or_and\n" + - " when\n" + - " (Foo(x == 1) and (Bar(x == 2) or Foo(x == 3))) or (Bar(x == 4) or (Foo(x == 5) and Bar(x == 6)))\n" + - " then\n" + - "end"; - PackageDescr pkg = parser.parse(drl); - - assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - final AndDescr rootAnd = (AndDescr) rule.getLhs(); - assertThat(rootAnd.getDescrs()).hasSize(1); - - final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); - assertThat(topOr.getDescrs()).hasSize(2); - - final AndDescr leftAnd = (AndDescr) topOr.getDescrs().get(0); - assertThat(leftAnd.getDescrs()).hasSize(2); - final PatternDescr foo1 = (PatternDescr) leftAnd.getDescrs().get(0); - assertThat(foo1.getObjectType()).isEqualTo("Foo"); - final OrDescr leftOr = (OrDescr) leftAnd.getDescrs().get(1); - assertThat(leftOr.getDescrs()).hasSize(2); - final PatternDescr bar1 = (PatternDescr) leftOr.getDescrs().get(0); - assertThat(bar1.getObjectType()).isEqualTo("Bar"); - final PatternDescr foo2 = (PatternDescr) leftOr.getDescrs().get(1); - assertThat(foo2.getObjectType()).isEqualTo("Foo"); - - final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); - assertThat(rightOr.getDescrs()).hasSize(2); - final PatternDescr bar2 = (PatternDescr) rightOr.getDescrs().get(0); - assertThat(bar2.getObjectType()).isEqualTo("Bar"); - final AndDescr rightAnd = (AndDescr) rightOr.getDescrs().get(1); - assertThat(rightAnd.getDescrs()).hasSize(2); - final PatternDescr foo3 = (PatternDescr) rightAnd.getDescrs().get(0); - assertThat(foo3.getObjectType()).isEqualTo("Foo"); - final PatternDescr bar3 = (PatternDescr) rightAnd.getDescrs().get(1); - assertThat(bar3.getObjectType()).isEqualTo("Bar"); - } - - @Test - void multipleLevelNestWithThreeOrSiblings() throws Exception { - final String drl = "rule nest_or_siblings\n" + - " when\n" + - " (A() or (B() or C() or (D() and E())))\n" + - " then\n" + - "end"; - PackageDescr pkg = parser.parse(drl); - - assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - final AndDescr rootAnd = (AndDescr) rule.getLhs(); - assertThat(rootAnd.getDescrs()).hasSize(1); - - final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); - assertThat(topOr.getDescrs()).hasSize(2); - - final PatternDescr leftPattern = (PatternDescr) topOr.getDescrs().get(0); - assertThat(leftPattern.getObjectType()).isEqualTo("A"); - - final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); - assertThat(rightOr.getDescrs()).as("top level Or has 3 sibling children").hasSize(3); - final PatternDescr bPattern = (PatternDescr) rightOr.getDescrs().get(0); - assertThat(bPattern.getObjectType()).isEqualTo("B"); - final PatternDescr cPattern = (PatternDescr) rightOr.getDescrs().get(1); - assertThat(cPattern.getObjectType()).isEqualTo("C"); - final AndDescr deAnd = (AndDescr) rightOr.getDescrs().get(2); - assertThat(deAnd.getDescrs()).hasSize(2); - - final PatternDescr dPattern = (PatternDescr) deAnd.getDescrs().get(0); - assertThat(dPattern.getObjectType()).isEqualTo("D"); - final PatternDescr ePattern = (PatternDescr) deAnd.getDescrs().get(1); - assertThat(ePattern.getObjectType()).isEqualTo("E"); - } - - @Test - public void existsMultipleLevelNestWithThreeOrSiblings() throws Exception { - final String drl = "rule nest_or_siblings\n" + - " when\n" + - " exists(A() or (B() or C() or (D() and E())))\n" + - " then\n" + - "end"; - PackageDescr pkg = parser.parse(drl); - - assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - final AndDescr rootAnd = (AndDescr) rule.getLhs(); - assertThat(rootAnd.getDescrs()).hasSize(1); - - final ExistsDescr topExists = (ExistsDescr) rootAnd.getDescrs().get(0); - assertThat(topExists.getDescrs()).hasSize(1); - - final OrDescr topOr = (OrDescr) topExists.getDescrs().get(0); - assertThat(topOr.getDescrs()).hasSize(2); - - final PatternDescr leftPattern = (PatternDescr) topOr.getDescrs().get(0); - assertThat(leftPattern.getObjectType()).isEqualTo("A"); - - final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); - assertThat(rightOr.getDescrs()).hasSize(3); - final PatternDescr bPattern = (PatternDescr) rightOr.getDescrs().get(0); - assertThat(bPattern.getObjectType()).isEqualTo("B"); - final PatternDescr cPattern = (PatternDescr) rightOr.getDescrs().get(1); - assertThat(cPattern.getObjectType()).isEqualTo("C"); - final AndDescr deAnd = (AndDescr) rightOr.getDescrs().get(2); - assertThat(deAnd.getDescrs()).hasSize(2); - - final PatternDescr dPattern = (PatternDescr) deAnd.getDescrs().get(0); - assertThat(dPattern.getObjectType()).isEqualTo("D"); - final PatternDescr ePattern = (PatternDescr) deAnd.getDescrs().get(1); - assertThat(ePattern.getObjectType()).isEqualTo("E"); - } - - @Test - public void parse_EvalMultiple() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "eval_multiple.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(4); - - final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(0 ); - assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace( "abc(\"foo\") + 5"); - - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(pattern.getObjectType()).isEqualTo("Foo"); - - } - - @Test - public void parse_WithEval() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "with_eval.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(3); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(pattern.getObjectType()).isEqualTo("Foo"); - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(pattern.getObjectType()).isEqualTo("Bar"); - - final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get( 2 ); - assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace( "abc(\"foo\")"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "Kapow"); - } - - @Test - public void parse_WithRetval() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "with_retval.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(col.getConstraint().getDescrs().size()).isEqualTo(1); - assertThat(col.getObjectType()).isEqualTo("Foo"); - final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get( 0 ); - - assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("name== (a + b)"); - } - - @Test - public void parse_WithPredicate() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "with_predicate.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - AndDescr and = (AndDescr) col.getConstraint(); - assertThat(and.getDescrs().size()).isEqualTo(2); - - final ExprConstraintDescr field = (ExprConstraintDescr) col.getDescrs().get( 0 ); - final ExprConstraintDescr pred = (ExprConstraintDescr) and.getDescrs().get( 1 ); - assertThat(field.getExpression()).isEqualToIgnoringWhitespace("$age2:age"); - assertThat(pred.getExpression()).isEqualToIgnoringWhitespace( "$age2 == $age1+2"); - } - - @Test - public void parse_NotWithConstraint() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "not_with_constraint.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); - - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(fieldBinding.getExpression()).isEqualToIgnoringWhitespace("$likes:like"); - - final NotDescr not = (NotDescr) rule.getLhs().getDescrs().get( 1 ); - pattern = (PatternDescr) not.getDescrs().get( 0 ); - - final ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); - - assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type == $likes"); - } - - @Disabled("Priority : Mid | Implement Descr lineNumber") - @Test - public void parse_Functions() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "functions.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(2); - - final List functions = pkg.getFunctions(); - assertThat(functions.size()).isEqualTo(2); - - FunctionDescr func = functions.get( 0 ); - assertThat(func.getName()).isEqualTo("functionA"); - assertThat(func.getReturnType()).isEqualTo("String"); - assertThat(func.getParameterNames().size()).isEqualTo(2); - assertThat(func.getParameterTypes().size()).isEqualTo(2); - assertThat(func.getLine()).isEqualTo(19); - assertThat(func.getColumn()).isEqualTo(0); - - assertThat(func.getParameterTypes().get(0)).isEqualTo("String"); - assertThat(func.getParameterNames().get(0)).isEqualTo("s"); - - assertThat(func.getParameterTypes().get(1)).isEqualTo("Integer"); - assertThat(func.getParameterNames().get(1)).isEqualTo("i"); - - assertThat(func.getBody()).isEqualToIgnoringWhitespace( "foo();"); - - func = functions.get( 1 ); - assertThat(func.getName()).isEqualTo("functionB"); - assertThat(func.getText()).isEqualToIgnoringWhitespace( "bar();"); - } - - @Test - public void parse_Comment() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "comment.drl" ); - - assertThat(pkg).isNotNull(); - - assertThat(pkg.getName()).isEqualTo("foo.bar"); - } - - @Test - public void parse_Attributes() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_attributes.drl" ); - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); - - final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(6); - - 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"); - assertThat(at.getValue()).isEqualTo("my_group"); - - at = (AttributeDescr) attrs.get( "no-loop" ); - assertThat(at.getName()).isEqualTo("no-loop"); - assertThat(at.getValue()).isEqualTo("true"); - - at = (AttributeDescr) attrs.get( "duration" ); - assertThat(at.getName()).isEqualTo("duration"); - assertThat(at.getValue()).isEqualTo("42"); - - at = (AttributeDescr) attrs.get( "activation-group" ); - assertThat(at.getName()).isEqualTo("activation-group"); - assertThat(at.getValue()).isEqualTo("my_activation_group"); - - at = (AttributeDescr) attrs.get( "lock-on-active" ); - assertThat(at.getName()).isEqualTo("lock-on-active"); - assertThat(at.getValue()).isEqualTo("true"); - } - - @Test - public void parse_Attributes2() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "rule_attributes2.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - List rules = pkg.getRules(); - assertThat(rules.size()).isEqualTo(3); - - RuleDescr rule = rules.get( 0 ); - assertThat(rule.getName()).isEqualTo("rule1"); - Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); - 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"); - assertThat(at.getValue()).isEqualTo("my_group"); - - rule = rules.get( 1 ); - assertThat(rule.getName()).isEqualTo("rule2"); - attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); - at = (AttributeDescr) attrs.get( "salience" ); - assertThat(at.getName()).isEqualTo("salience"); - assertThat(at.getValue()).isEqualTo("(Integer.MIN_VALUE)"); - at = (AttributeDescr) attrs.get( "no-loop" ); - assertThat(at.getName()).isEqualTo("no-loop"); - - rule = rules.get( 2 ); - assertThat(rule.getName()).isEqualTo("rule3"); - attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); - at = (AttributeDescr) attrs.get( "enabled" ); - assertThat(at.getName()).isEqualTo("enabled"); - assertThat(at.getValue()).isEqualTo("(Boolean.TRUE)"); - at = (AttributeDescr) attrs.get( "activation-group" ); - assertThat(at.getName()).isEqualTo("activation-group"); - assertThat(at.getValue()).isEqualTo("my_activation_group"); - - } - - @Test - public void parse_AttributeRefract() throws Exception { - final String source = "rule Test refract when Person() then end"; - - PackageDescr pkg = parser.parse( - source ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - - assertThat(rule.getName()).isEqualTo("Test"); - Map attributes = rule.getAttributes(); - assertThat(attributes.size()).isEqualTo(1); - AttributeDescr refract = attributes.get( "refract" ); - assertThat(refract).isNotNull(); - assertThat(refract.getValue()).isEqualTo("true"); - - } - - @Test - public void parse_EnabledExpression() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_enabled_expression.drl" ); - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); - - final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(3); - - AttributeDescr at = (AttributeDescr) attrs.get( "enabled" ); - assertThat(at.getName()).isEqualTo("enabled"); - assertThat(at.getValue()).isEqualTo("( 1 + 1 == 2 )"); - - at = (AttributeDescr) attrs.get( "salience" ); - assertThat(at.getName()).isEqualTo("salience"); - assertThat(at.getValue()).isEqualTo("( 1+2 )"); - - at = (AttributeDescr) attrs.get( "lock-on-active" ); - assertThat(at.getName()).isEqualTo("lock-on-active"); - assertThat(at.getValue()).isEqualTo("true"); - } - - @Test - public void parse_DurationExpression() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_duration_expression.drl" ); - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); - - final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); - - AttributeDescr at = (AttributeDescr) attrs.get( "duration" ); - assertThat(at.getName()).isEqualTo("duration"); - assertThat(at.getValue()).isEqualTo("1h30m"); - - at = (AttributeDescr) attrs.get( "lock-on-active" ); - assertThat(at.getName()).isEqualTo("lock-on-active"); - assertThat(at.getValue()).isEqualTo("true"); - } - - @Test - public void parse_Calendars() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_calendars_attribute.drl" ); - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); - - final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); - - AttributeDescr at = (AttributeDescr) attrs.get( "calendars" ); - assertThat(at.getName()).isEqualTo("calendars"); - assertThat(at.getValue()).isEqualTo("[ \"cal1\" ]"); - - at = (AttributeDescr) attrs.get( "lock-on-active" ); - assertThat(at.getName()).isEqualTo("lock-on-active"); - assertThat(at.getValue()).isEqualTo("true"); - } - - @Test - public void parse_Calendars2() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_calendars_attribute2.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); - - final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); - - AttributeDescr at = (AttributeDescr) attrs.get( "calendars" ); - assertThat(at.getName()).isEqualTo("calendars"); - assertThat(at.getValue()).isEqualTo("[ \"cal 1\", \"cal 2\", \"cal 3\" ]"); - - at = (AttributeDescr) attrs.get( "lock-on-active" ); - assertThat(at.getName()).isEqualTo("lock-on-active"); - assertThat(at.getValue()).isEqualTo("true"); - } - - @Disabled("Priority : Low | Not written in docs nor other unit tests. Drop the support?") - @Test - public void parse_Attributes_alternateSyntax() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_attributes_alt.drl" ); - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); - - final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(6); - - 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"); - assertThat(at.getValue()).isEqualTo("my_group"); - - at = (AttributeDescr) attrs.get( "no-loop" ); - assertThat(at.getName()).isEqualTo("no-loop"); - assertThat(at.getValue()).isEqualTo("true"); - - at = (AttributeDescr) attrs.get( "lock-on-active" ); - assertThat(at.getName()).isEqualTo("lock-on-active"); - assertThat(at.getValue()).isEqualTo("true"); - - at = (AttributeDescr) attrs.get( "duration" ); - assertThat(at.getName()).isEqualTo("duration"); - assertThat(at.getValue()).isEqualTo("42"); - - at = (AttributeDescr) attrs.get( "activation-group" ); - assertThat(at.getName()).isEqualTo("activation-group"); - assertThat(at.getValue()).isEqualTo("my_activation_group"); - } - - @Test - public void parse_Enumeration() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "enumeration.drl" ); - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(col.getObjectType()).isEqualTo("Foo"); - assertThat(col.getConstraint().getDescrs().size()).isEqualTo(1); - final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get( 0 ); - - assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == Foo.BAR"); - } - - @Test - public void parse_ExtraLhsNewline() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "extra_lhs_newline.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - } - - @Disabled("Priority : Low | Implement soundslike") - @Test - public void parse_SoundsLike() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "soundslike_operator.drl" ); - - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - PatternDescr pat = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - - pat.getConstraint(); - } - - @Test - public void parse_PackageAttributes() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "package_attributes.drl" ); - - AttributeDescr at = (AttributeDescr) pkg.getAttributes().get( 0 ); - assertThat(at.getName()).isEqualTo("agenda-group"); - assertThat(at.getValue()).isEqualTo("x"); - at = (AttributeDescr) pkg.getAttributes().get( 1 ); - assertThat(at.getName()).isEqualTo("dialect"); - assertThat(at.getValue()).isEqualTo("java"); - - assertThat(pkg.getRules().size()).isEqualTo(2); - - assertThat(pkg.getImports().size()).isEqualTo(2); - - 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"); - assertThat(at.getValue()).isEqualTo("x"); - at = (AttributeDescr) rule.getAttributes().get( "dialect" ); - assertThat(at.getName()).isEqualTo("dialect"); - assertThat(at.getValue()).isEqualTo("java"); - - rule = (RuleDescr) pkg.getRules().get( 1 ); - assertThat(rule.getName()).isEqualTo("baz"); - 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"); - assertThat(at.getValue()).isEqualTo("x"); - - } - - @Test - public void parse_StatementOrdering1() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "statement_ordering_1.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(2); - - assertThat(((RuleDescr) pkg.getRules().get(0)).getName()).isEqualTo("foo"); - assertThat(((RuleDescr) pkg.getRules().get(1)).getName()).isEqualTo("bar"); - - assertThat(pkg.getFunctions().size()).isEqualTo(2); - - assertThat(((FunctionDescr) pkg.getFunctions().get(0)).getName()).isEqualTo("cheeseIt"); - assertThat(((FunctionDescr) pkg.getFunctions().get(1)).getName()).isEqualTo("uncheeseIt"); - - assertThat(pkg.getImports().size()).isEqualTo(4); - assertThat(((ImportDescr) pkg.getImports().get(0)).getTarget()).isEqualTo("im.one"); - assertThat(((ImportDescr) pkg.getImports().get(1)).getTarget()).isEqualTo("im.two"); - assertThat(((ImportDescr) pkg.getImports().get(2)).getTarget()).isEqualTo("im.three"); - assertThat(((ImportDescr) pkg.getImports().get(3)).getTarget()).isEqualTo("im.four"); - } - - @Test - public void parse_RuleNamesStartingWithNumbers() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "rule_names_number_prefix.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(2); - - assertThat(((RuleDescr) pkg.getRules().get(0)).getName()).isEqualTo("1. Do Stuff!"); - assertThat(((RuleDescr) pkg.getRules().get(1)).getName()).isEqualTo("2. Do More Stuff!"); - } - - @Test - public void parse_EvalWithNewline() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "eval_with_newline.drl"); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - } - - @Disabled("Priority : Mid | implement Descr lineNumber") - @Test - public void parse_EndPosition() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "test_EndPosition.drl" ); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(col.getLine()).isEqualTo(21); - assertThat(col.getEndLine()).isEqualTo(23); - } - - @Test - public void parse_QualifiedClassname() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "qualified_classname.drl" ); - - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - - final PatternDescr p = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - - assertThat(p.getObjectType()).isEqualTo("com.cheeseco.Cheese"); - } - - @Test - public void parse_Accumulate() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulate.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;"); - assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;"); - assertThat(accum.getReverseCode()).isNull(); - assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)"); - - assertThat(accum.isExternalFunction()).isFalse(); - - final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); - assertThat(pattern.getObjectType()).isEqualTo("Person"); - } - - @Test - public void parse_AccumulateWithBindings() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulate_with_bindings.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace( "$counter"); - assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;"); - assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;"); - assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)"); - - final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); - assertThat(pattern.getObjectType()).isEqualTo("Person"); - } - - @Test - public void parse_Collect() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "collect.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final CollectDescr collect = (CollectDescr) outPattern.getSource(); - - final PatternDescr pattern = (PatternDescr) collect.getInputPattern(); - assertThat(pattern.getObjectType()).isEqualTo("Person"); - } - - @Test - public void parse_Predicate2() throws Exception { - // predicates are also prefixed by the eval keyword - final RuleDescr rule = parseAndGetFirstRuleDescr( - "rule X when Foo(eval( $var.equals(\"xyz\") )) then end" ); - - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final List< ? > constraints = pattern.getConstraint().getDescrs(); - assertThat(constraints.size()).isEqualTo(1); - - final ExprConstraintDescr predicate = (ExprConstraintDescr) constraints.get( 0 ); - assertThat(predicate.getExpression()).isEqualToIgnoringWhitespace("eval( $var.equals(\"xyz\") )"); - } - - @Test - public void parse_EscapedStrings() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "escaped-string.drl" ); - - assertThat(rule).isNotNull(); - - assertThat(rule.getName()).isEqualTo("test_Quotes"); - - final String expected = "String s = \"\\\"\\n\\t\\\\\";"; - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( expected); - } - - @Test - public void parse_NestedCEs() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "nested_conditional_elements.drl" ); - - assertThat(rule).isNotNull(); - - final AndDescr root = rule.getLhs(); - final NotDescr not1 = (NotDescr) root.getDescrs().get( 0 ); - final AndDescr and1 = (AndDescr) not1.getDescrs().get( 0 ); - - final PatternDescr state = (PatternDescr) and1.getDescrs().get( 0 ); - final NotDescr not2 = (NotDescr) and1.getDescrs().get( 1 ); - final AndDescr and2 = (AndDescr) not2.getDescrs().get( 0 ); - final PatternDescr person = (PatternDescr) and2.getDescrs().get( 0 ); - final PatternDescr cheese = (PatternDescr) and2.getDescrs().get( 1 ); - - final PatternDescr person2 = (PatternDescr) root.getDescrs().get( 1 ); - final OrDescr or = (OrDescr) root.getDescrs().get( 2 ); - final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get( 0 ); - final PatternDescr cheese3 = (PatternDescr) or.getDescrs().get( 1 ); - - assertThat("State").isEqualTo(state.getObjectType()); - assertThat("Person").isEqualTo(person.getObjectType()); - assertThat("Cheese").isEqualTo(cheese.getObjectType()); - assertThat("Person").isEqualTo(person2.getObjectType()); - assertThat("Cheese").isEqualTo(cheese2.getObjectType()); - assertThat("Cheese").isEqualTo(cheese3.getObjectType()); - } - - @Test - public void parse_Forall() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "forall.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0 ); - - assertThat(forall.getDescrs().size()).isEqualTo(2); - final PatternDescr pattern = forall.getBasePattern(); - assertThat(pattern.getObjectType()).isEqualTo("Person"); - final List remaining = forall.getRemainingPatterns(); - assertThat(remaining.size()).isEqualTo(1); - final PatternDescr cheese = (PatternDescr) remaining.get( 0 ); - assertThat(cheese.getObjectType()).isEqualTo("Cheese"); - } - - @Test - public void parse_ForallWithFrom() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "forallwithfrom.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get( 0 ); - - assertThat(forall.getDescrs().size()).isEqualTo(2); - final PatternDescr pattern = forall.getBasePattern(); - assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat(((FromDescr) pattern.getSource()).getDataSource().toString()).isEqualTo("$village"); - final List remaining = forall.getRemainingPatterns(); - assertThat(remaining.size()).isEqualTo(1); - final PatternDescr cheese = (PatternDescr) remaining.get( 0 ); - assertThat(cheese.getObjectType()).isEqualTo("Cheese"); - assertThat(((FromDescr) cheese.getSource()).getDataSource().toString()).isEqualTo("$cheesery"); - } - - @Test - public void parse_Memberof() throws Exception { - final String text = "rule X when Country( $cities : city )\nPerson( city memberOf $cities )\n then end"; - AndDescr descrs = parseAndGetFirstRuleDescr( - text).getLhs(); - - assertThat(descrs.getDescrs().size()).isEqualTo(2); - PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 1 ); - ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); - - assertThat(fieldConstr.getExpression()).isEqualTo("city memberOf $cities"); - } - - @Test - public void parse_NotMemberof() throws Exception { - final String text = "rule X when Country( $cities : city )\nPerson( city not memberOf $cities ) then end\n"; - AndDescr descrs = parseAndGetFirstRuleDescr( - text).getLhs(); - - assertThat(descrs.getDescrs().size()).isEqualTo(2); - PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 1 ); - ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); - - assertThat(fieldConstr.getExpression()).isEqualTo("city not memberOf $cities"); - } - - @Test - public void parse_InOperator() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "in_operator_test.drl" ); - - assertThat(rule).isNotNull(); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "consequence();"); - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); - - // The first pattern, with 2 restrictions on a single field (plus a - // connective) - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); - - ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); - assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); - - // the second col, with 2 fields, the first with 2 restrictions, the - // second field with one - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); - - fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); - assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type in ( \"sedan\", \"wagon\" )"); - - // now the second field - fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 1 ); - assertThat(fld.getExpression()).isEqualTo("age < 3"); - - } - - @Test - public void parse_NotInOperator() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "notin_operator_test.drl" ); - - assertThat(rule).isNotNull(); - - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "consequence();"); - assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); - - // The first pattern, with 2 restrictions on a single field (plus a - // connective) - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); - - ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); - assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); - - // the second col, with 2 fields, the first with 2 restrictions, the - // second field with one - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); - - fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); - assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type not in ( \"sedan\", \"wagon\" )"); - - // now the second field - fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 1 ); - assertThat(fld.getExpression()).isEqualTo("age < 3"); - - } - - @Test - public void parse_CheckOrDescr() throws Exception { - final String text = "rule X when Person( eval( age == 25 ) || ( eval( name.equals( \"bob\" ) ) && eval( age == 30 ) ) ) then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(1); - assertThat(AndDescr.class).isEqualTo(pattern.getConstraint().getClass()); - - assertThat(pattern.getConstraint().getDescrs().get(0).getClass()).isEqualTo(ExprConstraintDescr.class); - - } - - @Test - public void parse_ConstraintAndConnective() throws Exception { - final String text = "rule X when Person( age < 42 && location==\"atlanta\") then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 && location==\"atlanta\""); - } - - @Test - public void parse_ConstraintOrConnective() throws Exception { - final String text = "rule X when Person( age < 42 || location==\"atlanta\") then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 || location==\"atlanta\""); - } - - @Test - public void parse_Restrictions() throws Exception { - final String text = "rule X when Foo( bar > 1 || == 1 ) then end\n"; - - AndDescr descrs = (AndDescr) parseAndGetFirstRuleDescr( - text ).getLhs(); - - assertThat(descrs.getDescrs().size()).isEqualTo(1); - PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 0 ); - ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); - - assertThat(fieldConstr.getExpression()).isEqualTo("bar > 1 || == 1"); - } - - @Test - public void parse_Semicolon() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "semicolon.drl" ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); - assertThat(pkg.getGlobals().size()).isEqualTo(1); - assertThat(pkg.getRules().size()).isEqualTo(3); - - final RuleDescr rule1 = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule1.getLhs().getDescrs().size()).isEqualTo(2); - - final RuleDescr query1 = (RuleDescr) pkg.getRules().get( 1 ); - assertThat(query1.getLhs().getDescrs().size()).isEqualTo(3); - - final RuleDescr rule2 = (RuleDescr) pkg.getRules().get( 2 ); - assertThat(rule2.getLhs().getDescrs().size()).isEqualTo(2); - } - - @Test - public void parse_Eval() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "eval_parsing.drl" ); - - assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); - assertThat(pkg.getRules().size()).isEqualTo(1); - - final RuleDescr rule1 = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule1.getLhs().getDescrs().size()).isEqualTo(1); - } - - @Test - public void parse_AccumulateReverse() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulateReverse.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final AccumulateDescr accum = (AccumulateDescr) out.getSource(); - assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;" - ); - assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;" - ); - assertThat(accum.getReverseCode()).isEqualToIgnoringWhitespace( "x--;" - ); - assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)" - ); - assertThat(accum.isExternalFunction()).isFalse(); - - final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); - assertThat(pattern.getObjectType()).isEqualTo("Person"); - } - - @Test - public void parse_AccumulateExternalFunction() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulateExternalFunction.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final AccumulateDescr accum = (AccumulateDescr) out.getSource(); - assertThat(accum.getFunctions().get( 0 ).getParams()[0]).isEqualToIgnoringWhitespace( "$age" - ); - assertThat(accum.getFunctions().get( 0 ).getFunction()).isEqualToIgnoringWhitespace( "average" - ); - assertThat(accum.isExternalFunction()).isTrue(); - - final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); - assertThat(pattern.getObjectType()).isEqualTo("Person"); - } - - @Test - public void parse_CollectWithNestedFrom() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "collect_with_nested_from.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final CollectDescr collect = (CollectDescr) out.getSource(); - - PatternDescr person = (PatternDescr) collect.getInputPattern(); - assertThat(person.getObjectType()).isEqualTo("Person"); - - final CollectDescr collect2 = (CollectDescr) person.getSource(); - - final PatternDescr people = collect2.getInputPattern(); - assertThat(people.getObjectType()).isEqualTo("People"); - } - - @Test - public void parse_AccumulateWithNestedFrom() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulate_with_nested_from.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final AccumulateDescr accumulate = (AccumulateDescr) out.getSource(); - - PatternDescr person = (PatternDescr) accumulate.getInputPattern(); - assertThat(person.getObjectType()).isEqualTo("Person"); - - final CollectDescr collect2 = (CollectDescr) person.getSource(); - - final PatternDescr people = collect2.getInputPattern(); - assertThat(people.getObjectType()).isEqualTo("People"); - } - - @Test - public void parse_AccumulateMultipleFunctions() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulateMultipleFunctions.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(out.getObjectType()).isEqualTo("Object"); - AccumulateDescr accum = (AccumulateDescr) out.getSource(); - assertThat(accum.isExternalFunction()).isTrue(); - - List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(3); - assertThat(functions.get(0).getFunction()).isEqualTo("average"); - assertThat(functions.get(0).getBind()).isEqualTo("$a1"); - assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); - - assertThat(functions.get(1).getFunction()).isEqualTo("min"); - assertThat(functions.get(1).getBind()).isEqualTo("$m1"); - assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); - - assertThat(functions.get(2).getFunction()).isEqualTo("max"); - assertThat(functions.get(2).getBind()).isEqualTo("$M1"); - assertThat(functions.get(2).getParams()[0]).isEqualTo("$price"); - - final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); - assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - } - - @Test - public void parse_AccumulateMnemonic() throws Exception { - String drl = "package org.drools.mvel.compiler\n" + - "rule \"Accumulate 1\"\n" + - "when\n" + - " acc( Cheese( $price : price ),\n" + - " $a1 : average( $price ) )\n" + - "then\n" + - "end\n"; - PackageDescr pkg = parser.parse( - drl ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(out.getObjectType()).isEqualTo("Object"); - AccumulateDescr accum = (AccumulateDescr) out.getSource(); - assertThat(accum.isExternalFunction()).isTrue(); - - List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(1); - assertThat(functions.get(0).getFunction()).isEqualTo("average"); - assertThat(functions.get(0).getBind()).isEqualTo("$a1"); - assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); - - final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); - assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - } - - @Test - public void parse_AccumulateMnemonic2() throws Exception { - String drl = "package org.drools.mvel.compiler\n" + - "rule \"Accumulate 1\"\n" + - "when\n" + - " Number() from acc( Cheese( $price : price ),\n" + - " average( $price ) )\n" + - "then\n" + - "end\n"; - PackageDescr pkg = parser.parse( - drl ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(out.getObjectType()).isEqualTo("Number"); - AccumulateDescr accum = (AccumulateDescr) out.getSource(); - assertThat(accum.isExternalFunction()).isTrue(); - - List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(1); - assertThat(functions.get(0).getFunction()).isEqualTo("average"); - assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); - - final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); - assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - } - - @Test - public void parse_ImportAccumulate() throws Exception { - String drl = "package org.drools.mvel.compiler\n" + - "import acc foo.Bar baz\n" + - "import accumulate foo.Bar2 baz2\n" + - "rule \"Accumulate 1\"\n" + - "when\n" + - " acc( Cheese( $price : price ),\n" + - " $v1 : baz( $price ), \n" + - " $v2 : baz2( $price ) )\n" + - "then\n" + - "end\n"; - PackageDescr pkg = parser.parse( - drl ); - - assertThat(pkg.getAccumulateImports().size()).isEqualTo(2); - AccumulateImportDescr imp = (AccumulateImportDescr) pkg.getAccumulateImports().get(0); - assertThat(imp.getTarget()).isEqualTo("foo.Bar"); - assertThat(imp.getFunctionName()).isEqualTo("baz"); - - imp = (AccumulateImportDescr) pkg.getAccumulateImports().get(1); - assertThat(imp.getTarget()).isEqualTo("foo.Bar2"); - assertThat(imp.getFunctionName()).isEqualTo("baz2"); - - assertThat(pkg.getRules().size()).isEqualTo(1); - - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(out.getObjectType()).isEqualTo("Object"); - AccumulateDescr accum = (AccumulateDescr) out.getSource(); - assertThat(accum.isExternalFunction()).isTrue(); - - List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(2); - assertThat(functions.get(0).getFunction()).isEqualTo("baz"); - assertThat(functions.get(0).getBind()).isEqualTo("$v1"); - assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); - - assertThat(functions.get(1).getFunction()).isEqualTo("baz2"); - assertThat(functions.get(1).getBind()).isEqualTo("$v2"); - assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); - - final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); - assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - } - - @Test - public void parse_AccumulateMultipleFunctionsConstraint() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulateMultipleFunctionsConstraint.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(out.getObjectType()).isEqualTo("Object"); - assertThat(out.getConstraint().getDescrs().size()).isEqualTo(2); - assertThat(out.getConstraint().getDescrs().get(0).toString()).isEqualTo("$a1 > 10 && $M1 <= 100"); - assertThat(out.getConstraint().getDescrs().get(1).toString()).isEqualTo("$m1 == 5"); - AccumulateDescr accum = (AccumulateDescr) out.getSource(); - assertThat(accum.isExternalFunction()).isTrue(); - - List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(3); - assertThat(functions.get(0).getFunction()).isEqualTo("average"); - assertThat(functions.get(0).getBind()).isEqualTo("$a1"); - assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); - - assertThat(functions.get(1).getFunction()).isEqualTo("min"); - assertThat(functions.get(1).getBind()).isEqualTo("$m1"); - assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); - - assertThat(functions.get(2).getFunction()).isEqualTo("max"); - assertThat(functions.get(2).getBind()).isEqualTo("$M1"); - assertThat(functions.get(2).getParams()[0]).isEqualTo("$price"); - - final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); - assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - } - - @Test - public void parse_OrCE() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "or_ce.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); - - final PatternDescr person = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(person.getObjectType()).isEqualTo("Person"); - assertThat(person.getIdentifier()).isEqualTo("$p"); - - final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(or.getDescrs().size()).isEqualTo(2); - - final PatternDescr cheese1 = (PatternDescr) or.getDescrs().get( 0 ); - assertThat(cheese1.getObjectType()).isEqualTo("Cheese"); - assertThat(cheese1.getIdentifier()).isEqualTo("$c"); - final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get( 1 ); - assertThat(cheese2.getObjectType()).isEqualTo("Cheese"); - assertThat(cheese2.getIdentifier()).isNull(); - } - - @Test - public void parse_RuleSingleLine() throws Exception { - final String text = "rule \"another test\" salience 10 when eval( true ) then System.out.println(1); end"; - RuleDescr rule = parseAndGetFirstRuleDescr( - text ); - - assertThat(rule.getName()).isEqualTo("another test"); - assertThat((String)rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1); "); - } - - @Test - public void parse_RuleTwoLines() throws Exception { - final String text = "rule \"another test\" salience 10 when eval( true ) then System.out.println(1);\n end"; - RuleDescr rule = parseAndGetFirstRuleDescr( - text ); - - assertThat(rule.getName()).isEqualTo("another test"); - assertThat((String)rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1);\n "); - } - - @Test - public void parse_RuleParseLhs3() throws Exception { - final String text = "rule X when (or\nnot Person()\n(and Cheese()\nMeat()\nWine())) then end"; - AndDescr pattern = parseAndGetFirstRuleDescr( - text ).getLhs(); - - assertThat(pattern.getDescrs().size()).isEqualTo(1); - OrDescr or = (OrDescr) pattern.getDescrs().get( 0 ); - assertThat(or.getDescrs().size()).isEqualTo(2); - NotDescr not = (NotDescr) or.getDescrs().get( 0 ); - AndDescr and = (AndDescr) or.getDescrs().get( 1 ); - assertThat(not.getDescrs().size()).isEqualTo(1); - PatternDescr person = (PatternDescr) not.getDescrs().get( 0 ); - assertThat(person.getObjectType()).isEqualTo("Person"); - assertThat(and.getDescrs().size()).isEqualTo(3); - PatternDescr cheese = (PatternDescr) and.getDescrs().get( 0 ); - assertThat(cheese.getObjectType()).isEqualTo("Cheese"); - PatternDescr meat = (PatternDescr) and.getDescrs().get( 1 ); - assertThat(meat.getObjectType()).isEqualTo("Meat"); - PatternDescr wine = (PatternDescr) and.getDescrs().get( 2 ); - assertThat(wine.getObjectType()).isEqualTo("Wine"); - - } - - @Test - public void parse_AccumulateMultiPattern() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulate_multi_pattern.drl" ); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace( "$counter" - ); - assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;" - ); - assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;" - ); - assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)" - ); - - final AndDescr and = (AndDescr) accum.getInput(); - assertThat(and.getDescrs().size()).isEqualTo(2); - final PatternDescr person = (PatternDescr) and.getDescrs().get( 0 ); - final PatternDescr cheese = (PatternDescr) and.getDescrs().get( 1 ); - assertThat(person.getObjectType()).isEqualTo("Person"); - assertThat(cheese.getObjectType()).isEqualTo("Cheese"); - } - - @Test - public void parse_PluggableOperators() throws Exception { - - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "pluggable_operators.drl" ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(5); - - final PatternDescr eventA = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(eventA.getIdentifier()).isEqualTo("$a"); - assertThat(eventA.getObjectType()).isEqualTo("EventA"); - - final PatternDescr eventB = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(eventB.getIdentifier()).isEqualTo("$b"); - assertThat(eventB.getObjectType()).isEqualTo("EventB"); - assertThat(eventB.getConstraint().getDescrs().size()).isEqualTo(1); - assertThat(eventB.getConstraint().getDescrs().size()).isEqualTo(1); - - final ExprConstraintDescr fcdB = (ExprConstraintDescr) eventB.getConstraint().getDescrs().get( 0 ); - assertThat(fcdB.getExpression()).isEqualTo("this after[1,10] $a || this not after[15,20] $a"); - - final PatternDescr eventC = (PatternDescr) rule.getLhs().getDescrs().get( 2 ); - assertThat(eventC.getIdentifier()).isEqualTo("$c"); - assertThat(eventC.getObjectType()).isEqualTo("EventC"); - assertThat(eventC.getConstraint().getDescrs().size()).isEqualTo(1); - final ExprConstraintDescr fcdC = (ExprConstraintDescr) eventC.getConstraint().getDescrs().get( 0 ); - assertThat(fcdC.getExpression()).isEqualTo("this finishes $b"); - - final PatternDescr eventD = (PatternDescr) rule.getLhs().getDescrs().get( 3 ); - assertThat(eventD.getIdentifier()).isEqualTo("$d"); - assertThat(eventD.getObjectType()).isEqualTo("EventD"); - assertThat(eventD.getConstraint().getDescrs().size()).isEqualTo(1); - final ExprConstraintDescr fcdD = (ExprConstraintDescr) eventD.getConstraint().getDescrs().get( 0 ); - assertThat(fcdD.getExpression()).isEqualTo("this not starts $a"); - - final PatternDescr eventE = (PatternDescr) rule.getLhs().getDescrs().get( 4 ); - assertThat(eventE.getIdentifier()).isEqualTo("$e"); - assertThat(eventE.getObjectType()).isEqualTo("EventE"); - assertThat(eventE.getConstraint().getDescrs().size()).isEqualTo(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"); - } - - @Test - public void parse_RuleMetadata() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "Rule_with_Metadata.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - // @fooAttribute(barValue) - // @fooAtt2(barVal2) - RuleDescr rule = pkg.getRules().get( 0 ); - assertThat(rule.getAnnotationNames().contains("fooMeta1")).isTrue(); - assertThat(rule.getAnnotation("fooMeta1").getValue()).isEqualTo("barVal1"); - assertThat(rule.getAnnotationNames().contains("fooMeta2")).isTrue(); - assertThat(rule.getAnnotation("fooMeta2").getValue()).isEqualTo("barVal2"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"Consequence\");" - ); - } - - @Test - public void parse_RuleExtends() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "Rule_with_Extends.drl" ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get( 0 ); - assertThat(rule.getParentName() != null).isTrue(); - assertThat(rule.getParentName()).isEqualTo("rule1"); - - AndDescr lhs = rule.getLhs(); - assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); - - PatternDescr pattern = (PatternDescr) lhs.getDescrs().get( 0 ); - assertThat(pattern.getObjectType()).isEqualTo("foo"); - assertThat(pattern.getIdentifier()).isEqualTo("$foo"); - - } - - @Test - public void parse_TypeDeclarationWithFields() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "declare_type_with_fields.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - List td = pkg.getTypeDeclarations(); - assertThat(td.size()).isEqualTo(3); - - TypeDeclarationDescr d = td.get( 0 ); - assertThat(d.getTypeName()).isEqualTo("SomeFact"); - assertThat(d.getFields().size()).isEqualTo(2); - assertThat(d.getFields().containsKey("name")).isTrue(); - assertThat(d.getFields().containsKey("age")).isTrue(); - - TypeFieldDescr f = d.getFields().get("name" ); - assertThat(f.getPattern().getObjectType()).isEqualTo("String"); - - f = d.getFields().get( "age" ); - assertThat(f.getPattern().getObjectType()).isEqualTo("Integer"); - - d = td.get( 1 ); - assertThat(d.getTypeName()).isEqualTo("AnotherFact"); - - TypeDeclarationDescr type = td.get( 2 ); - assertThat(type.getTypeName()).isEqualTo("Person"); - - assertThat(type.getAnnotation("role").getValue()).isEqualTo("fact"); - assertThat(type.getAnnotation("doc").getValue("descr")).isEqualTo("\"Models a person\""); - assertThat(type.getAnnotation("doc").getValue("author")).isEqualTo("\"Bob\""); - assertThat(type.getAnnotation("doc").getValue("date")).isEqualTo("Calendar.getInstance().getDate()"); - - assertThat(type.getFields().size()).isEqualTo(2); - TypeFieldDescr field = type.getFields().get( "name" ); - assertThat(field.getFieldName()).isEqualTo("name"); - assertThat(field.getPattern().getObjectType()).isEqualTo("String"); - assertThat(field.getInitExpr()).isEqualTo("\"John Doe\""); - assertThat(field.getAnnotation("length").getValue("max")).isEqualTo("50"); - assertThat( field.getAnnotation( "key" ) ).isNotNull(); - - field = type.getFields().get( "age" ); - assertThat(field.getFieldName()).isEqualTo("age"); - assertThat(field.getPattern().getObjectType()).isEqualTo("int"); - assertThat(field.getInitExpr()).isEqualTo("-1"); - assertThat(field.getAnnotation("ranged").getValue("min")).isEqualTo("0"); - assertThat(field.getAnnotation("ranged").getValue("max")).isEqualTo("150"); - assertThat(field.getAnnotation("ranged").getValue("unknown")).isEqualTo("-1"); - - } - - @Test - public void parenthesesOneLevelNestWithThreeSiblings() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( "Rule_with_nested_LHS.drl" ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get( 0 ); - assertThat(rule.getName()).isEqualTo("test"); - - AndDescr lhs = rule.getLhs(); - assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(2); - - PatternDescr a = (PatternDescr) lhs.getDescrs().get( 0 ); - assertThat(a.getObjectType()).isEqualTo("A"); - - OrDescr or = (OrDescr) lhs.getDescrs().get( 1 ); - assertThat(or.getDescrs().size()).isEqualTo(3); - - AndDescr and1 = (AndDescr) or.getDescrs().get( 0 ); - assertThat(and1.getDescrs().size()).isEqualTo(2); - PatternDescr b = (PatternDescr) and1.getDescrs().get( 0 ); - PatternDescr c = (PatternDescr) and1.getDescrs().get( 1 ); - assertThat(b.getObjectType()).isEqualTo("B"); - assertThat(c.getObjectType()).isEqualTo("C"); - - AndDescr and2 = (AndDescr) or.getDescrs().get( 1 ); - assertThat(and2.getDescrs().size()).isEqualTo(2); - PatternDescr d = (PatternDescr) and2.getDescrs().get( 0 ); - PatternDescr e = (PatternDescr) and2.getDescrs().get( 1 ); - assertThat(d.getObjectType()).isEqualTo("D"); - assertThat(e.getObjectType()).isEqualTo("E"); - - AndDescr and3 = (AndDescr) or.getDescrs().get( 2 ); - assertThat(and3.getDescrs().size()).isEqualTo(2); - PatternDescr f = (PatternDescr) and3.getDescrs().get( 0 ); - PatternDescr g = (PatternDescr) and3.getDescrs().get( 1 ); - assertThat(f.getObjectType()).isEqualTo("F"); - assertThat(g.getObjectType()).isEqualTo("G"); - } - - @Test - public void parse_EntryPoint() throws Exception { - final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point StreamA then end"; - - PackageDescr pkg = parser.parse( - text ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get( 0 ); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); - - assertThat(pattern.getSource()).isNotNull(); - EntryPointDescr entry = (EntryPointDescr) pattern.getSource(); - assertThat(entry.getEntryId()).isEqualTo("StreamA"); - } - - @Test - public void parse_EntryPoint2() throws Exception { - final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point \"StreamA\" then end"; - - PackageDescr pkg = parser.parse( - text ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get( 0 ); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); - - assertThat(pattern.getSource()).isNotNull(); - EntryPointDescr entry = (EntryPointDescr) pattern.getSource(); - assertThat(entry.getEntryId()).isEqualTo("StreamA"); - } - - @Test - public void parse_SlidingWindow() throws Exception { - final String text = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end"; - - PackageDescr pkg = parser.parse( text ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - RuleDescr rule = pkg.getRules().get( 0 ); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); - - List behaviors = pattern.getBehaviors(); - assertThat(behaviors).isNotNull(); - assertThat(behaviors.size()).isEqualTo(1); - BehaviorDescr descr = behaviors.get( 0 ); - assertThat(descr.getType()).isEqualTo("window"); - assertThat(descr.getSubType()).isEqualTo("length"); - assertThat(descr.getParameters().get(0)).isEqualTo("10"); - } - - @Test - public void parse_RuleOldSyntax1() throws Exception { - final String source = "rule \"Test\" when ( not $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; - - PackageDescr pkg = parser.parse( - source ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - - assertThat(rule.getName()).isEqualTo("Test"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - assertThat(((NotDescr) rule.getLhs().getDescrs().get(0)).getDescrs().size()).isEqualTo(1); - NotDescr notDescr = (NotDescr) rule.getLhs().getDescrs().get( 0 ); - PatternDescr patternDescr = (PatternDescr) notDescr.getDescrs().get( 0 ); - assertThat(patternDescr.getIdentifier()).isEqualTo("$r"); - assertThat(patternDescr.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get( 0 ); - assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); - } - - @Test - public void parse_RuleOldSyntax2() throws Exception { - final String source = "rule \"Test\" when ( $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; - - PackageDescr pkg = parser.parse( - source ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - - assertThat(rule.getName()).isEqualTo("Test"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - PatternDescr patternDescr = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(patternDescr.getIdentifier()).isEqualTo("$r"); - assertThat(patternDescr.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get( 0 ); - assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); - } - - @Test - public void parse_TypeWithMetaData() throws Exception { - - PackageDescr pkg = parseAndGetPackageDescrFromFile( - "type_with_meta.drl" ); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - final List declarations = pkg.getTypeDeclarations(); - - assertThat(declarations.size()).isEqualTo(3); - } - - @Test - public void parse_NullConstraints() throws Exception { - final String text = "rule X when Person( name == null ) then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(fcd.getExpression()).isEqualTo("name == null"); - assertThat(fcd.getPosition()).isEqualTo(0); - assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); - } - - @Test - public void parse_PositionalConstraintsOnly() throws Exception { - final String text = "rule X when Person( \"Mark\", 42; ) then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(2); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); - assertThat(fcd.getPosition()).isEqualTo(0); - assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); - fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); - assertThat(fcd.getExpression()).isEqualTo("42"); - assertThat(fcd.getPosition()).isEqualTo(1); - assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); - } - - @Test - public void parse_IsQuery() throws Exception { - final String text = "rule X when ?person( \"Mark\", 42; ) then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.isQuery()).isTrue(); - - assertThat(pattern.getDescrs().size()).isEqualTo(2); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); - assertThat(fcd.getPosition()).isEqualTo(0); - assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); - fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); - assertThat(fcd.getExpression()).isEqualTo("42"); - assertThat(fcd.getPosition()).isEqualTo(1); - assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); - } - - @Test - public void parse_FromFollowedByQuery() throws Exception { - // the 'from' expression requires a ";" to disambiguate the "?" - // prefix for queries from the ternary operator "? :" - final String text = "rule X when Cheese() from $cheesery ?person( \"Mark\", 42; ) then end"; - RuleDescr rule = parseAndGetFirstRuleDescr( - text ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - assertThat(pattern.getSource().getText()).isEqualTo("from $cheesery"); - assertThat(pattern.isQuery()).isFalse(); - - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(pattern.getObjectType()).isEqualTo("person"); - assertThat(pattern.isQuery()).isTrue(); - - } - - @Test - public void parse_FromWithTernaryFollowedByQuery() throws Exception { - // the 'from' expression requires a ";" to disambiguate the "?" - // prefix for queries from the ternary operator "? :" - final String text = "rule X when Cheese() from (isFull ? $cheesery : $market) ?person( \"Mark\", 42; ) then end"; - RuleDescr rule = parseAndGetFirstRuleDescr( - text ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - assertThat(pattern.getSource().getText()).isEqualToIgnoringWhitespace("from (isFull ? $cheesery : $market)"); - assertThat(pattern.isQuery()).isFalse(); - - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(pattern.getObjectType()).isEqualTo("person"); - assertThat(pattern.isQuery()).isTrue(); - - } - - @Disabled("Priority : Low | Implement multi-value annotation. Not written in docs") - @Test - public void parse_MultiValueAnnotationsBackwardCompatibility() throws Exception { - // multiple values with no keys are parsed as a single value - final String text = "rule X @ann1( val1, val2 ) @ann2( \"val1\", \"val2\" ) when then end"; - RuleDescr rule = parseAndGetFirstRuleDescr( - text ); - - AnnotationDescr ann = rule.getAnnotation("ann1" ); - assertThat(ann).isNotNull(); - assertThat(ann.getValue()).isEqualTo("val1, val2"); - - ann = rule.getAnnotation( "ann2" ); - assertThat(ann).isNotNull(); - assertThat(ann.getValue()).isEqualTo("\"val1\", \"val2\""); - } - - @Test - public void parse_PositionalsAndNamedConstraints() throws Exception { - final String text = "rule X when Person( \"Mark\", 42; location == \"atlanta\" ) then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(3); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); - assertThat(fcd.getPosition()).isEqualTo(0); - assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); - fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); - assertThat(fcd.getExpression()).isEqualTo("42"); - assertThat(fcd.getPosition()).isEqualTo(1); - assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); - - fcd = (ExprConstraintDescr) pattern.getDescrs().get( 2 ); - assertThat(fcd.getExpression()).isEqualTo("location == \"atlanta\""); - assertThat(fcd.getPosition()).isEqualTo(2); - assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); - - } - - @Test - public void parse_UnificationBinding() throws Exception { - final String text = "rule X when $p := Person( $name := name, $loc : location ) then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getIdentifier()).isEqualTo("$p"); - assertThat(pattern.isUnification()).isTrue(); - - assertThat(pattern.getDescrs().size()).isEqualTo(2); - ExprConstraintDescr bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(bindingDescr.getExpression()).isEqualTo("$name := name"); - - bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); - assertThat(bindingDescr.getExpression()).isEqualTo("$loc : location"); - - } - - @Test - public void parse_BigLiterals() { - final String text = "rule X when Primitives( bigInteger == (10I), " + - " bigDecimal == (10B), " + - " bigInteger < 50I, " + - " bigDecimal < 50.2B ) then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(4); - ExprConstraintDescr ecd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); - assertThat(ecd.getExpression()).isEqualTo("bigInteger == (10I)"); - - ecd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); - assertThat(ecd.getExpression()).isEqualTo("bigDecimal == (10B)"); - - ecd = (ExprConstraintDescr) pattern.getDescrs().get( 2 ); - assertThat(ecd.getExpression()).isEqualTo("bigInteger < 50I"); - - ecd = (ExprConstraintDescr) pattern.getDescrs().get( 3 ); - assertThat(ecd.getExpression()).isEqualTo("bigDecimal < 50.2B"); - } - - @Test - public void parse_BindingComposite() throws Exception { - final String text = "rule X when Person( $name : name == \"Bob\" || $loc : location == \"Montreal\" ) then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat(pattern.isUnification()).isFalse(); - - // embedded bindings are extracted at compile time - List< ? > constraints = pattern.getDescrs(); - assertThat(constraints.size()).isEqualTo(1); - assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name == \"Bob\" || $loc : location == \"Montreal\""); - } - - @Test - public void parse_BindingCompositeWithMethods() throws Exception { - final String text = "rule X when Person( $name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\" ) then end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat(pattern.isUnification()).isFalse(); - - // embedded bindings are extracted at compile time - List< ? > constraints = pattern.getDescrs(); - assertThat(constraints.size()).isEqualTo(1); - assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\""); - } - - @Test - public void parse_PluggableOperators2() throws Exception { - final String text = "rule \"tt\"\n" + - " dialect \"mvel\"\n" + - "when\n" + - " exists (TelephoneCall( this finishes [1m] \"25-May-2011\" ))\n" + - "then\n" + - "end"; - PatternDescr pattern = (PatternDescr) ((ExistsDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 )).getDescrs().get( 0 ); - - assertThat(pattern.getObjectType()).isEqualTo("TelephoneCall"); - ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); - assertThat(constr.getText()).isEqualTo("this finishes [1m] \"25-May-2011\""); - - } - - @Test - public void parse_InlineEval() throws Exception { - final String text = "rule \"inline eval\"\n" + - "when\n" + - " Person( eval( name.startsWith(\"b\") && name.finishesWith(\"b\")) )\n" + - "then\n" + - "end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getObjectType()).isEqualTo("Person"); - ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); - assertThat(constr.getText()).isEqualToIgnoringWhitespace("eval( name.startsWith(\"b\") && name.finishesWith(\"b\"))"); - - } - - @Test - public void parse_InfinityLiteral() throws Exception { - final String text = "rule \"infinity\"\n" + - "when\n" + - " StockTick( this after[-*,*] $another )\n" + - "then\n" + - "end"; - PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getObjectType()).isEqualTo("StockTick"); - ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); - assertThat(constr.getText()).isEqualTo("this after[-*,*] $another"); - - } - - @Test - public void parse_EntryPointDeclaration() throws Exception { - final String text = "package org.drools\n" + - "declare entry-point eventStream\n" + - " @source(\"jndi://queues/events\")\n" + - " @foo( true )\n" + - "end"; - PackageDescr pkg = parser.parse( - text ); - - assertThat(pkg.getName()).isEqualTo("org.drools"); - assertThat(pkg.getEntryPointDeclarations().size()).isEqualTo(1); - - EntryPointDeclarationDescr epd = pkg.getEntryPointDeclarations().iterator().next(); - - assertThat(epd.getEntryPointId()).isEqualTo("eventStream"); - assertThat(epd.getAnnotations().size()).isEqualTo(2); - assertThat(epd.getAnnotation("source").getValue()).isEqualTo("\"jndi://queues/events\""); - assertThat(epd.getAnnotation("foo").getValue()).isEqualTo("true"); - } - - @Test - public void parse_WindowDeclaration() throws Exception { - final String text = "package org.drools\n" + - "declare window Ticks\n" + - " @doc(\"last 10 stock ticks\")\n" + - " $s : StockTick( source == \"NYSE\" )\n" + - " over window:length( 10, $s.symbol )\n" + - " from entry-point stStream\n" + - "end"; - PackageDescr pkg = parser.parse( - text ); - - assertThat(pkg.getName()).isEqualTo("org.drools"); - assertThat(pkg.getWindowDeclarations().size()).isEqualTo(1); - - WindowDeclarationDescr wdd = pkg.getWindowDeclarations().iterator().next(); - - assertThat(wdd.getName()).isEqualTo("Ticks"); - assertThat(wdd.getAnnotations().size()).isEqualTo(1); - assertThat(wdd.getAnnotation("doc").getValue()).isEqualTo("\"last 10 stock ticks\""); - - PatternDescr pd = wdd.getPattern(); - assertThat(pd).isNotNull(); - assertThat(pd.getIdentifier()).isEqualTo("$s"); - assertThat(pd.getObjectType()).isEqualTo("StockTick"); - assertThat(pd.getSource().getText()).isEqualTo("stStream"); - - assertThat(pd.getBehaviors().size()).isEqualTo(1); - BehaviorDescr bd = pd.getBehaviors().get( 0 ); - assertThat(bd.getType()).isEqualTo("window"); - assertThat(bd.getSubType()).isEqualTo("length"); - assertThat(bd.getParameters().size()).isEqualTo(2); - assertThat(bd.getParameters().get(0)).isEqualTo("10"); - assertThat(bd.getParameters().get(1)).isEqualTo("$s.symbol"); - } - - @Disabled("Priority : Mid | Implement using declared window. Not written in docs, but unit tests found.") - @Test - public void parse_WindowUsage() throws Exception { - final String text = "package org.drools\n" + - "rule X\n" + - "when\n" + - " StockTick() from window Y\n" + - "then\n" + - "end\n"; - PackageDescr pkg = parser.parse( - text ); - - assertThat(pkg.getName()).isEqualTo("org.drools"); - assertThat(pkg.getRules().size()).isEqualTo(1); - - RuleDescr rd = pkg.getRules().get(0); - - assertThat(rd.getName()).isEqualTo("X"); - assertThat(rd.getLhs().getDescrs().size()).isEqualTo(1); - - PatternDescr pd = (PatternDescr) rd.getLhs().getDescrs().get(0); - assertThat(pd).isNotNull(); - assertThat(pd.getObjectType()).isEqualTo("StockTick"); - assertThat(pd.getSource().getText()).isEqualTo("Y"); - } - - @Test - public void endInRhs() throws Exception { - final String text = "package org.drools\n" + - "rule X\n" + - "when\n" + - " $s : String()\n" + - "then\n" + - " System.out.println($s.endsWith(\"xyz\"));\n" + - "end\n"; - PackageDescr packageDescr = parser.parse(text ); - - RuleDescr ruleDescr = packageDescr.getRules().get(0); - assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("System.out.println($s.endsWith(\"xyz\"));"); - } - - @Test - public void endTokenInRhs() throws Exception { - final String text = "package org.drools\n" + - "rule X\n" + - "when\n" + - " $s : String()\n" + - "then\n" + - " int end = 10;\n" + - "end\n"; - PackageDescr packageDescr = parser.parse(text ); - - RuleDescr ruleDescr = packageDescr.getRules().get(0); - assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int end = 10;"); - } - - @Test - public void ruleTokenInRhs() throws Exception { - final String text = "package org.drools\n" + - "rule X\n" + - "when\n" + - " $s : String()\n" + - "then\n" + - " int rule = 10;\n" + - "end\n"; - PackageDescr packageDescr = parser.parse(text ); - - RuleDescr ruleDescr = packageDescr.getRules().get(0); - assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int rule = 10;"); - } -} diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml b/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml deleted file mode 100644 index 7740901e7d3..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - %date{HH:mm:ss.SSS} [%thread] %-5level %class{36}.%method:%line - %msg%n - - - - - - - - - - \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl deleted file mode 100644 index 74cff04d3c1..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler - -rule test_rule extends rule1 - when - $foo : foo() - then - -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl deleted file mode 100644 index 122634a9b26..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -package org.drools.compiler - -rule test_rule - @fooMeta1(barVal1) - @fooMeta2(barVal2) - when - then - System.out.println("Consequence"); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl deleted file mode 100644 index c009e6ec210..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler - -rule test - when - A() - ( B() and C() ) or - ( D() and E() ) or - ( F() and G() ) - then - -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl deleted file mode 100755 index 7f3f4ce75f9..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule "AccumulateParserTest" -when - Integer() from accumulate( Person( age > 21 ), - init( int x = 0; ), - action( x++; ), - result( new Integer(x) ) ); -then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl deleted file mode 100755 index 43ee672e90b..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule "AccumulateReverseParserTest" -when - Number() from accumulate( Person( $age : age > 21 ), - average( $age ) ); -then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl deleted file mode 100755 index 0557d308f43..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler - -rule "Accumulate 1" -when - accumulate( Cheese( $price : price ), - $a1 : average( $price ), - $m1 : min( $price ), - $M1 : max( $price ) // binds are optional, but it makes no sense to not have a binding in this case - ) -then - // do something -end - diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl deleted file mode 100755 index 9c146f05edb..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler - -rule "Accumulate 1" -when - accumulate( Cheese( $price : price ); - $a1 : average( $price ), - $m1 : min( $price ), - $M1 : max( $price ); // binds are optional, but it makes no sense to not have a binding in this case - $a1 > 10 && $M1 <= 100, - $m1 == 5 // inline evals - ) -then - // do something -end - diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl deleted file mode 100755 index 76872623dda..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule "AccumulateReverseParserTest" -when - Integer() from accumulate( Person( age > 21 ), - init( int x = 0; ), - action( x++; ), - reverse( x--; ), - result( new Integer(x) ) ); -then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl deleted file mode 100755 index 8d3f6828f50..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule "AccumulateMultiPatternParserTest" -when - $counter:Integer() from accumulate( $person : Person( age > 21 ) and Cheese( type == $person.likes ), - init( int x = 0; ), - action( x++; ), - result( new Integer(x) ) ); -then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl deleted file mode 100755 index 75d70816931..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule "AccumulateParserTest" -when - $counter:Integer() from accumulate( $person : Person( age > 21 ), - init( int x = 0; ), - action( x++; ), - result( new Integer(x) ) ); -then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl deleted file mode 100755 index 3696836b1f2..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -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() ), - max( $age ) ); -then -end - diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl deleted file mode 100644 index 5155aa035de..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule almost_empty - when - then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl deleted file mode 100644 index e81b1d4a18f..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -import org.drools.compiler.Person - -rule simple_rule - when - Person(name == "mark") and Cheese(type == "stilton") - Person(name == "mark") or Cheese(type == "stilton") - then - System.out.println( "Mark and Michael" ); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl deleted file mode 100644 index 48fa4c52a19..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule rule1 - auto-focus true - when - not Cheese(type == "stilton") - then - funky(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl deleted file mode 100644 index 7c48ee595b5..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler.test; - -import org.drools.compiler.Cheese; - -rule "like cheddar" - when - Cheese( $type:type ) - then - System.out.println("I like " + $type); -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl deleted file mode 100644 index 6aabea7bd1b..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler.test; - -import org.drools.compiler.Cheese; -import org.drools.compiler.Person; - -rule "Who likes Stilton" - when - Cheese($type : type == "stilton") - $person : Person( $name : name == "bob", likes == $type) - then - System.out.println( $name + " likes " + $type); -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl deleted file mode 100644 index 8259a28773c..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule simple_rule - when - ( (not Foo(x=="a") or Foo(x=="y") ) and ( Shoes() or Butt() ) ) - then -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl deleted file mode 100755 index 839e2c6c19e..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule "CollectParserTest" -when - $personList : ArrayList() from collect( Person( age > 21 ) ); -then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl deleted file mode 100755 index 146b9e46c6a..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule "CollectParserTest" -when - // below statement makes no sense, but is useful to test parsing recursiveness - $personList : ArrayList() from collect( $p : Person( age > 21 || age < 10 ) from collect( People() from $town.getPeople() ) ); -then -end - diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl deleted file mode 100644 index e46ecbe4601..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -//this starts with a comment -package foo.bar - -//and another comment - -/* -yet - another - style -*/ - -rule "test" - when - then -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl deleted file mode 100644 index b2cf4cb9c84..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl +++ /dev/null @@ -1,5 +0,0 @@ -#place your comments here - this is just a description for your own purposes. -[when]There is a Person with name of {name}=Person(name=="{name}") -[when]Person is at least {age} years old and lives in {location}=Person(age > {age}, location == "{location}") -[then]Log "{message}"=System.out.println("{message}"); -[when]Or=or diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl deleted file mode 100644 index 836a53dcd57..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - - -rule myrule - when - then - int i = 0; - i = 1; - i / 1; - i == 1; - i(i); - i = 'i'; - i.i.i; - ii; - i="i"; - ++i; - i++; - --i; - i--; - i += i; - i -= i; - i *= i; - i /= i; - int i = 5; - for(int j; j 21, $likes : likes ) - Cheese( type == $likes ) ); -then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl deleted file mode 100644 index d387cf9c647..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule "ForallParserTest" -when - forall( Person( age > 21, $likes : likes ) from $village - Cheese( type == $likes ) from $cheesery ); -then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl deleted file mode 100644 index 47f918be139..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule using_from - when - Foo() from bar.baz - Foo() from bar.baz["key"] - Foo() from bar.baz[$key] - Foo() from bar.baz[1] - Whee(bar=="baz") from whee("y") - f: Foo(la==2) from bar.la(x) - Bam() from wa() - Kah() from la.wa(42, 42.42, false, null) - Bam(a=="c") - then - whee(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl deleted file mode 100644 index 98df27bf96a..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package foo - -function String[] yourFunction(String args[]) { - baz(); -} - -rule "new rule" - - when - Something() - then - yourFunction(new String[] {"a","b","c"}); - -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl deleted file mode 100644 index 2a543650f58..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -import java.lang.String - -function String functionA(String s, Integer i) { - - foo(); - -} - -function void functionB() { - bar(); -} - - -rule something - when - then -end - -rule "one more thing" - when - then -end - - - diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl deleted file mode 100644 index ed6d45ff31f..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler.test; - -import org.drools.compiler.Cheese; - -global java.lang.String foo -global java.lang.Integer bar; - -rule baz - when - Cheese( ) - then - -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl deleted file mode 100644 index 54f5225c3e8..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -//testing 'in' operator - -rule simple_rule - when - Person(age > 30 && < 40) - Vehicle(type in ( "sedan", "wagon" ), age < 3) - then - consequence(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl deleted file mode 100644 index 3d4d2df7c75..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule simple_rule - when - foo3 : Bar(a==3) ; foo4 : Bar(a4:a==4) ; Baz() - then - if ( a == b ) { - assert( foo3 ); - } else { - retract( foo4 ); - } - System.out.println( a4 ); -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl deleted file mode 100644 index a1d01a65573..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -//check that it can handle true/false literals, and -//negative numbers -rule simple_rule - when - Foo(bar == false) - Foo(boo > -42) - Foo(boo > -42.42) - then - cons(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl deleted file mode 100644 index 92a142ec007..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl +++ /dev/null @@ -1,6 +0,0 @@ -#place your comments here - this is just a description for your own purposes. -[when]There is a Person with=Person() -[when]- age less than {age}=age < {age} -[when]- location is '{city}'=location=={city} -[when]Bar bar black sheep=Bar() -[then]Log "{message}"=System.out.println("{message}"); diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl deleted file mode 100644 index 067e55fdb9d..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler.test; - -import org.drools.integrationtests.Cheese; - -rule "Like Stilton" - when - Cheese( t:type == "stilton" ) - then - System.out.println("I like " + t); -end - -rule "Like Cheddar" - when - Cheese( t:type == "cheddar" ) - then - System.out.println("I like " + t ); -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl deleted file mode 100755 index 0b11f17c562..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule "test nested CEs" - when - not ( State( $state : state ) and - not( Person( status == $state, $likes : likes ) and - Cheese( type == $likes ) ) ) - Person( name == "Bob" ) - ( Cheese( price == 10 ) or Cheese( type == "brie" ) ) - then - results.add("OK"); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl deleted file mode 100644 index 768fa8775c8..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule rule1 - no-loop false - when - not Cheese(type == "stilton") - then - funky(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl deleted file mode 100644 index 8ec3fd4f86e..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package HR1 - -rule simple_rule - when - not ( Cheese(type == "stilton") ) - exists ( Foo() ) - then - funky(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl deleted file mode 100644 index 573fe4808d6..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler.test; - -import org.drools.compiler.Cheese; - -global java.util.List list; -global java.lang.Integer five; - -rule "not rule test" - when - $person : Person( $likes:like ) - not Cheese( type == $likes ) - then - list.add( $person ); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl deleted file mode 100644 index a2eae254405..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -//testing not 'in' operator - -rule simple_rule - when - Person(age > 30 && < 40) - Vehicle(type not in ( "sedan", "wagon" ), age < 3) - then - consequence(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl deleted file mode 100644 index 87907a60b7a..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -import org.drools.compiler.Person - -rule simple_rule - when - foo : ( Person(name == "mark") or Person(type == "fan") ) - Cheese(type == "green") - then - System.out.println( "Mark and Michael" + bar ); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl deleted file mode 100644 index 2090d8f8565..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - - -rule simple_rule - when - foo : ( Person(name == "mark") - or - Person(type == "fan") ) - then - System.out.println( "Mark and Michael" + bar ); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl deleted file mode 100644 index a96bae49029..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule simple_rule - when - foo : ( - Person(name == "mark") or Person(type == "fan") - ) - then - System.out.println( "Mark and Michael" + bar ); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl deleted file mode 100644 index 3e576f091a8..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler - -rule "testing OR CE" -when - $p : Person( name == "bob" ) - $c : Cheese( type == $p.likes ) or Cheese( price == 10 ) -then - // do something -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl deleted file mode 100644 index ecf9ddb2338..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -import org.drools.compiler.Person - -rule simple_rule - when - Person(name == "mark") or - ( Person(type == "fan") and Cheese(type == "green") ) - then - System.out.println( "Mark and Michael" + bar ); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl deleted file mode 100644 index 156f5c58f6d..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package com.foo; - -agenda-group "x" - -import goo.ber -import wee.waa - - -dialect "java" - - - - -rule bar - when - then -end - -rule baz - dialect "mvel" - when - then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl deleted file mode 100644 index 59c31d2c8e7..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler - -rule "test pluggable operators" -when - $a : EventA() - $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 ) -then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl deleted file mode 100644 index 9347834bbbb..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler.test; - -rule "Who likes Stilton" - when - com.cheeseco.Cheese($type : type == "stilton") - then - System.out.println( $name + " likes " + $type); -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl deleted file mode 100644 index e9b9be3edd2..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -package foo - -rule bar - when - Baz() - then - Boo() -end - -query "simple_query" - foo3 : Bar(a==3) - foo4 : Bar(a4:a==4) - Baz() - -end - -rule bar2 - when - Baz() - then - Boo() -end - -query "simple_query2" - foo3 : Bar(a==3) - foo4 : Bar(a4:a==4) - Baz() - -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl deleted file mode 100644 index 9eda0358e56..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule "quoted string name" - when - then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl deleted file mode 100644 index edf674db5ed..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -//this is for showing off all the new multi restriction stuff - -rule simple_rule - when - Person(age > 30 && < 40) - Vehicle(type == "sedan" || == "wagon", age < 3) - then - consequence(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl deleted file mode 100644 index faf0d0c3351..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - - - -rule simple_rule - // attributes keywork (and colon) is totally optional - salience 42 - agenda-group "my_group" - no-loop - duration 42 - activation-group "my_activation_group" - lock-on-active true - when - Foo() - then - bar(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl deleted file mode 100644 index cece840aa59..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package foo.bar - - -rule rule1 - salience (42) - agenda-group "my_group" - when - Foo() - then - bar(); -end - -rule rule2 - salience (Integer.MIN_VALUE) - no-loop - when - Foo() - then - bar(); -end - -rule rule3 - enabled (Boolean.TRUE) - activation-group "my_activation_group" - when - Foo() - then - bar(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl deleted file mode 100644 index fafc7032171..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - - - -rule simple_rule - attributes: - salience 42, agenda-group "my_group", no-loop, lock-on-active, duration 42, activation-group "my_activation_group" - when - Foo() - then - bar(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl deleted file mode 100644 index 2605f494aa9..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule simple_rule - calendars "cal1" - lock-on-active true - when - Foo() - then - bar(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl deleted file mode 100644 index 31040f9e95f..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule simple_rule - calendars "cal 1", "cal 2", "cal 3" - lock-on-active true - when - Foo() - then - bar(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl deleted file mode 100644 index c0ca3ba4430..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule simple_rule - duration ( 1h30m ) - lock-on-active true - when - Foo() - then - bar(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl deleted file mode 100644 index 12550c159c7..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule simple_rule - enabled ( 1 + 1 == 2 ) - salience ( 1+2 ) - lock-on-active true - when - Foo() - then - bar(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl deleted file mode 100644 index cd14e5699a6..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule "1. Do Stuff!" - when - then -end - -rule "2. Do More Stuff!" - when - then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl deleted file mode 100644 index 96a2448ca41..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule simple_rule - when - not Cheese(type == "stilton") - then - funky(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl deleted file mode 100755 index 8b48eea0fe9..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule rule1 - ruleflow-group "a group" - when - not Cheese(type == "stilton") - then - funky(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl deleted file mode 100644 index 7d25f230e25..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.mvel.compiler - -global java.util.List list; - -rule "rule1" -when - Pattern1(); - Pattern2() from x.y.z; -then - System.out.println("Test"); -end; - -query "query1" - Pattern5(); - Pattern6(); - Pattern7(); -end; - -rule "rule2" -when - Pattern3(); - Pattern4() from collect( Pattern5() ); -then - System.out.println("Test"); -end; - diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl deleted file mode 100644 index 2532abc0b6c..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - - -query "simple_query" - foo3 : Bar(a==3) - foo4 : Bar(a4:a==4) - Baz() - -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl deleted file mode 100644 index afc7e6480b0..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ -rule simple_rule - when - foo3 : Bar(a==3) - foo4 : Bar(a4:a==4) - Baz() - then - if ( a == b ) { - assert( foo3 ); - } else { - retract( foo4 ); - } - System.out.println( a4 ); -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl deleted file mode 100644 index 0b6c21d5bc4..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package nesting; - - - - -rule "test something" - - when - p: Person( name soundslike "Michael" ) - then - p.name = "goober" - System.out.println(p.name) -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl deleted file mode 100644 index 4b0b93995d1..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -package com.foo; - -import im.one - -import im.two - -rule foo - when - then -end - -function cheeseIt() { - -} - -import im.three; - -rule bar - when - then -end - -function uncheeseIt() { - -} - -import im.four; \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl deleted file mode 100644 index 23013d6b5d2..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package foo - -rule rule_one - when - Foo() - then - if (speed > speedLimit ? true : false;) - pullEmOver(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl deleted file mode 100644 index 7c7df07bd51..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package la - - -rule simple_rule - when - Baz() - then - //woot - first; - - // - - /* lala - - */ - second; -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl deleted file mode 100755 index 4c50536c900..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -rule blah - when - Col1() from doIt1( foo,bar,42,"hello",[ a : "b"], [a, "b", 42] ).doIt2(bar, [a, "b", 42]).field["key"] - Col2() - then - partay(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl deleted file mode 100644 index de85f100561..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler.test; - -import org.drools.compiler.Cheese; - -rule "simple rule" - when - Cheese( ) - then -end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl deleted file mode 100644 index f867e69fe2d..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - - - -rule simple_rule - when - Foo( - bar == baz, la==laz - ) - then -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl deleted file mode 100644 index 1b56f045643..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package HR1 - -import function abd.def.x -import function qed.wah.* - -rule simple_rule - when - not ( Cheese(type == "stilton") ) - exists ( Foo() ) - then - funky(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl deleted file mode 100644 index 2bf358046e0..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule blah - - when - - Col1() from something.doIt["key"] - Col2() - then - partay(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl deleted file mode 100644 index da376e84385..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule blah - - when - - Col1() from something.doIt - Col2() - then - partay(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl deleted file mode 100644 index af156c5ea1c..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule blah - - when - - Col1() from doIt( foo,bar,42,"hello",[ a : "b", "something" : 42, "a" : foo, x : [x:y]],"end", [a, "b", 42] ) - Col2() - then - partay(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl deleted file mode 100644 index a8e32df1d53..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule blah - - when - - Col1() from something.doIt( foo,bar,42,"hello",[ a : "b", "something" : 42, "a" : foo, x : [x:y]],"end", [a, "b", 42] ) - Col2() - then - partay(); -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl deleted file mode 100644 index 708bd667b0a..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - -package org.drools.compiler - -declare NetworkNode - locElevation: java.math.BigDecimal - name: String @key - nodeClass: String - locLongitude: java.math.BigDecimal - nodeType: String - locLatitude: java.math.BigDecimal -end - -declare NetworkConnection - id: String @key - node1: NetworkNode - node2: NetworkNode - hops: Integer -end - -declare NetworkEvent - @role( event ) - @timestamp( creationTime ) - - id: String @key - locElevation: java.math.BigDecimal - description: String - sourceComponent: NetworkNode - locLongitude: java.math.BigDecimal - severity: Integer - creationTime: java.util.Date - locLatitude: java.math.BigDecimal -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl deleted file mode 100644 index c2e0145747d..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule simple_rule - when - Foo() - Bar() - eval(abc("foo")) - then - Kapow -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl deleted file mode 100644 index 41ff2715d8a..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule simple_rule - when - Person( $age2:age, $age2 == $age1+2 ) - then -end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl deleted file mode 100644 index 8db9671fee7..00000000000 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations - * under the License. - */ - - -rule simple_rule - when - Foo(name== (a + b)) - then -end diff --git a/drools-drl/drools-drl-parser/pom.xml b/drools-drl/drools-drl-parser/pom.xml index 0eeb7871009..545625e5ad4 100644 --- a/drools-drl/drools-drl-parser/pom.xml +++ b/drools-drl/drools-drl-parser/pom.xml @@ -66,32 +66,7 @@ org.antlr antlr-runtime - - org.antlr - antlr4-runtime - - - - org.assertj - assertj-core - test - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - ch.qos.logback - logback-classic - test - @@ -126,26 +101,6 @@ - - - - org.antlr - antlr4-maven-plugin - ${version.org.antlr4} - - - - antlr4 - - - true - false - src/main/antlr4/org/drools/drl10/parser/ - - - - - diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 deleted file mode 100644 index ef6e0982672..00000000000 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 +++ /dev/null @@ -1,847 +0,0 @@ -parser grammar DRL6Expressions; - -options { - language = Java; - tokenVocab = DRLLexer; - superClass=DRLExpressions; -} - -@header { - import java.util.LinkedList; - import org.drools.drl.parser.DroolsParserException; - import org.drools.drl.parser.lang.DroolsEditorType; - import org.drools.drl.parser.lang.DroolsParserExceptionFactory; - import org.drools.drl.parser.lang.DroolsSentence; - import org.drools.drl.parser.lang.DroolsSoftKeywords; - import org.drools.drl.parser.lang.Location; - - import org.drools.drl.ast.dsl.AnnotatedDescrBuilder; - import org.drools.drl.ast.dsl.AnnotationDescrBuilder; - - import org.drools.drl.ast.descr.AnnotatedBaseDescr; - import org.drools.drl.ast.descr.AnnotationDescr; - import org.drools.drl.ast.descr.AtomicExprDescr; - import org.drools.drl.ast.descr.BaseDescr; - import org.drools.drl.ast.descr.BindingDescr; - import org.drools.drl.ast.descr.ConstraintConnectiveDescr; - import org.drools.drl.ast.descr.RelationalExprDescr; -} - -@members { - private ParserHelper helper; - - public DRL6Expressions(TokenStream input, - ParserHelper helper ) { - this( input ); - this.helper = helper; - } - - public ParserHelper getHelper() { return helper; } - public boolean hasErrors() { return helper.hasErrors(); } - public List getErrors() { return helper.getErrors(); } - public List getErrorMessages() { return helper.getErrorMessages(); } - public void enableEditorInterface() { helper.enableEditorInterface(); } - public void disableEditorInterface() { helper.disableEditorInterface(); } - public LinkedList getEditorInterface() { return helper.getEditorInterface(); } - public void reportError(RecognitionException ex) { helper.reportError( ex ); } - public void emitErrorMessage(String msg) {} - - private boolean buildDescr; - private int inMap = 0; - private int ternOp = 0; - private boolean hasBindings; - public void setBuildDescr( boolean build ) { this.buildDescr = build; } - public boolean isBuildDescr() { return this.buildDescr; } - - public void setLeftMostExpr( String value ) { helper.setLeftMostExpr( value ); } - public String getLeftMostExpr() { return helper.getLeftMostExpr(); } - - public void setHasBindings( boolean value ) { this.hasBindings = value; } - public boolean hasBindings() { return this.hasBindings; } - - @Override - public final BaseDescr conditionalOrExpressionDescr() throws RecognitionException { - return conditionalOrExpression().result; - } - - private boolean isNotEOF() { - // TODO verify that we can omit the backtracking check - /*if (state.backtracking != 0){ - return false; - }*/ - if (_input.get( _input.index() - 1 ).getType() == DRLLexer.WS){ - return true; - } - if (_input.LA(-1) == DRLLexer.LPAREN){ - return true; - } - return _input.get( _input.index() ).getType() != DRLLexer.EOF; - } - - private boolean notStartWithNewline() { - int currentTokenIndex = _input.index(); // current position in input stream - Token previousHiddenToken = _input.get(currentTokenIndex - 1); - String previousHiddenTokenText = previousHiddenToken.getText(); - return !previousHiddenTokenText.contains("\n"); - } -} - -// Alter code generation so catch-clauses get replace with -// this action. -@rulecatch { -catch (RecognitionException re) { - throw re; -} -} - -// -------------------------------------------------------- -// GENERAL RULES -// -------------------------------------------------------- -literal - : STRING_LITERAL { helper.emit($STRING_LITERAL, DroolsEditorType.STRING_CONST); } - | DRL_STRING_LITERAL { helper.emit($DRL_STRING_LITERAL, DroolsEditorType.STRING_CONST); } - | DECIMAL_LITERAL { helper.emit($DECIMAL_LITERAL, DroolsEditorType.NUMERIC_CONST); } - | HEX_LITERAL { helper.emit($HEX_LITERAL, DroolsEditorType.NUMERIC_CONST); } - | FLOAT_LITERAL { helper.emit($FLOAT_LITERAL, DroolsEditorType.NUMERIC_CONST); } - | BOOL_LITERAL { helper.emit($BOOL_LITERAL, DroolsEditorType.BOOLEAN_CONST); } - | NULL_LITERAL { helper.emit($NULL_LITERAL, DroolsEditorType.NULL_CONST); } - | TIME_INTERVAL { helper.emit($TIME_INTERVAL, DroolsEditorType.NULL_CONST); } - | MUL { helper.emit($MUL, DroolsEditorType.NUMERIC_CONST); } // this means "infinity" in Drools - ; - -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 ); } } - : 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); } - | rop=relationalOp { $negated = $rop.negated; $opr=($x != null ? $x.text : "")+$rop.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 ); } } - : ( 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);} - | op=GT { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} - | xop=complexOp { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} - | not_key nop=neg_operator_key { $negated = true; $opr=$nop.text;} - | cop=operator_key { $negated = false; $opr=$cop.text;} - ) - ; - -complexOp returns [String opr] - : t=TILDE e=ASSIGN { $opr=$t.text+$e.text; } - ; - -typeList - : type (COMMA type)* - ; - -type - : tm=typeMatch - ; - -typeMatch - : primitiveType (LBRACK RBRACK)* - | IDENTIFIER (typeArguments)? (DOT IDENTIFIER (typeArguments)? )* (LBRACK RBRACK)* - ; - -typeArguments - : LT typeArgument (COMMA typeArgument)* GT - ; - -typeArgument - : type - | QUESTION ((extends_key | super_key) type)? - ; - -// -------------------------------------------------------- -// EXPRESSIONS -// -------------------------------------------------------- -// the following dymmy rule is to force the AT symbol to be -// included in the follow set of the expression on the DFAs -dummy - : expression ( AT | SEMI | EOF | IDENTIFIER | RPAREN ) ; - -dummy2 - : relationalExpression EOF; - -// top level entry point for arbitrary expression parsing -expression returns [BaseDescr result] - : left=conditionalExpression { if( buildDescr ) { $result = $left.result; } } - (op=assignmentOperator right=expression)? - ; - -conditionalExpression returns [BaseDescr result] - : left=conditionalOrExpression { if( buildDescr ) { $result = $left.result; } } - ternaryExpression? - ; - -ternaryExpression -@init{ ternOp++; } - : QUESTION ts=expression COLON fs=expression - ; -finally { ternOp--; } - - -fullAnnotation [AnnotatedDescrBuilder inDescrBuilder] returns [AnnotationDescr result] -@init{ String n = ""; AnnotationDescrBuilder annoBuilder = null; } - : AT name=IDENTIFIER { n = $name.text; } ( DOT x=IDENTIFIER { n += "." + $x.text; } )* - { if( buildDescr ) { - if ( inDescrBuilder == null ) { - $result = new AnnotationDescr( n ); - } else { - annoBuilder = inDescrBuilder instanceof AnnotationDescrBuilder ? - ((AnnotationDescrBuilder) inDescrBuilder).newAnnotation( n ) : inDescrBuilder.newAnnotation( n ); - $result = (AnnotationDescr) annoBuilder.getDescr(); - } - } - } - annotationArgs[$result, annoBuilder] - ; - -annotationArgs [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] - : LPAREN - ( - annotationElementValuePairs[descr, inDescrBuilder] - | value=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setValue( $value.result ); } } - )? - RPAREN - ; - -annotationElementValuePairs [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] - : annotationElementValuePair[descr, inDescrBuilder] ( COMMA annotationElementValuePair[descr, inDescrBuilder] )* - ; - -annotationElementValuePair [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] - : key=IDENTIFIER ASSIGN val=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setKeyValue( $key.text, $val.result ); } } - ; - -annotationValue[AnnotatedDescrBuilder inDescrBuilder] returns [Object result] - : exp=expression { if ( buildDescr ) $result = $exp.text; } - | annos=annotationArray[inDescrBuilder] { if ( buildDescr ) $result = $annos.result.toArray(); } - | anno=fullAnnotation[inDescrBuilder] { if ( buildDescr ) $result = $anno.result; } - ; - -annotationArray[AnnotatedDescrBuilder inDescrBuilder] returns [java.util.List result] -@init { $result = new java.util.ArrayList();} - : LBRACE ( anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } - ( COMMA anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } )* )? - RBRACE - ; - - - -conditionalOrExpression returns [BaseDescr result] - : left=conditionalAndExpression { if( buildDescr ) { $result = $left.result; } } - ( OR - { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } - args=fullAnnotation[null]? right=conditionalAndExpression - { if( buildDescr ) { - ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newOr(); - descr.addOrMerge( $result ); - descr.addOrMerge( $right.result ); - if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } - $result = descr; - } - } - )* - ; - -conditionalAndExpression returns [BaseDescr result] - : left=inclusiveOrExpression { if( buildDescr ) { $result = $left.result; } } - ( AND - { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } - args=fullAnnotation[null]? right=inclusiveOrExpression - { if( buildDescr ) { - ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newAnd(); - descr.addOrMerge( $result ); - descr.addOrMerge( $right.result ); - if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } - $result = descr; - } - } - )* - ; - -inclusiveOrExpression returns [BaseDescr result] - : left=exclusiveOrExpression { if( buildDescr ) { $result = $left.result; } } - ( BITOR right=exclusiveOrExpression - { if( buildDescr ) { - ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newIncOr(); - descr.addOrMerge( $result ); - descr.addOrMerge( $right.result ); - $result = descr; - } - } - )* - ; - -exclusiveOrExpression returns [BaseDescr result] - : left=andExpression { if( buildDescr ) { $result = $left.result; } } - ( CARET right=andExpression - { if( buildDescr ) { - ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newXor(); - descr.addOrMerge( $result ); - descr.addOrMerge( $right.result ); - $result = descr; - } - } - )* - ; - -andExpression returns [BaseDescr result] - : left=equalityExpression { if( buildDescr ) { $result = $left.result; } } - ( BITAND right=equalityExpression - { if( buildDescr ) { - ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newIncAnd(); - descr.addOrMerge( $result ); - descr.addOrMerge( $right.result ); - $result = descr; - } - } - )* - ; - -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 ); } - right=instanceOfExpression - { if( buildDescr ) { - $result = new RelationalExprDescr( $op.text, false, null, $left.result, $right.result ); - } - } - )* - ; - -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 ); } - right=type - { if( buildDescr ) { - $result = new RelationalExprDescr( $op.text, false, null, $left.result, new AtomicExprDescr($right.text) ); - } - } - )? - ; - -inExpression returns [BaseDescr result] -@init { ConstraintConnectiveDescr descr = null; BaseDescr leftDescr = null; BindingDescr binding = null; } -@after { if( binding != null && descr != null ) descr.addOrMerge( binding ); } - : left=relationalExpression - { if( buildDescr ) { $result = $left.result; } - if( $left.result instanceof BindingDescr ) { - binding = (BindingDescr)$left.result; - leftDescr = new AtomicExprDescr( binding.getExpression() ); - } else { - leftDescr = $left.result; - } - } - (not_key in=in_key LPAREN - { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } - e1=expression - { descr = ConstraintConnectiveDescr.newAnd(); - RelationalExprDescr rel1 = new RelationalExprDescr( "!=", false, null, leftDescr, $e1.result ); - descr.addOrMerge( rel1 ); - $result = descr; - } - (COMMA e2=expression - { RelationalExprDescr rel2 = new RelationalExprDescr( "!=", false, null, leftDescr, $e2.result ); - descr.addOrMerge( rel2 ); - } - )* RPAREN - { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } - | in=in_key LPAREN - { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } - e1=expression - { descr = ConstraintConnectiveDescr.newOr(); - RelationalExprDescr rel1 = new RelationalExprDescr( "==", false, null, leftDescr, $e1.result ); - descr.addOrMerge( rel1 ); - $result = descr; - } - (COMMA e2=expression - { RelationalExprDescr rel2 = new RelationalExprDescr( "==", false, null, leftDescr, $e2.result ); - descr.addOrMerge( rel2 ); - } - )* RPAREN - { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } - )? - ; - -relationalExpression returns [BaseDescr result] -locals [ BaseDescr lsd ] -// TODO access lsd directly instead of through dynamic context here -@init { $relationalExpression::lsd = null; } - : left=shiftExpression - { if( buildDescr ) { - if ( $left.result == null ) { - $result = new AtomicExprDescr( $left.text ); - } else if ( $left.result instanceof AtomicExprDescr ) { - if ( $left.text.equals(((AtomicExprDescr)$left.result).getExpression()) ) { - $result = $left.result; - } else { - $result = new AtomicExprDescr( $left.text ) ; - } - } else if ( $left.result instanceof BindingDescr ) { - if ( $left.text.equals(((BindingDescr)$left.result).getExpression()) ) { - $result = $left.result; - } else { - BindingDescr bind = (BindingDescr) $left.result; - int offset = bind.isUnification() ? 2 : 1; - String fullExpression = $left.text.substring( $left.text.indexOf( ":" ) + offset ).trim(); - $result = new BindingDescr( bind.getVariable(), bind.getExpression(), fullExpression, bind.isUnification() ); - } - } else { - $result = $left.result; - } - // TODO access lsd directly instead of through dynamic context here - $relationalExpression::lsd = $result; - } - } - ( right=orRestriction - { if( buildDescr ) { - $result = $right.result; - // TODO access lsd directly instead of through dynamic context here - $relationalExpression::lsd = $result; - } - } - )* - ; - -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 ); } - ( sa=squareArguments value=shiftExpression - | value=shiftExpression - ) - { if( buildDescr ) { - BaseDescr descr = ( $value.result != null && - ( (!($value.result instanceof AtomicExprDescr)) || - ($value.text.equals(((AtomicExprDescr)$value.result).getExpression())) )) ? - $value.result : - new AtomicExprDescr( $value.text ) ; - $result = new RelationalExprDescr( $op.opr, $op.negated, $ctx.sa != null ? $sa.args : null, $relationalExpression::lsd, descr ); - if( $relationalExpression::lsd instanceof BindingDescr ) { - $relationalExpression::lsd = new AtomicExprDescr( ((BindingDescr)$relationalExpression::lsd).getExpression() ); - } - } - helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); - } - | LPAREN or=orRestriction RPAREN { $result = $or.result; } - ; - - - -shiftExpression returns [BaseDescr result] - : left=additiveExpression { if( buildDescr ) { $result = $left.result; } } - ( shiftOp additiveExpression )* - ; - -shiftOp - : ( LT LT - | GT GT GT - | GT GT ) - ; - -additiveExpression returns [BaseDescr result] - : left=multiplicativeExpression { if( buildDescr ) { $result = $left.result; } } - ( (ADD | SUB) multiplicativeExpression )* - ; - -multiplicativeExpression returns [BaseDescr result] - : left=unaryExpression { if( buildDescr ) { $result = $left.result; } } - ( ( MUL | DIV | MOD ) unaryExpression )* - ; - -unaryExpression returns [BaseDescr result] - : ADD ue=unaryExpression - { if( buildDescr ) { - $result = $ue.result; - if( $result instanceof AtomicExprDescr ) { - ((AtomicExprDescr)$result).setExpression( "+" + ((AtomicExprDescr)$result).getExpression() ); - } - } } - | SUB ue=unaryExpression - { if( buildDescr ) { - $result = $ue.result; - if( $result instanceof AtomicExprDescr ) { - ((AtomicExprDescr)$result).setExpression( "-" + ((AtomicExprDescr)$result).getExpression() ); - } - } } - | INC primary - | DEC primary - | left=unaryExpressionNotPlusMinus { if( buildDescr ) { $result = $left.result; } } - ; - -unaryExpressionNotPlusMinus returns [BaseDescr result] -@init { boolean isLeft = false; BindingDescr bind = null;} - : TILDE unaryExpression - | BANG ue=unaryExpression - { - if( buildDescr && $ue.result != null ) { - $result = $ue.result.negate(); - } - } - | castExpression - | backReferenceExpression - | { isLeft = helper.getLeftMostExpr() == null;} - ( ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.COLON}? (var=IDENTIFIER COLON - { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($COLON, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, false); helper.setStart( bind, $var ); } } )) - | ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.DRL_UNIFY}? (var=IDENTIFIER DRL_UNIFY - { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($DRL_UNIFY, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, true); helper.setStart( bind, $var ); } } )) - )? - - ( left2=xpathPrimary { if( buildDescr ) { $result = $left2.result; } } - | left1=primary { if( buildDescr ) { $result = $left1.result; } } - ) - - (selector)* - { - if( buildDescr ) { - String expr = $text; - if( isLeft ) { - helper.setLeftMostExpr( expr ); - } - if( bind != null ) { - if( bind.isUnification() ) { - expr = expr.substring( expr.indexOf( ":=" ) + 2 ).trim(); - } else { - expr = expr.substring( expr.indexOf( ":" ) + 1 ).trim(); - } - bind.setExpressionAndBindingField( expr ); - helper.setEnd( bind ); - $result = bind; - } - } - } - ((INC|DEC))? - ; - -castExpression - : LPAREN primitiveType RPAREN expr=unaryExpression - | LPAREN type RPAREN unaryExpressionNotPlusMinus - ; - -backReferenceExpression - : (DOT DOT DIV)+ unaryExpressionNotPlusMinus - ; - -primitiveType - : boolean_key - | char_key - | byte_key - | short_key - | int_key - | long_key - | float_key - | double_key - ; - -xpathSeparator - : DIV - | QUESTION_DIV - ; - -xpathPrimary returns [BaseDescr result] - : xpathChunk ({notStartWithNewline()}? xpathChunk)* - ; - -xpathChunk returns [BaseDescr result] - : xpathSeparator IDENTIFIER (DOT IDENTIFIER)* (HASH IDENTIFIER)? (LBRACK xpathExpressionList RBRACK)? - ; - -xpathExpressionList returns [java.util.List exprs] -@init { $exprs = new java.util.ArrayList();} - : f=expression { $exprs.add( $f.text ); } - (COMMA s=expression { $exprs.add( $s.text ); })* - ; - -primary returns [BaseDescr result] - : expr=parExpression { if( buildDescr ) { $result = $expr.result; } } - | nonWildcardTypeArguments (explicitGenericInvocationSuffix | this_key arguments) - | literal { if( buildDescr ) { $result = new AtomicExprDescr( $literal.text, true ); } } - //| this_key ({!helper.validateSpecialID(2)}? DOT IDENTIFIER)* ({helper.validateIdentifierSufix()}? identifierSuffix)? - | super_key superSuffix - | new_key creator - | primitiveType (LBRACK RBRACK)* DOT class_key - //| void_key DOT class_key - | inlineMapExpression - | inlineListExpression - | i1=IDENTIFIER { helper.emit($i1, DroolsEditorType.IDENTIFIER); } - ( - ( d=DOT i2=IDENTIFIER { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) - | - ( d=(DOT|NULL_SAFE_DOT) LPAREN { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($LPAREN, DroolsEditorType.SYMBOL); } - expression (COMMA { helper.emit($COMMA, DroolsEditorType.SYMBOL); } expression)* - RPAREN { helper.emit($RPAREN, DroolsEditorType.SYMBOL); } - ) - | - ( h=HASH i2=IDENTIFIER { helper.emit($h, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) - | - ( n=NULL_SAFE_DOT i2=IDENTIFIER { helper.emit($n, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) - )* (identifierSuffix)? - ; - -inlineListExpression - : LBRACK expressionList? RBRACK - ; - -inlineMapExpression -@init{ inMap++; } - : LBRACK mapExpressionList RBRACK - ; -finally { inMap--; } - -mapExpressionList - : mapEntry (COMMA mapEntry)* - ; - -mapEntry - : expression COLON expression - ; - -parExpression returns [BaseDescr result] - : LPAREN expr=expression RPAREN - { if( buildDescr ) { - $result = $expr.result; - if( $result instanceof AtomicExprDescr ) { - ((AtomicExprDescr)$result).setExpression("(" +((AtomicExprDescr)$result).getExpression() + ")" ); - } - } - } - ; - -identifierSuffix - : (LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } - RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } )+ - DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } class_key - | (LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } - expression - RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } )+ // can also be matched by selector, but do here - | arguments -// | DOT class_key -// | DOT explicitGenericInvocation -// | DOT this_key -// | DOT super_key arguments -// | DOT new_key (nonWildcardTypeArguments)? innerCreator - ; - -creator - : nonWildcardTypeArguments? createdName - (arrayCreatorRest | classCreatorRest) - ; - -createdName - : IDENTIFIER typeArguments? - ( DOT IDENTIFIER typeArguments?)* - | primitiveType - ; - -innerCreator - : {!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? IDENTIFIER classCreatorRest - ; - -arrayCreatorRest - : LBRACK - ( RBRACK (LBRACK RBRACK)* arrayInitializer - | expression RBRACK ({!helper.validateLT(2,"]")}? LBRACK expression RBRACK)* (LBRACK RBRACK)* - ) - ; - -variableInitializer - : arrayInitializer - | expression - ; - -arrayInitializer - : LBRACE (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RBRACE - ; - -classCreatorRest - : arguments //classBody? //sotty: restored classBody to allow for inline, anonymous classes - ; - -explicitGenericInvocation - : nonWildcardTypeArguments arguments - ; - -nonWildcardTypeArguments - : LT typeList GT - ; - -explicitGenericInvocationSuffix - : super_key superSuffix - | IDENTIFIER arguments - ; - -selector - : DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } super_key superSuffix - | DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } new_key (nonWildcardTypeArguments)? innerCreator - | DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } - IDENTIFIER { helper.emit($IDENTIFIER, DroolsEditorType.IDENTIFIER); } - (arguments)? - | NULL_SAFE_DOT { helper.emit($NULL_SAFE_DOT, DroolsEditorType.SYMBOL); } - IDENTIFIER { helper.emit($IDENTIFIER, DroolsEditorType.IDENTIFIER); } - (arguments)? - //| DOT this_key - | LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } - expression - RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } - ; - -superSuffix - : arguments - | DOT IDENTIFIER (arguments)? - ; - -squareArguments returns [java.util.List args] - : LBRACK (el=expressionList { $args = $el.exprs; })? RBRACK - ; - -arguments - : LPAREN { helper.emit($LPAREN, DroolsEditorType.SYMBOL); } - expressionList? - RPAREN { helper.emit($RPAREN, DroolsEditorType.SYMBOL); } - ; - -expressionList returns [java.util.List exprs] -@init { $exprs = new java.util.ArrayList();} - : f=expression { $exprs.add( $f.text ); } - (COMMA s=expression { $exprs.add( $s.text ); })* - ; - -assignmentOperator - : ASSIGN - | ADD_ASSIGN - | SUB_ASSIGN - | MUL_ASSIGN - | DIV_ASSIGN - | AND_ASSIGN - | OR_ASSIGN - | XOR_ASSIGN - | MOD_ASSIGN - | LT LT ASSIGN - | GT GT GT ASSIGN - | GT GT ASSIGN - ; - -// -------------------------------------------------------- -// KEYWORDS -// -------------------------------------------------------- -extends_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.EXTENDS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -super_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.SUPER))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -instanceof_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -boolean_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.BOOLEAN))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -char_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.CHAR))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -byte_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.BYTE))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -short_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.SHORT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -int_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.INT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -float_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.FLOAT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -long_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.LONG))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -double_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.DOUBLE))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -void_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.VOID))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -this_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.THIS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -class_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.CLASS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -new_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.NEW))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -not_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.NOT))}? id=DRL_NOT { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -in_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.IN))}? id=DRL_IN { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -operator_key - // TODO get rid of the DRL_MATCHES token or introduce DRL_CONTAINS etc. for consistency. - : {(helper.isPluggableEvaluator(false))}? id=(IDENTIFIER|DRL_MATCHES) { helper.emit($id, DroolsEditorType.KEYWORD); } - ; - -neg_operator_key - : {(helper.isPluggableEvaluator(true))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } - ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 deleted file mode 100644 index 8aac81873cc..00000000000 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 +++ /dev/null @@ -1,161 +0,0 @@ -lexer grammar DRLLexer; - -import JavaLexer; - -@members { - public String normalizeString( String input ) { - if( input != null && (input.length() == 2 || input.length() >= 4) ) { - input = input.substring( 1, input.length() - 1 ); - input = input.replaceAll( "\'", "'" ); - input = input.replaceAll( "\"", "\\\"" ); - input = "\"" + input + "\""; - } - return input; - } -} - -///////////////// -// KEYWORDS -///////////////// - -// These keywords are already declared in JavaLexer. They should not be overriden with different names, or else Vocabulary's literalName will be null. -// So no need to declare by DRLLexer -// PACKAGE : 'package'; -// IMPORT : 'import'; -// STATIC : 'static'; -// EXTENDS : 'extends'; -// SUPER : 'super'; - -// DRL keywords -DRL_UNIT : 'unit'; -DRL_FUNCTION : 'function'; -DRL_GLOBAL : 'global'; -DRL_DECLARE : 'declare'; -DRL_RULE : 'rule'; -DRL_QUERY : 'query'; -DRL_WHEN : 'when'; -DRL_THEN : 'then' -> pushMode(RHS); -DRL_END : 'end'; - -DRL_AND : 'and'; -DRL_OR : 'or'; - -DRL_EXISTS : 'exists'; -DRL_NOT : 'not'; -DRL_IN : 'in'; -DRL_FROM : 'from'; -DRL_COLLECT : 'collect'; -DRL_MATCHES : 'matches'; -DRL_MEMBEROF : 'memberOf'; -DRL_ACCUMULATE : 'accumulate'; -DRL_ACC : 'acc'; -DRL_INIT : 'init'; -DRL_ACTION : 'action'; -DRL_REVERSE : 'reverse'; -DRL_RESULT : 'result'; -DRL_ENTRY_POINT : 'entry-point'; -DRL_EVAL : 'eval'; -DRL_FORALL : 'forall'; -DRL_OVER : 'over'; - -// temporal operators -DRL_AFTER : 'after'; -DRL_BEFORE : 'before'; -DRL_COINCIDES : 'coincides'; -DRL_DURING : 'during'; -DRL_INCLUDES : 'includes'; -DRL_FINISHES : 'finishes'; -DRL_FINISHED_BY : 'finishedby'; -DRL_MEETS : 'meets'; -DRL_MET_BY : 'metby'; -DRL_OVERLAPS : 'overlaps'; -DRL_OVERLAPPED_BY : 'overlappedby'; -DRL_STARTS : 'starts'; -DRL_STARTED_BY : 'startedby'; - -DRL_WINDOW : 'window'; - -// attributes -DRL_SALIENCE : 'salience'; -DRL_ENABLED : 'enabled'; -DRL_NO_LOOP : 'no-loop'; -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'; -DRL_DATE_EXPIRES : 'date-expires'; -DRL_DIALECT : 'dialect'; -DRL_CALENDARS : 'calendars'; -DRL_TIMER : 'timer'; -DRL_DURATION : 'duration'; - -///////////////// -// LEXER -///////////////// - -TIME_INTERVAL - : (('0'..'9')+ 'd') (('0'..'9')+ 'h')?(('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? - | (('0'..'9')+ 'h') (('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? - | (('0'..'9')+ 'm') (('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? - | (('0'..'9')+ 's') (('0'..'9')+ 'ms'?)? - | (('0'..'9')+ 'ms') - ; - -DRL_STRING_LITERAL - : ('"' ( DrlEscapeSequence | ~('\\'|'"') )* '"') - | ('\'' ( DrlEscapeSequence | ~('\\'|'\'') )* '\'') { setText( normalizeString( getText() ) ); } - ; - -DRL_BIG_DECIMAL_LITERAL - : ('0'..'9')+ [B] - | ('0'..'9')+ '.' ('0'..'9')+ [B] - ; - -DRL_BIG_INTEGER_LITERAL - : ('0'..'9')+ [I] - ; - -///////////////// -// SYMBOLS -///////////////// - -HASH : '#'; -DRL_UNIFY : ':=' ; -NULL_SAFE_DOT : '!.' ; -QUESTION_DIV : '?/' ; - -MISC : '\'' | '\\' | '$' ; - -///////////////// -// Fragment -///////////////// -fragment -DrlEscapeSequence - : '\\' ('b'|'B'|'t'|'n'|'f'|'r'|'"'|'\''|'\\'|'.'|'o'| - 'x'|'a'|'e'|'c'|'d'|'D'|'s'|'S'|'w'|'W'|'p'|'A'| - 'G'|'Z'|'z'|'Q'|'E'|'*'|'['|']'|'('|')'|'$'|'^'| - '{'|'}'|'?'|'+'|'-'|'&'|'|') - | DrlUnicodeEscape - | DrlOctalEscape - ; - -fragment -DrlOctalEscape - : '\\' ('0'..'3') ('0'..'7') ('0'..'7') - | '\\' ('0'..'7') ('0'..'7') - | '\\' ('0'..'7') - ; - -fragment -DrlUnicodeEscape - : '\\' 'u' HexDigit HexDigit HexDigit HexDigit - ; - -mode RHS; -RHS_WS : [ \t\r\n\u000C]+ -> channel(HIDDEN); -DRL_RHS_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) {setText("end");} -> popMode; -RHS_CHUNK : ~[ \t\r\n\u000C]+ ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 deleted file mode 100644 index 933c013ee6c..00000000000 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 +++ /dev/null @@ -1,495 +0,0 @@ -parser grammar DRLParser; - -options { tokenVocab=DRLLexer; } - -import JavaParser; - - /* - * statement := importStatement - * | globalStatement - * | declare - * | rule - * | ruleAttribute - * | function - * | query - * ; - */ -compilationUnit : packagedef? unitdef? drlStatementdef* ; - -drlStatementdef - : importdef - | globaldef - | declaredef - | ruledef - | attributes - | functiondef - | querydef - ; - -packagedef : PACKAGE name=drlQualifiedName SEMI? ; - -unitdef : DRL_UNIT name=drlQualifiedName SEMI? ; - -importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? SEMI? #importStandardDef - | IMPORT (DRL_ACCUMULATE|DRL_ACC) drlQualifiedName IDENTIFIER SEMI? #importAccumulateDef - ; - -globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; - -/** - * declare := DECLARE - * | (ENTRY-POINT) => entryPointDeclaration - * | (WINDOW) => windowDeclaration - * | (TRAIT) => typeDeclaration (trait) - * | (ENUM) => enumDeclaration - * | typeDeclaration (class) - * END - */ - -declaredef : DRL_DECLARE ( - | entryPointDeclaration - | windowDeclaration - | typeDeclaration - ) DRL_END ; - -/* - * typeDeclaration := [TYPE] qualifiedIdentifier (EXTENDS qualifiedIdentifier)? - * annotation* - * field* - * END - */ - -typeDeclaration : name=drlQualifiedName (EXTENDS superType=drlQualifiedName)? drlAnnotation* field* ; - -// entryPointDeclaration := ENTRY-POINT stringId annotation* END - -entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* ; - -// windowDeclaration := WINDOW ID annotation* lhsPatternBind END - -windowDeclaration : DRL_WINDOW name=stringId drlAnnotation* lhsPatternBind ; - -// field := label fieldType (EQUALS_ASSIGN conditionalExpression)? annotation* SEMICOLON? - -field : label type (ASSIGN initExpr=conditionalOrExpression)? drlAnnotation* SEMI? ; - -// rule := RULE stringId (EXTENDS stringId)? annotation* attributes? lhs? rhs END - -ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* attributes? lhs rhs DRL_RHS_END ; - -// query := QUERY stringId parameters? annotation* lhsExpression END - -querydef : DRL_QUERY name=stringId formalParameters? drlAnnotation* lhsExpression+ DRL_END SEMI?; - -lhs : DRL_WHEN lhsExpression* ; - -lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed - | lhsUnary #lhsUnarySingle - | LPAREN DRL_AND lhsExpression+ RPAREN #lhsAnd - | lhsExpression (DRL_AND lhsExpression)+ #lhsAnd - | LPAREN DRL_OR lhsExpression+ RPAREN #lhsOr - | lhsExpression (DRL_OR lhsExpression)+ #lhsOr - ; - -// 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 lhsUnary)* - | LPAREN DRL_AND lhsUnary+ RPAREN - ; - -/* -lhsUnary : ( lhsExists namedConsequence? - | lhsNot namedConsequence? - | lhsEval consequenceInvocation* - | lhsForall - | lhsAccumulate - | LPAREN lhsOr RPAREN namedConsequence? - | lhsPatternBind consequenceInvocation* - ) SEMI? ; -*/ - -lhsUnary : ( - lhsExists - | lhsNot - | lhsEval - | lhsForall - | lhsAccumulate - | lhsPatternBind - ) SEMI? ; - -lhsPatternBind : (label|unif)? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; - -/* -lhsPattern : xpathPrimary (OVER patternFilter)? | - ( QUESTION? qualifiedIdentifier LPAREN positionalConstraints? constraints? RPAREN (OVER patternFilter)? (FROM patternSource)? ) ; -*/ - -lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN (DRL_OVER patternFilter)? (DRL_FROM patternSource)? ; -positionalConstraints : constraint (COMMA constraint)* SEMI ; -constraints : constraint (COMMA constraint)* ; -constraint : ( nestedConstraint | conditionalOrExpression ) ; -nestedConstraint : ( IDENTIFIER ( DOT | HASH ) )* IDENTIFIER DOT LPAREN constraints RPAREN ; -conditionalOrExpression : left=conditionalAndExpression (OR right=conditionalAndExpression)* ; -conditionalAndExpression : left=inclusiveOrExpression (AND right=inclusiveOrExpression)* ; -inclusiveOrExpression : left=exclusiveOrExpression (BITOR right=exclusiveOrExpression)* ; -exclusiveOrExpression : left=andExpression (CARET right=andExpression)* ; -andExpression : left=equalityExpression (BITAND right=equalityExpression)* ; -equalityExpression : label? left=instanceOfExpression ( ( op=EQUAL | op=NOTEQUAL ) right=instanceOfExpression )* ; -instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; -inExpression : left=relationalExpression ( 'not'? 'in' LPAREN drlExpression (COMMA drlExpression)* RPAREN )? ; -relationalExpression : left=drlExpression (right=orRestriction)* ; -orRestriction : left=andRestriction (OR right=andRestriction)* ; -andRestriction : left=singleRestriction (AND right=singleRestriction)* ; -singleRestriction : op=relationalOperator drlExpression ; - -relationalOperator - : EQUAL - | NOTEQUAL - | LE - | GE - | GT - | LT - | temporalOperator - ; - -/* function := FUNCTION type? ID parameters(typed) chunk_{_} */ -functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters block ; - - -/* extending JavaParser qualifiedName */ -drlQualifiedName - : drlIdentifier (DOT drlIdentifier)* - ; - -/* extending JavaParser identifier */ -drlIdentifier - : drlKeywords - | IDENTIFIER - | MODULE - | OPEN - | REQUIRES - | EXPORTS - | OPENS - | TO - | USES - | PROVIDES - | WITH - | TRANSITIVE - | YIELD - | SEALED - | PERMITS - | RECORD - | VAR - ; - -drlKeywords - : DRL_UNIT - | DRL_FUNCTION - | DRL_GLOBAL - | DRL_DECLARE - | DRL_RULE - | DRL_QUERY - | DRL_WHEN - | DRL_THEN - | DRL_END - | DRL_AND - | DRL_OR - | DRL_EXISTS - | DRL_NOT - | DRL_IN - | DRL_FROM - | DRL_MATCHES - | DRL_MEMBEROF - | DRL_ACCUMULATE - | DRL_ACC - | DRL_INIT - | DRL_ACTION - | DRL_REVERSE - | DRL_RESULT - | DRL_ENTRY_POINT - | DRL_EVAL - | DRL_SALIENCE - | DRL_ENABLED - | DRL_NO_LOOP - | DRL_AUTO_FOCUS - | DRL_LOCK_ON_ACTIVE - | DRL_REFRACT - | DRL_DIRECT - | DRL_AGENDA_GROUP - | DRL_ACTIVATION_GROUP - | DRL_RULEFLOW_GROUP - | DRL_DATE_EFFECTIVE - | DRL_DATE_EXPIRES - | DRL_DIALECT - | DRL_CALENDARS - | DRL_TIMER - | DRL_DURATION - ; - -/* extending JavaParser expression */ -drlExpression - : drlPrimary - | drlExpression bop=DOT - ( - drlIdentifier - | methodCall - | THIS - | NEW nonWildcardTypeArguments? innerCreator - | SUPER superSuffix - | explicitGenericInvocation - ) - | drlExpression LBRACK drlExpression RBRACK - | DRL_EVAL LPAREN conditionalOrExpression RPAREN - | methodCall - | NEW drlCreator - | LPAREN annotation* typeType (BITAND typeType)* RPAREN drlExpression - | drlExpression postfix=(INC | DEC) - | prefix=(ADD|SUB|INC|DEC) drlExpression - | prefix=(TILDE|BANG) drlExpression - | drlExpression bop=(MUL|DIV|MOD) drlExpression - | drlExpression bop=(ADD|SUB) drlExpression - | drlExpression (LT LT | GT GT GT | GT GT) drlExpression - | drlExpression bop=(LE | GE | GT | LT) drlExpression - | drlExpression temporalOperator drlExpression - | drlExpression bop=INSTANCEOF (typeType | pattern) - | drlExpression bop=DRL_MATCHES drlExpression - | drlExpression DRL_NOT? DRL_MEMBEROF drlExpression - | drlExpression bop=DRL_UNIFY drlExpression - | drlExpression bop=(EQUAL | NOTEQUAL) drlExpression - | drlExpression bop=BITAND drlExpression - | drlExpression bop=CARET drlExpression - | drlExpression bop=BITOR drlExpression - | drlExpression bop=AND drlExpression - | drlExpression bop=OR drlExpression - | drlExpression bop=QUESTION drlExpression COLON drlExpression - | drlExpression - bop=(ASSIGN | ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | RSHIFT_ASSIGN | URSHIFT_ASSIGN | LSHIFT_ASSIGN | MOD_ASSIGN) - drlExpression - | lambdaExpression // Java8 - | switchExpression // Java17 - - // Java 8 methodReference - | drlExpression COLONCOLON typeArguments? drlIdentifier - | typeType COLONCOLON (typeArguments? drlIdentifier | NEW) - | classType COLONCOLON typeArguments? NEW - ; - -temporalOperator : DRL_NOT? bop=(DRL_AFTER | DRL_BEFORE | DRL_COINCIDES | DRL_DURING | DRL_INCLUDES | DRL_FINISHES | DRL_FINISHED_BY | DRL_MEETS | DRL_MET_BY | DRL_OVERLAPS | DRL_OVERLAPPED_BY | DRL_STARTS | DRL_STARTED_BY) timeAmount? ; - -timeAmount : LBRACK (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL) (COMMA (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL))* RBRACK ; - -/* extending JavaParser primary */ -drlPrimary - : LPAREN drlExpression RPAREN - | THIS - | SUPER - | drlLiteral - | drlIdentifier - | typeTypeOrVoid DOT CLASS - | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) - | inlineListExpression - | inlineMapExpression - ; - -/* extending JavaParser literal */ -drlLiteral - : integerLiteral - | floatLiteral - | DRL_BIG_DECIMAL_LITERAL - | DRL_BIG_INTEGER_LITERAL - | CHAR_LITERAL - | DRL_STRING_LITERAL - | BOOL_LITERAL - | NULL_LITERAL - | TEXT_BLOCK // Java17 - ; - -inlineListExpression - : LBRACK expressionList? RBRACK - ; - -expressionList - : drlExpression (COMMA drlExpression)* - ; - -inlineMapExpression - : LBRACK mapExpressionList RBRACK - ; - -mapExpressionList - : mapEntry (COMMA mapEntry)* - ; - -mapEntry - : drlExpression COLON drlExpression - ; - -/* - patternFilter := OVER filterDef - filterDef := label ID LEFT_PAREN parameters RIGHT_PAREN -*/ -patternFilter : DRL_WINDOW COLON IDENTIFIER LPAREN expressionList RPAREN ; - -/* - patternSource := FROM - ( fromAccumulate - | fromCollect - | fromEntryPoint - | fromWindow - | fromExpression ) -*/ -patternSource : fromAccumulate - | fromCollect - | fromEntryPoint - | fromExpression - ; - -fromExpression : conditionalOrExpression ; - - -/* -fromAccumulate := ACCUMULATE LEFT_PAREN lhsAnd (COMMA|SEMICOLON) - ( INIT chunk_(_) COMMA ACTION chunk_(_) COMMA - ( REVERSE chunk_(_) COMMA)? RESULT chunk_(_) - | accumulateFunction - ) RIGHT_PAREN -*/ -fromAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) - ( DRL_INIT LPAREN initBlockStatements=blockStatements RPAREN COMMA DRL_ACTION LPAREN actionBlockStatements=blockStatements RPAREN COMMA ( DRL_REVERSE LPAREN reverseBlockStatements=blockStatements RPAREN COMMA)? DRL_RESULT LPAREN expression RPAREN - | accumulateFunction - ) - RPAREN (SEMI)? - ; - -blockStatements : blockStatement* ; - -/* -accumulateFunction := label? ID parameters -*/ -accumulateFunction : label? IDENTIFIER LPAREN drlExpression RPAREN; - -// fromCollect := COLLECT LEFT_PAREN lhsPatternBind RIGHT_PAREN - -fromCollect : DRL_COLLECT LPAREN lhsPatternBind RPAREN ; - -fromEntryPoint : DRL_ENTRY_POINT stringId ; - -/* - lhsExists := EXISTS - ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or - | LEFT_PAREN lhsOr RIGHT_PAREN - | lhsPatternBind - ) -*/ -// Use lhsExpression instead of lhsOr because lhsExpression has good enough structure -lhsExists : DRL_EXISTS - ( LPAREN lhsExpression RPAREN - | lhsPatternBind - ) - ; - -/* - lhsNot := NOT - ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or - | LEFT_PAREN lhsOr RIGHT_PAREN - | lhsPatternBind - ) -*/ -// Use lhsExpression instead of lhsOr because lhsExpression has good enough structure -lhsNot : DRL_NOT - ( LPAREN lhsExpression RPAREN - | lhsPatternBind - ) - ; - -/** - * lhsEval := EVAL LEFT_PAREN conditionalExpression RIGHT_PAREN - */ -lhsEval : DRL_EVAL LPAREN conditionalOrExpression RPAREN ; - -/** - * lhsForall := FORALL LEFT_PAREN lhsPatternBind+ RIGHT_PAREN - */ - -lhsForall : DRL_FORALL LPAREN lhsPatternBind+ RPAREN ; - -/** - * lhsAccumulate := (ACCUMULATE|ACC) LEFT_PAREN lhsAnd (COMMA|SEMICOLON) - * accumulateFunctionBinding (COMMA accumulateFunctionBinding)* - * (SEMICOLON constraints)? - * RIGHT_PAREN SEMICOLON? - */ - -lhsAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) - accumulateFunction (COMMA accumulateFunction)* - (SEMI constraints)? - RPAREN (SEMI)? - ; - -rhs : DRL_THEN consequence ; - -consequence : RHS_CHUNK* ; - -stringId : ( IDENTIFIER | DRL_STRING_LITERAL ) ; - -type : (classOrInterfaceType | primitiveType) typeArguments? ( DOT IDENTIFIER typeArguments? )* (LBRACK RBRACK)* ; - -//typeArguments : LT typeArgument (COMMA typeArgument)* GT ; -//typeArgument : QUESTION (( EXTENDS | SUPER ) type )? | type ; - -drlArguments : LPAREN drlArgument (COMMA drlArgument)* RPAREN ; -drlArgument : ( stringId | floatLiteral | BOOL_LITERAL | NULL_LITERAL ) ; - -drlAnnotation : AT name=drlQualifiedName (LPAREN ( drlElementValuePairs | drlElementValue )? RPAREN)? ; - -drlElementValuePairs : drlElementValuePair (COMMA drlElementValuePair)* ; -drlElementValuePair : key=drlIdentifier ASSIGN value=drlElementValue ; - -drlElementValue - : drlExpression - | drlArrayInitializer - ; - -attributes : attribute ( COMMA? attribute )* ; -attribute : name=( 'salience' | 'enabled' ) conditionalOrExpression #expressionAttribute - | name=( 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOL_LITERAL? #booleanAttribute - | name=( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) DRL_STRING_LITERAL #stringAttribute - | name='calendars' DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* #stringListAttribute - | name='timer' ( DECIMAL_LITERAL | chunk ) #intOrChunkAttribute - | name='duration' ( DECIMAL_LITERAL | TIME_INTERVAL | LPAREN TIME_INTERVAL RPAREN ) #durationAttribute - ; - -chunk : LPAREN .+? RPAREN; - -assignmentOperator : ASSIGN - | ADD_ASSIGN - | SUB_ASSIGN - | MUL_ASSIGN - | DIV_ASSIGN - | AND_ASSIGN - | OR_ASSIGN - | XOR_ASSIGN - | MOD_ASSIGN - | LT LT ASSIGN ; - -label : IDENTIFIER COLON ; -unif : IDENTIFIER DRL_UNIFY ; - -/* extending JavaParser variableInitializer */ -drlVariableInitializer - : arrayInitializer - | drlExpression - ; - - drlCreator - : nonWildcardTypeArguments createdName classCreatorRest - | createdName (drlArrayCreatorRest | classCreatorRest) - ; - - drlArrayCreatorRest - : LBRACK (RBRACK (LBRACK RBRACK)* drlArrayInitializer | expression RBRACK (LBRACK expression RBRACK)* (LBRACK RBRACK)*) - ; - - drlArrayInitializer - : LBRACE (drlVariableInitializer (COMMA drlVariableInitializer)* (COMMA)? )? RBRACE - ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 deleted file mode 100644 index 1af884db096..00000000000 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 +++ /dev/null @@ -1,245 +0,0 @@ -/* - [The "BSD licence"] - Copyright (c) 2013 Terence Parr, Sam Harwell - Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) - Copyright (c) 2021 Michał Lorek (upgrade to Java 11) - Copyright (c) 2022 Michał Lorek (upgrade to Java 17) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -// source: https://github.com/antlr/grammars-v4/tree/master/java/java - -lexer grammar JavaLexer; - -// Keywords - -ABSTRACT: 'abstract'; -ASSERT: 'assert'; -BOOLEAN: 'boolean'; -BREAK: 'break'; -BYTE: 'byte'; -CASE: 'case'; -CATCH: 'catch'; -CHAR: 'char'; -CLASS: 'class'; -CONST: 'const'; -CONTINUE: 'continue'; -DEFAULT: 'default'; -DO: 'do'; -DOUBLE: 'double'; -ELSE: 'else'; -ENUM: 'enum'; -EXTENDS: 'extends'; -FINAL: 'final'; -FINALLY: 'finally'; -FLOAT: 'float'; -FOR: 'for'; -IF: 'if'; -GOTO: 'goto'; -IMPLEMENTS: 'implements'; -IMPORT: 'import'; -INSTANCEOF: 'instanceof'; -INT: 'int'; -INTERFACE: 'interface'; -LONG: 'long'; -NATIVE: 'native'; -NEW: 'new'; -PACKAGE: 'package'; -PRIVATE: 'private'; -PROTECTED: 'protected'; -PUBLIC: 'public'; -RETURN: 'return'; -SHORT: 'short'; -STATIC: 'static'; -STRICTFP: 'strictfp'; -SUPER: 'super'; -SWITCH: 'switch'; -SYNCHRONIZED: 'synchronized'; -THIS: 'this'; -THROW: 'throw'; -THROWS: 'throws'; -TRANSIENT: 'transient'; -TRY: 'try'; -VOID: 'void'; -VOLATILE: 'volatile'; -WHILE: 'while'; - -// Module related keywords -MODULE: 'module'; -OPEN: 'open'; -REQUIRES: 'requires'; -EXPORTS: 'exports'; -OPENS: 'opens'; -TO: 'to'; -USES: 'uses'; -PROVIDES: 'provides'; -WITH: 'with'; -TRANSITIVE: 'transitive'; - -// Local Variable Type Inference -VAR: 'var'; // reserved type name - -// Switch Expressions -YIELD: 'yield'; - -// Records -RECORD: 'record'; - -// Sealed Classes -SEALED: 'sealed'; -PERMITS: 'permits'; -NON_SEALED: 'non-sealed'; - -// Literals - -DECIMAL_LITERAL: ('0' | [1-9] (Digits? | '_'+ Digits)) [lL]?; -HEX_LITERAL: '0' [xX] [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? [lL]?; -OCT_LITERAL: '0' '_'* [0-7] ([0-7_]* [0-7])? [lL]?; -BINARY_LITERAL: '0' [bB] [01] ([01_]* [01])? [lL]?; - -FLOAT_LITERAL: (Digits '.' Digits? | '.' Digits) ExponentPart? [fFdD]? - | Digits (ExponentPart [fFdD]? | [fFdD]) - ; - -HEX_FLOAT_LITERAL: '0' [xX] (HexDigits '.'? | HexDigits? '.' HexDigits) [pP] [+-]? Digits [fFdD]?; - -BOOL_LITERAL: 'true' - | 'false' - ; - -CHAR_LITERAL: '\'' (~['\\\r\n] | EscapeSequence) '\''; - -STRING_LITERAL: '"' (~["\\\r\n] | EscapeSequence)* '"'; - -TEXT_BLOCK: '"""' [ \t]* [\r\n] (. | EscapeSequence)*? '"""'; - -NULL_LITERAL: 'null'; - -// Separators - -LPAREN: '('; -RPAREN: ')'; -LBRACE: '{'; -RBRACE: '}'; -LBRACK: '['; -RBRACK: ']'; -SEMI: ';'; -COMMA: ','; -DOT: '.'; - -// Operators - -ASSIGN: '='; -GT: '>'; -LT: '<'; -BANG: '!'; -TILDE: '~'; -QUESTION: '?'; -COLON: ':'; -EQUAL: '=='; -LE: '<='; -GE: '>='; -NOTEQUAL: '!='; -AND: '&&'; -OR: '||'; -INC: '++'; -DEC: '--'; -ADD: '+'; -SUB: '-'; -MUL: '*'; -DIV: '/'; -BITAND: '&'; -BITOR: '|'; -CARET: '^'; -MOD: '%'; - -ADD_ASSIGN: '+='; -SUB_ASSIGN: '-='; -MUL_ASSIGN: '*='; -DIV_ASSIGN: '/='; -AND_ASSIGN: '&='; -OR_ASSIGN: '|='; -XOR_ASSIGN: '^='; -MOD_ASSIGN: '%='; -LSHIFT_ASSIGN: '<<='; -RSHIFT_ASSIGN: '>>='; -URSHIFT_ASSIGN: '>>>='; - -// Java 8 tokens - -ARROW: '->'; -COLONCOLON: '::'; - -// Additional symbols not defined in the lexical specification - -AT: '@'; -ELLIPSIS: '...'; - -// Whitespace and comments - -WS: [ \t\r\n\u000C]+ -> channel(HIDDEN); -COMMENT: '/*' .*? '*/' -> channel(HIDDEN); -LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN); - -// Identifiers - -IDENTIFIER: Letter LetterOrDigit*; - -// Fragment rules - -fragment ExponentPart - : [eE] [+-]? Digits - ; - -fragment EscapeSequence - : '\\' [btnfr"'\\] - | '\\' ([0-3]? [0-7])? [0-7] - | '\\' 'u'+ HexDigit HexDigit HexDigit HexDigit - ; - -fragment HexDigits - : HexDigit ((HexDigit | '_')* HexDigit)? - ; - -fragment HexDigit - : [0-9a-fA-F] - ; - -fragment Digits - : [0-9] ([0-9_]* [0-9])? - ; - -fragment LetterOrDigit - : Letter - | [0-9] - ; - -fragment Letter - : [a-zA-Z$_] // these are the "java letters" below 0x7F - | ~[\u0000-\u007F\uD800-\uDBFF] // covers all characters above 0x7F which are not a surrogate - | [\uD800-\uDBFF] [\uDC00-\uDFFF] // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF - ; - -TEXT : .+? ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 deleted file mode 100644 index 9e9f0a68513..00000000000 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 +++ /dev/null @@ -1,752 +0,0 @@ -/* - [The "BSD licence"] - Copyright (c) 2013 Terence Parr, Sam Harwell - Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) - Copyright (c) 2021 Michał Lorek (upgrade to Java 11) - Copyright (c) 2022 Michał Lorek (upgrade to Java 17) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -// source: https://github.com/antlr/grammars-v4/tree/master/java/java - -parser grammar JavaParser; - -options { tokenVocab=JavaLexer; } - -compilationUnit - : packageDeclaration? importDeclaration* typeDeclaration* - | moduleDeclaration EOF - ; - -packageDeclaration - : annotation* PACKAGE qualifiedName SEMI - ; - -importDeclaration - : IMPORT STATIC? qualifiedName (DOT MUL)? SEMI - ; - -typeDeclaration - : classOrInterfaceModifier* - (classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration | recordDeclaration) - | SEMI - ; - -modifier - : classOrInterfaceModifier - | NATIVE - | SYNCHRONIZED - | TRANSIENT - | VOLATILE - ; - -classOrInterfaceModifier - : annotation - | PUBLIC - | PROTECTED - | PRIVATE - | STATIC - | ABSTRACT - | FINAL // FINAL for class only -- does not apply to interfaces - | STRICTFP - | SEALED // Java17 - | NON_SEALED // Java17 - ; - -variableModifier - : FINAL - | annotation - ; - -classDeclaration - : CLASS identifier typeParameters? - (EXTENDS typeType)? - (IMPLEMENTS typeList)? - (PERMITS typeList)? // Java17 - classBody - ; - -typeParameters - : LT typeParameter (COMMA typeParameter)* GT - ; - -typeParameter - : annotation* identifier (EXTENDS annotation* typeBound)? - ; - -typeBound - : typeType (BITAND typeType)* - ; - -enumDeclaration - : ENUM identifier (IMPLEMENTS typeList)? LBRACE enumConstants? COMMA? enumBodyDeclarations? RBRACE - ; - -enumConstants - : enumConstant (COMMA enumConstant)* - ; - -enumConstant - : annotation* identifier arguments? classBody? - ; - -enumBodyDeclarations - : SEMI classBodyDeclaration* - ; - -interfaceDeclaration - : INTERFACE identifier typeParameters? (EXTENDS typeList)? (PERMITS typeList)? interfaceBody - ; - -classBody - : LBRACE classBodyDeclaration* RBRACE - ; - -interfaceBody - : LBRACE interfaceBodyDeclaration* RBRACE - ; - -classBodyDeclaration - : SEMI - | STATIC? block - | modifier* memberDeclaration - ; - -memberDeclaration - : methodDeclaration - | genericMethodDeclaration - | fieldDeclaration - | constructorDeclaration - | genericConstructorDeclaration - | interfaceDeclaration - | annotationTypeDeclaration - | classDeclaration - | enumDeclaration - | recordDeclaration //Java17 - ; - -/* We use rule this even for void methods which cannot have [] after parameters. - This simplifies grammar and we can consider void to be a type, which - renders the [] matching as a context-sensitive issue or a semantic check - for invalid return type after parsing. - */ -methodDeclaration - : typeTypeOrVoid identifier formalParameters (LBRACK RBRACK)* - (THROWS qualifiedNameList)? - methodBody - ; - -methodBody - : block - | SEMI - ; - -typeTypeOrVoid - : typeType - | VOID - ; - -genericMethodDeclaration - : typeParameters methodDeclaration - ; - -genericConstructorDeclaration - : typeParameters constructorDeclaration - ; - -constructorDeclaration - : identifier formalParameters (THROWS qualifiedNameList)? constructorBody=block - ; - -fieldDeclaration - : typeType variableDeclarators SEMI - ; - -interfaceBodyDeclaration - : modifier* interfaceMemberDeclaration - | SEMI - ; - -interfaceMemberDeclaration - : constDeclaration - | interfaceMethodDeclaration - | genericInterfaceMethodDeclaration - | interfaceDeclaration - | annotationTypeDeclaration - | classDeclaration - | enumDeclaration - | recordDeclaration // Java17 - ; - -constDeclaration - : typeType constantDeclarator (COMMA constantDeclarator)* SEMI - ; - -constantDeclarator - : identifier (LBRACK RBRACK)* ASSIGN variableInitializer - ; - -// Early versions of Java allows brackets after the method name, eg. -// public int[] return2DArray() [] { ... } -// is the same as -// public int[][] return2DArray() { ... } -interfaceMethodDeclaration - : interfaceMethodModifier* interfaceCommonBodyDeclaration - ; - -// Java8 -interfaceMethodModifier - : annotation - | PUBLIC - | ABSTRACT - | DEFAULT - | STATIC - | STRICTFP - ; - -genericInterfaceMethodDeclaration - : interfaceMethodModifier* typeParameters interfaceCommonBodyDeclaration - ; - -interfaceCommonBodyDeclaration - : annotation* typeTypeOrVoid identifier formalParameters (LBRACK RBRACK)* (THROWS qualifiedNameList)? methodBody - ; - -variableDeclarators - : variableDeclarator (COMMA variableDeclarator)* - ; - -variableDeclarator - : variableDeclaratorId (ASSIGN variableInitializer)? - ; - -variableDeclaratorId - : identifier (LBRACK RBRACK)* - ; - -variableInitializer - : arrayInitializer - | expression - ; - -arrayInitializer - : LBRACE (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RBRACE - ; - -classOrInterfaceType - : identifier typeArguments? (DOT identifier typeArguments?)* - ; - -typeArgument - : typeType - | annotation* QUESTION ((EXTENDS | SUPER) typeType)? - ; - -qualifiedNameList - : qualifiedName (COMMA qualifiedName)* - ; - -formalParameters - : LPAREN ( receiverParameter? - | receiverParameter (COMMA formalParameterList)? - | formalParameterList? - ) RPAREN - ; - -receiverParameter - : typeType (identifier DOT)* THIS - ; - -formalParameterList - : formalParameter (COMMA formalParameter)* (COMMA lastFormalParameter)? - | lastFormalParameter - ; - -formalParameter - : variableModifier* typeType variableDeclaratorId - ; - -lastFormalParameter - : variableModifier* typeType annotation* ELLIPSIS variableDeclaratorId - ; - -// local variable type inference -lambdaLVTIList - : lambdaLVTIParameter (COMMA lambdaLVTIParameter)* - ; - -lambdaLVTIParameter - : variableModifier* VAR identifier - ; - -qualifiedName - : identifier (DOT identifier)* - ; - -literal - : integerLiteral - | floatLiteral - | CHAR_LITERAL - | STRING_LITERAL - | BOOL_LITERAL - | NULL_LITERAL - | TEXT_BLOCK // Java17 - ; - -integerLiteral - : DECIMAL_LITERAL - | HEX_LITERAL - | OCT_LITERAL - | BINARY_LITERAL - ; - -floatLiteral - : FLOAT_LITERAL - | HEX_FLOAT_LITERAL - ; - -// ANNOTATIONS -altAnnotationQualifiedName - : (identifier DOT)* AT identifier - ; - -annotation - : (AT qualifiedName | altAnnotationQualifiedName) (LPAREN ( elementValuePairs | elementValue )? RPAREN)? - ; - -elementValuePairs - : elementValuePair (COMMA elementValuePair)* - ; - -elementValuePair - : identifier ASSIGN elementValue - ; - -elementValue - : expression - | annotation - | elementValueArrayInitializer - ; - -elementValueArrayInitializer - : LBRACE (elementValue (COMMA elementValue)*)? (COMMA)? RBRACE - ; - -annotationTypeDeclaration - : AT INTERFACE identifier annotationTypeBody - ; - -annotationTypeBody - : LBRACE (annotationTypeElementDeclaration)* RBRACE - ; - -annotationTypeElementDeclaration - : modifier* annotationTypeElementRest - | SEMI // this is not allowed by the grammar, but apparently allowed by the actual compiler - ; - -annotationTypeElementRest - : typeType annotationMethodOrConstantRest SEMI - | classDeclaration SEMI? - | interfaceDeclaration SEMI? - | enumDeclaration SEMI? - | annotationTypeDeclaration SEMI? - | recordDeclaration SEMI? // Java17 - ; - -annotationMethodOrConstantRest - : annotationMethodRest - | annotationConstantRest - ; - -annotationMethodRest - : identifier LPAREN RPAREN defaultValue? - ; - -annotationConstantRest - : variableDeclarators - ; - -defaultValue - : DEFAULT elementValue - ; - -// MODULES - Java9 - -moduleDeclaration - : OPEN? MODULE qualifiedName moduleBody - ; - -moduleBody - : LBRACE moduleDirective* RBRACE - ; - -moduleDirective - : REQUIRES requiresModifier* qualifiedName SEMI - | EXPORTS qualifiedName (TO qualifiedName)? SEMI - | OPENS qualifiedName (TO qualifiedName)? SEMI - | USES qualifiedName SEMI - | PROVIDES qualifiedName WITH qualifiedName SEMI - ; - -requiresModifier - : TRANSITIVE - | STATIC - ; - -// RECORDS - Java 17 - -recordDeclaration - : RECORD identifier typeParameters? recordHeader - (IMPLEMENTS typeList)? - recordBody - ; - -recordHeader - : LPAREN recordComponentList? RPAREN - ; - -recordComponentList - : recordComponent (COMMA recordComponent)* - ; - -recordComponent - : typeType identifier - ; - -recordBody - : LBRACE classBodyDeclaration* RBRACE - ; - -// STATEMENTS / BLOCKS - -block - : LBRACE blockStatement* RBRACE - ; - -blockStatement - : localVariableDeclaration SEMI - | statement - | localTypeDeclaration - ; - -localVariableDeclaration - : variableModifier* (typeType variableDeclarators | VAR identifier ASSIGN expression) - ; - -identifier - : IDENTIFIER - | MODULE - | OPEN - | REQUIRES - | EXPORTS - | OPENS - | TO - | USES - | PROVIDES - | WITH - | TRANSITIVE - | YIELD - | SEALED - | PERMITS - | RECORD - | VAR - ; - -localTypeDeclaration - : classOrInterfaceModifier* - (classDeclaration | interfaceDeclaration | recordDeclaration) - | SEMI - ; - -statement - : blockLabel=block - | ASSERT expression (COLON expression)? SEMI - | IF parExpression statement (ELSE statement)? - | FOR LPAREN forControl RPAREN statement - | WHILE parExpression statement - | DO statement WHILE parExpression SEMI - | TRY block (catchClause+ finallyBlock? | finallyBlock) - | TRY resourceSpecification block catchClause* finallyBlock? - | SWITCH parExpression LBRACE switchBlockStatementGroup* switchLabel* RBRACE - | SYNCHRONIZED parExpression block - | RETURN expression? SEMI - | THROW expression SEMI - | BREAK identifier? SEMI - | CONTINUE identifier? SEMI - | YIELD expression SEMI // Java17 - | SEMI - | statementExpression=expression SEMI - | switchExpression SEMI? // Java17 - | identifierLabel=identifier COLON statement - ; - -catchClause - : CATCH LPAREN variableModifier* catchType identifier RPAREN block - ; - -catchType - : qualifiedName (BITOR qualifiedName)* - ; - -finallyBlock - : FINALLY block - ; - -resourceSpecification - : LPAREN resources SEMI? RPAREN - ; - -resources - : resource (SEMI resource)* - ; - -resource - : variableModifier* ( classOrInterfaceType variableDeclaratorId | VAR identifier ) ASSIGN expression - | identifier - ; - -/** Matches cases then statements, both of which are mandatory. - * To handle empty cases at the end, we add switchLabel* to statement. - */ -switchBlockStatementGroup - : switchLabel+ blockStatement+ - ; - -switchLabel - : CASE (constantExpression=expression | enumConstantName=IDENTIFIER | typeType varName=identifier) COLON - | DEFAULT COLON - ; - -forControl - : enhancedForControl - | forInit? SEMI expression? SEMI forUpdate=expressionList? - ; - -forInit - : localVariableDeclaration - | expressionList - ; - -enhancedForControl - : variableModifier* (typeType | VAR) variableDeclaratorId COLON expression - ; - -// EXPRESSIONS - -parExpression - : LPAREN expression RPAREN - ; - -expressionList - : expression (COMMA expression)* - ; - -methodCall - : identifier LPAREN expressionList? RPAREN - | THIS LPAREN expressionList? RPAREN - | SUPER LPAREN expressionList? RPAREN - ; - -expression - : primary - | expression bop=DOT - ( - identifier - | methodCall - | THIS - | NEW nonWildcardTypeArguments? innerCreator - | SUPER superSuffix - | explicitGenericInvocation - ) - | expression LBRACK expression RBRACK - | methodCall - | NEW creator - | LPAREN annotation* typeType (BITAND typeType)* RPAREN expression - | expression postfix=(INC | DEC) - | prefix=(ADD|SUB|INC|DEC) expression - | prefix=(TILDE|BANG) expression - | expression bop=(MUL|DIV|MOD) expression - | expression bop=(ADD|SUB) expression - | expression (LT LT | GT GT GT | GT GT) expression - | expression bop=(LE | GE | GT | LT) expression - | expression bop=INSTANCEOF (typeType | pattern) - | expression bop=(EQUAL | NOTEQUAL) expression - | expression bop=BITAND expression - | expression bop=CARET expression - | expression bop=BITOR expression - | expression bop=AND expression - | expression bop=OR expression - | expression bop=QUESTION expression COLON expression - | expression - bop=(ASSIGN | ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | RSHIFT_ASSIGN | URSHIFT_ASSIGN | LSHIFT_ASSIGN | MOD_ASSIGN) - expression - | lambdaExpression // Java8 - | switchExpression // Java17 - - // Java 8 methodReference - | expression COLONCOLON typeArguments? identifier - | typeType COLONCOLON (typeArguments? identifier | NEW) - | classType COLONCOLON typeArguments? NEW - ; - -// Java17 -pattern - : variableModifier* typeType annotation* identifier - ; - -// Java8 -lambdaExpression - : lambdaParameters ARROW lambdaBody - ; - -// Java8 -lambdaParameters - : identifier - | LPAREN formalParameterList? RPAREN - | LPAREN identifier (COMMA identifier)* RPAREN - | LPAREN lambdaLVTIList? RPAREN - ; - -// Java8 -lambdaBody - : expression - | block - ; - -primary - : LPAREN expression RPAREN - | THIS - | SUPER - | literal - | identifier - | typeTypeOrVoid DOT CLASS - | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) - ; - -// Java17 -switchExpression - : SWITCH parExpression LBRACE switchLabeledRule* RBRACE - ; - -// Java17 -switchLabeledRule - : CASE (expressionList | NULL_LITERAL | guardedPattern) (ARROW | COLON) switchRuleOutcome - | DEFAULT (ARROW | COLON) switchRuleOutcome - ; - -// Java17 -guardedPattern - : LPAREN guardedPattern RPAREN - | variableModifier* typeType annotation* identifier (AND expression)* - | guardedPattern AND expression - ; - -// Java17 -switchRuleOutcome - : block - | blockStatement* - ; - -classType - : (classOrInterfaceType DOT)? annotation* identifier typeArguments? - ; - -creator - : nonWildcardTypeArguments createdName classCreatorRest - | createdName (arrayCreatorRest | classCreatorRest) - ; - -createdName - : identifier typeArgumentsOrDiamond? (DOT identifier typeArgumentsOrDiamond?)* - | primitiveType - ; - -innerCreator - : identifier nonWildcardTypeArgumentsOrDiamond? classCreatorRest - ; - -arrayCreatorRest - : LBRACK (RBRACK (LBRACK RBRACK)* arrayInitializer | expression RBRACK (LBRACK expression RBRACK)* (LBRACK RBRACK)*) - ; - -classCreatorRest - : arguments classBody? - ; - -explicitGenericInvocation - : nonWildcardTypeArguments explicitGenericInvocationSuffix - ; - -typeArgumentsOrDiamond - : LT GT - | typeArguments - ; - -nonWildcardTypeArgumentsOrDiamond - : LT GT - | nonWildcardTypeArguments - ; - -nonWildcardTypeArguments - : LT typeList GT - ; - -typeList - : typeType (COMMA typeType)* - ; - -typeType - : annotation* (classOrInterfaceType | primitiveType) (annotation* LBRACK RBRACK)* - ; - -primitiveType - : BOOLEAN - | CHAR - | BYTE - | SHORT - | INT - | LONG - | FLOAT - | DOUBLE - ; - -typeArguments - : LT typeArgument (COMMA typeArgument)* GT - ; - -superSuffix - : arguments - | DOT typeArguments? identifier arguments? - ; - -explicitGenericInvocationSuffix - : SUPER superSuffix - | identifier arguments - ; - -arguments - : LPAREN expressionList? RPAREN - ; \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java index 71b23c2fdd3..15bf0addf05 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java @@ -25,7 +25,6 @@ import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognizerSharedState; import org.antlr.runtime.TokenStream; -import org.drools.drl.parser.lang.DRL10Lexer; import org.drools.drl.parser.lang.DRL5Expressions; import org.drools.drl.parser.lang.DRL5Lexer; import org.drools.drl.parser.lang.DRL5Parser; @@ -114,8 +113,6 @@ public static DRLLexer getDRLLexer(CharStream input, LanguageLevelOption languag case DRL6: case DRL6_STRICT: return new DRL6Lexer(input); - case DRL10: - return new DRL10Lexer(); } throw new RuntimeException("Unknown language level"); } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java deleted file mode 100644 index 9fb0186afb7..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl.parser; - -import java.util.Collections; -import java.util.List; - -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.RecognizerSharedState; -import org.drools.drl.ast.descr.BaseDescr; -import org.drools.drl.ast.descr.ConstraintConnectiveDescr; -import org.drools.drl.parser.lang.DRLExpressions; -import org.drools.drl.parser.lang.DRLLexer; -import org.drools.drl.parser.lang.ParserHelper; -import org.kie.internal.builder.conf.LanguageLevelOption; - -/** - * This is a helper class that provides helper methods to parse expressions - * using both the DRLExpressions parser and the DRLExprTree parser. - */ -public class Drl6ExprParser implements DrlExprParser { - - private ParserHelper helper = null; - - private final LanguageLevelOption languageLevel; - - public Drl6ExprParser(LanguageLevelOption languageLevel) { - this.languageLevel = languageLevel; - } - - /** Parse an expression from text */ - public ConstraintConnectiveDescr parse( final String text ) { - ConstraintConnectiveDescr constraint = null; - try { - DRLLexer lexer = DRLFactory.getDRLLexer(new ANTLRStringStream(text), languageLevel); - CommonTokenStream input = new CommonTokenStream( lexer ); - RecognizerSharedState state = new RecognizerSharedState(); - helper = new ParserHelper( input, state, languageLevel ); - DRLExpressions parser = DRLFactory.getDRLExpressions(input, state, helper, languageLevel); - parser.setBuildDescr( true ); - parser.setLeftMostExpr( null ); // setting initial value just in case - BaseDescr expr = parser.conditionalOrExpression(); - if ( expr != null && !parser.hasErrors() ) { - constraint = ConstraintConnectiveDescr.newAnd(); - constraint.addOrMerge( expr ); - } - } catch ( RecognitionException e ) { - helper.reportError( e ); - } - return constraint; - } - - public String getLeftMostExpr() { - return helper != null ? helper.getLeftMostExpr() : null; - } - - /** - * @return true if there were parser errors. - */ - public boolean hasErrors() { - return helper != null && helper.hasErrors(); - } - - /** - * @return a list of errors found while parsing. - */ - @SuppressWarnings("unchecked") - public List getErrors() { - return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; - } - -} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java index 0702a1d1461..60c61ac248d 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java @@ -18,29 +18,73 @@ */ package org.drools.drl.parser; +import java.util.Collections; import java.util.List; +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.RecognizerSharedState; +import org.drools.drl.parser.lang.DRLExpressions; +import org.drools.drl.parser.lang.DRLLexer; +import org.drools.drl.parser.lang.ParserHelper; +import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.kie.internal.builder.conf.LanguageLevelOption; /** * This is a helper class that provides helper methods to parse expressions * using both the DRLExpressions parser and the DRLExprTree parser. */ -public interface DrlExprParser { +public class DrlExprParser { - /** Parse an expression from text */ - ConstraintConnectiveDescr parse( final String text ); + private ParserHelper helper = null; + + private final LanguageLevelOption languageLevel; - String getLeftMostExpr(); + public DrlExprParser(LanguageLevelOption languageLevel) { + this.languageLevel = languageLevel; + } + + /** Parse an expression from text */ + public ConstraintConnectiveDescr parse( final String text ) { + ConstraintConnectiveDescr constraint = null; + try { + DRLLexer lexer = DRLFactory.getDRLLexer(new ANTLRStringStream(text), languageLevel); + CommonTokenStream input = new CommonTokenStream( lexer ); + RecognizerSharedState state = new RecognizerSharedState(); + helper = new ParserHelper( input, state, languageLevel ); + DRLExpressions parser = DRLFactory.getDRLExpressions(input, state, helper, languageLevel); + parser.setBuildDescr( true ); + parser.setLeftMostExpr( null ); // setting initial value just in case + BaseDescr expr = parser.conditionalOrExpression(); + if ( expr != null && !parser.hasErrors() ) { + constraint = ConstraintConnectiveDescr.newAnd(); + constraint.addOrMerge( expr ); + } + } catch ( RecognitionException e ) { + helper.reportError( e ); + } + return constraint; + } + + public String getLeftMostExpr() { + return helper != null ? helper.getLeftMostExpr() : null; + } /** * @return true if there were parser errors. */ - boolean hasErrors(); + public boolean hasErrors() { + return helper != null && helper.hasErrors(); + } /** * @return a list of errors found while parsing. */ @SuppressWarnings("unchecked") - List getErrors(); + public List getErrors() { + return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; + } + } 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 deleted file mode 100644 index 9ee116faf37..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.drools.drl.parser; - -import org.drools.drl10.parser.Drl10ExprParser; -import org.kie.internal.builder.conf.LanguageLevelOption; - -public class DrlExprParserFactory { - - public static DrlExprParser getDrlExrParser(LanguageLevelOption languageLevel) { - switch (languageLevel) { - case DRL5: - case DRL6: - case DRL6_STRICT: - 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 d6ee0c042bb..7b852c8dce3 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 @@ -18,8 +18,6 @@ */ package org.drools.drl.parser; -import org.drools.drl10.parser.DRLParserError; -import org.drools.drl10.parser.DRLParserWrapper; import org.drools.io.InternalResource; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.parser.lang.DRLLexer; @@ -166,35 +164,10 @@ public PackageDescr parse(final boolean isEditor, final InputStream is) throws DroolsParserException, IOException { this.resource = resource; String encoding = resource instanceof InternalResource ? ((InternalResource) resource).getEncoding() : null; - System.out.println("### parse : languageLevel = " + languageLevel); - if (languageLevel == LanguageLevelOption.DRL10) { - // new parser based on antlr4 - try { - DRLParserWrapper parser = new DRLParserWrapper(); - PackageDescr packageDescr = parser.parse(is); - for (final DRLParserError drlParserError : parser.getErrors()) { - final ParserError err = new ParserError(resource, - drlParserError.getMessage(), - drlParserError.getLineNumber(), - drlParserError.getColumn()); - this.results.add(err); - } - return !this.hasErrors() ? packageDescr : null; - } catch (Exception e) { - LOG.error("Exception", e); - final ParserError err = new ParserError(resource, - GENERIC_ERROR_MESSAGE + e.toString() + "\n" + Arrays.toString(e.getStackTrace()), - -1, - 0); - this.results.add(err); - throw new DroolsParserException(GENERIC_ERROR_MESSAGE + e.getMessage(), e); - } - } else { - // old parsers based on antlr3 - lexer = DRLFactory.buildLexer(is, encoding, languageLevel); - DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); - return compile(isEditor, parser); - } + + lexer = DRLFactory.buildLexer(is, encoding, languageLevel); + DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); + return compile(isEditor, parser); } /** diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java deleted file mode 100644 index 15f6157bd3e..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl.parser.lang; - -import java.util.List; - -import org.antlr.runtime.Token; -import org.drools.drl.parser.DroolsParserException; - -/** - * No implementation because everything is handled by DRL10Parser - */ -public class DRL10Lexer implements DRLLexer { - - @Override - public String getSourceName() { - throw new UnsupportedOperationException("This method should not be called"); - } - - @Override - public Token nextToken() { - throw new UnsupportedOperationException("This method should not be called"); - } - - @Override - public List getErrors() { - throw new UnsupportedOperationException("This method should not be called"); - } - -} \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java deleted file mode 100644 index 0e5b5985b6c..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -import java.util.ArrayList; -import java.util.List; - -import org.antlr.v4.runtime.BaseErrorListener; -import org.antlr.v4.runtime.RecognitionException; -import org.antlr.v4.runtime.Recognizer; - -/** - * Collect errors while parsing DRL - */ -public class DRLErrorListener extends BaseErrorListener { - - private final List errors = new ArrayList<>(); - - public List getErrors() { - return errors; - } - - @Override - public void syntaxError(Recognizer recognizer, - Object offendingSymbol, - int line, - int charPositionInLine, - String msg, - RecognitionException e) { - - errors.add(new DRLParserError(line, charPositionInLine, msg)); - } -} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java deleted file mode 100644 index e7aa8102c48..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -import java.util.LinkedList; -import java.util.List; - -import org.antlr.v4.runtime.Parser; -import org.antlr.v4.runtime.RecognitionException; -import org.antlr.v4.runtime.TokenStream; -import org.drools.drl.ast.descr.BaseDescr; -import org.drools.drl.parser.DroolsParserException; -import org.drools.drl.parser.lang.DroolsSentence; - -public abstract class DRLExpressions extends Parser { - public DRLExpressions(TokenStream input) { - super(input); - } - - public abstract void setBuildDescr( boolean build ); - public abstract boolean isBuildDescr(); - - public abstract void setLeftMostExpr( String value ); - public abstract String getLeftMostExpr(); - - public abstract void setHasBindings( boolean value ); - public abstract boolean hasBindings(); - - /* - * This is the original method signature in drools/drools-drl/drools-drl-parser: - * public abstract BaseDescr conditionalOrExpression() throws RecognitionException; - * I changed it here because the conditionalOrExpression() method generated by ANTLR 4 from the conditionalOrExpression rule - * returns ConditionalOrExpressionContext, so it has a return type that's different from what was originally expected here. - * The Descr object is of course inside that context (go to this method's impl to see). - */ - public abstract BaseDescr conditionalOrExpressionDescr() throws RecognitionException; - - public abstract ParserHelper getHelper(); - public abstract boolean hasErrors(); - public abstract List getErrors(); - public abstract List getErrorMessages(); - public abstract void enableEditorInterface(); - public abstract void disableEditorInterface(); - public abstract LinkedList getEditorInterface(); -} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java deleted file mode 100644 index 4b893e11e46..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -/** - * Error information while parsing DRL - */ -public class DRLParserError { - - private int lineNumber; - private int column; - private String message; - - private Exception exception; - - public DRLParserError(int lineNumber, int column, String message) { - this.lineNumber = lineNumber; - this.column = column; - this.message = message; - } - - public DRLParserError(Exception exception) { - this.exception = exception; - } - - public int getLineNumber() { - return lineNumber; - } - - public void setLineNumber(int lineNumber) { - this.lineNumber = lineNumber; - } - - public int getColumn() { - return column; - } - - public void setColumn(int column) { - this.column = column; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - @Override - public String toString() { - return "DRLParserError{" + - "lineNumber=" + lineNumber + - ", column=" + column + - ", message='" + message + '\'' + - ", exception=" + exception + - '}'; - } -} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java deleted file mode 100644 index 833d1aa8df0..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -public class DRLParserException extends RuntimeException { - - public DRLParserException() { - super(); - } - - public DRLParserException(String message) { - super(message); - } -} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java deleted file mode 100644 index f4436bf44b0..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; - -import org.antlr.v4.runtime.CharStream; -import org.antlr.v4.runtime.CharStreams; -import org.antlr.v4.runtime.CommonTokenStream; -import org.antlr.v4.runtime.Token; -import org.antlr.v4.runtime.TokenStream; -import org.antlr.v4.runtime.tree.ErrorNode; -import org.antlr.v4.runtime.tree.ParseTree; -import org.antlr.v4.runtime.tree.TerminalNode; -import org.drools.drl.ast.descr.PackageDescr; - -/** - * Collection of static helper methods for DRLParser - */ -public class DRLParserHelper { - - private DRLParserHelper() { - } - - /** - * Entry point for parsing DRL. - * Unlike DRLParserWrapper.parse(), this method does not collect errors. - */ - public static PackageDescr parse(String drl) { - DRLParser drlParser = createDrlParser(drl); - return compilationUnitContext2PackageDescr(drlParser.compilationUnit(), drlParser.getTokenStream()); - } - - public static DRLParser createDrlParser(String drl) { - CharStream charStream = CharStreams.fromString(drl); - return createDrlParser(charStream); - } - - public static DRLParser createDrlParser(InputStream is) { - try { - CharStream charStream = CharStreams.fromStream(is); - return createDrlParser(charStream); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - private static DRLParser createDrlParser(CharStream charStream) { - DRLLexer drlLexer = new DRLLexer(charStream); - CommonTokenStream commonTokenStream = new CommonTokenStream(drlLexer); - return new DRLParser(commonTokenStream); - } - - /** - * DRLVisitorImpl visits a parse tree and creates a PackageDescr - */ - public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.CompilationUnitContext ctx, TokenStream tokenStream) { - DRLVisitorImpl visitor = new DRLVisitorImpl(tokenStream); - Object descr = visitor.visit(ctx); - if (descr instanceof PackageDescr) { - return (PackageDescr) descr; - } else { - throw new DRLParserException("CompilationUnitContext should produce PackageDescr. descr = " + descr.getClass()); - } - } - - /** - * 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) { - for (int i = 0; i < parser.getInputStream().size(); i++) { - Token token = parser.getInputStream().get(i); - int start = token.getCharPositionInLine(); - int stop = token.getCharPositionInLine() + token.getText().length(); - if (token.getLine() > row) { - return token.getTokenIndex() - 1; - } else if (token.getLine() == row && start >= col) { - return token.getTokenIndex() == 0 ? 0 : token.getTokenIndex() - 1; - } else if (token.getLine() == row && start < col && stop >= col) { - return token.getTokenIndex(); - } - } - return null; - } - - /** - * RuleContext.getText() connects all nodes including ErrorNode. This method appends texts only from valid nodes - */ - public static String getTextWithoutErrorNode(ParseTree tree) { - if (tree.getChildCount() == 0) { - return ""; - } - - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < tree.getChildCount(); i++) { - ParseTree child = tree.getChild(i); - if (!(child instanceof ErrorNode)) { - if (child instanceof TerminalNode) { - builder.append(child.getText()); - } else { - builder.append(getTextWithoutErrorNode(child)); - } - } - } - - return builder.toString(); - } -} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java deleted file mode 100644 index 914255e1375..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import org.drools.drl.ast.descr.PackageDescr; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.drools.drl10.parser.DRLParserHelper.compilationUnitContext2PackageDescr; - -/** - * Wrapper for DRLParser. Somewhat duplicated from DRLParserHelper, but this class is instantiated and holds errors. - */ -public class DRLParserWrapper { - - private static final Logger LOGGER = LoggerFactory.getLogger(DRLParserWrapper.class); - - private final List errors = new ArrayList<>(); - - /** - * Main entry point for parsing DRL - */ - public PackageDescr parse(String drl) { - DRLParser drlParser = DRLParserHelper.createDrlParser(drl); - return parse(drlParser); - } - - /** - * Main entry point for parsing DRL - */ - public PackageDescr parse(InputStream is) { - DRLParser drlParser = DRLParserHelper.createDrlParser(is); - return parse(drlParser); - } - - private PackageDescr parse(DRLParser drlParser) { - DRLErrorListener errorListener = new DRLErrorListener(); - drlParser.addErrorListener(errorListener); - - DRLParser.CompilationUnitContext cxt = drlParser.compilationUnit(); - - errors.addAll(errorListener.getErrors()); - - try { - return compilationUnitContext2PackageDescr(cxt, drlParser.getTokenStream()); - } catch (Exception e) { - LOGGER.error("Exception while creating PackageDescr", e); - errors.add(new DRLParserError(e)); - return null; - } - } - - public List getErrors() { - return errors; - } - - public List getErrorMessages() { - return errors.stream().map(DRLParserError::getMessage).collect(Collectors.toList()); - } - - public boolean hasErrors() { - return !errors.isEmpty(); - } -} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java deleted file mode 100644 index a977fee9882..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java +++ /dev/null @@ -1,845 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.v4.runtime.ParserRuleContext; -import org.antlr.v4.runtime.TokenStream; -import org.antlr.v4.runtime.tree.ParseTree; -import org.antlr.v4.runtime.tree.RuleNode; -import org.drools.drl.ast.descr.AccumulateDescr; -import org.drools.drl.ast.descr.AccumulateImportDescr; -import org.drools.drl.ast.descr.AndDescr; -import org.drools.drl.ast.descr.AnnotationDescr; -import org.drools.drl.ast.descr.AttributeDescr; -import org.drools.drl.ast.descr.BaseDescr; -import org.drools.drl.ast.descr.BehaviorDescr; -import org.drools.drl.ast.descr.CollectDescr; -import org.drools.drl.ast.descr.EntryPointDeclarationDescr; -import org.drools.drl.ast.descr.EntryPointDescr; -import org.drools.drl.ast.descr.EvalDescr; -import org.drools.drl.ast.descr.ExistsDescr; -import org.drools.drl.ast.descr.ExprConstraintDescr; -import org.drools.drl.ast.descr.ForallDescr; -import org.drools.drl.ast.descr.FromDescr; -import org.drools.drl.ast.descr.FunctionDescr; -import org.drools.drl.ast.descr.FunctionImportDescr; -import org.drools.drl.ast.descr.GlobalDescr; -import org.drools.drl.ast.descr.ImportDescr; -import org.drools.drl.ast.descr.MVELExprDescr; -import org.drools.drl.ast.descr.NotDescr; -import org.drools.drl.ast.descr.OrDescr; -import org.drools.drl.ast.descr.PackageDescr; -import org.drools.drl.ast.descr.PatternDescr; -import org.drools.drl.ast.descr.PatternSourceDescr; -import org.drools.drl.ast.descr.QueryDescr; -import org.drools.drl.ast.descr.RuleDescr; -import org.drools.drl.ast.descr.TypeDeclarationDescr; -import org.drools.drl.ast.descr.TypeFieldDescr; -import org.drools.drl.ast.descr.UnitDescr; -import org.drools.drl.ast.descr.WindowDeclarationDescr; - -import static org.drools.drl10.parser.DRLParserHelper.getTextWithoutErrorNode; -import static org.drools.drl10.parser.ParserStringUtils.getTextPreservingWhitespace; -import static org.drools.drl10.parser.ParserStringUtils.getTokenTextPreservingWhitespace; -import static org.drools.drl10.parser.ParserStringUtils.safeStripStringDelimiters; -import static org.drools.drl10.parser.ParserStringUtils.trimThen; -import static org.drools.util.StringUtils.unescapeJava; - -/** - * Visitor implementation for DRLParser. - * 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 { - - private final TokenStream tokenStream; - - public DRLVisitorImpl(TokenStream tokenStream) { - this.tokenStream = tokenStream; - } - - /** - * Main entry point for creating PackageDescr from a parser tree. - */ - @Override - public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { - PackageDescr packageDescr = new PackageDescr(); - if (ctx.packagedef() != null) { - packageDescr.setName(getTextWithoutErrorNode(ctx.packagedef().name)); - } - List descrList = visitDescrChildren(ctx); - applyChildrenDescrs(packageDescr, descrList); - return packageDescr; - } - - /** - * Add all children Descr to PackageDescr - */ - private void applyChildrenDescrs(PackageDescr packageDescr, List descrList) { - // This bunch of if-blocks will be refactored by DROOLS-7564 - descrList.forEach(descr -> { - if (descr instanceof UnitDescr) { - packageDescr.setUnit((UnitDescr) descr); - } else if (descr instanceof GlobalDescr) { - packageDescr.addGlobal((GlobalDescr) descr); - } else if (descr instanceof FunctionImportDescr) { - packageDescr.addFunctionImport((FunctionImportDescr) descr); - } else if (descr instanceof AccumulateImportDescr) { - packageDescr.addAccumulateImport((AccumulateImportDescr) descr); - } else if (descr instanceof ImportDescr) { - packageDescr.addImport((ImportDescr) descr); - } else if (descr instanceof FunctionDescr) { - FunctionDescr functionDescr = (FunctionDescr) descr; - functionDescr.setNamespace(packageDescr.getNamespace()); - AttributeDescr dialect = packageDescr.getAttribute("dialect"); - if (dialect != null) { - functionDescr.setDialect(dialect.getValue()); - } - packageDescr.addFunction(functionDescr); - } else if (descr instanceof TypeDeclarationDescr) { - packageDescr.addTypeDeclaration((TypeDeclarationDescr) descr); - } else if (descr instanceof EntryPointDeclarationDescr) { - packageDescr.addEntryPointDeclaration((EntryPointDeclarationDescr) descr); - } else if (descr instanceof WindowDeclarationDescr) { - packageDescr.addWindowDeclaration((WindowDeclarationDescr) descr); - } else if (descr instanceof AttributeDescr) { - packageDescr.addAttribute((AttributeDescr) descr); - } else if (descr instanceof RuleDescr) { // QueryDescr extends RuleDescr - packageDescr.addRule((RuleDescr) descr); - packageDescr.afterRuleAdded((RuleDescr) descr); - } - }); - } - - @Override - public UnitDescr visitUnitdef(DRLParser.UnitdefContext ctx) { - return new UnitDescr(ctx.name.getText()); - } - - @Override - public GlobalDescr visitGlobaldef(DRLParser.GlobaldefContext ctx) { - GlobalDescr globalDescr = new GlobalDescr(ctx.drlIdentifier().getText(), ctx.type().getText()); - populateStartEnd(globalDescr, ctx); - return globalDescr; - } - - @Override - public ImportDescr visitImportStandardDef(DRLParser.ImportStandardDefContext ctx) { - String target = ctx.drlQualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); - if (ctx.DRL_FUNCTION() != null || ctx.STATIC() != null) { - FunctionImportDescr functionImportDescr = new FunctionImportDescr(); - functionImportDescr.setTarget(target); - populateStartEnd(functionImportDescr, ctx); - return functionImportDescr; - } else { - ImportDescr importDescr = new ImportDescr(); - importDescr.setTarget(target); - populateStartEnd(importDescr, ctx); - return importDescr; - } - } - - @Override - public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulateDefContext ctx) { - AccumulateImportDescr accumulateImportDescr = new AccumulateImportDescr(); - accumulateImportDescr.setTarget(ctx.drlQualifiedName().getText()); - accumulateImportDescr.setFunctionName(ctx.IDENTIFIER().getText()); - return accumulateImportDescr; - } - - @Override - public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { - FunctionDescr functionDescr = new FunctionDescr(); - if (ctx.typeTypeOrVoid() != null) { - functionDescr.setReturnType(ctx.typeTypeOrVoid().getText()); - } else { - functionDescr.setReturnType("void"); - } - functionDescr.setName(ctx.IDENTIFIER().getText()); - - // add function parameters - DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); - DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); - if (formalParameterListContext != null) { - List formalParameterContexts = formalParameterListContext.formalParameter(); - formalParameterContexts.forEach(formalParameterContext -> { - DRLParser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); - DRLParser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); - functionDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); - }); - } - functionDescr.setBody(getTextPreservingWhitespace(ctx.block())); - return functionDescr; - } - - @Override - public BaseDescr visitDeclaredef(DRLParser.DeclaredefContext ctx) { - return visitDescrChildren(ctx).get(0); // only one child - } - - @Override - public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContext ctx) { - TypeDeclarationDescr typeDeclarationDescr = new TypeDeclarationDescr(ctx.name.getText()); - if (ctx.EXTENDS() != null) { - typeDeclarationDescr.addSuperType(ctx.superType.getText()); - } - ctx.drlAnnotation().stream() - .map(this::visitDrlAnnotation) - .forEach(typeDeclarationDescr::addAnnotation); - ctx.field().stream() - .map(this::visitField) - .forEach(typeDeclarationDescr::addField); - return typeDeclarationDescr; - } - - @Override - public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPointDeclarationContext ctx) { - EntryPointDeclarationDescr entryPointDeclarationDescr = new EntryPointDeclarationDescr(); - entryPointDeclarationDescr.setEntryPointId(ctx.name.getText()); - ctx.drlAnnotation().stream() - .map(this::visitDrlAnnotation) - .forEach(entryPointDeclarationDescr::addAnnotation); - return entryPointDeclarationDescr; - } - - @Override - public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclarationContext ctx) { - WindowDeclarationDescr windowDeclarationDescr = new WindowDeclarationDescr(); - windowDeclarationDescr.setName(ctx.name.getText()); - ctx.drlAnnotation().stream() - .map(this::visitDrlAnnotation) - .forEach(windowDeclarationDescr::addAnnotation); - windowDeclarationDescr.setPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); - return windowDeclarationDescr; - } - - /** - * entry point for one rule - */ - @Override - public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { - RuleDescr ruleDescr = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); - - if (ctx.EXTENDS() != null) { - ruleDescr.setParentName(safeStripStringDelimiters(ctx.parentName.getText())); - } - - ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(ruleDescr::addAnnotation); - - if (ctx.attributes() != null) { - List descrList = visitDescrChildren(ctx.attributes()); - descrList.stream() - .filter(AttributeDescr.class::isInstance) - .map(AttributeDescr.class::cast) - .forEach(ruleDescr::addAttribute); - } - - if (ctx.lhs() != null) { - List lhsDescrList = visitLhs(ctx.lhs()); - lhsDescrList.forEach(descr -> ruleDescr.getLhs().addDescr(descr)); - slimLhsRootDescr(ruleDescr.getLhs()); - } - - if (ctx.rhs() != null) { - ruleDescr.setConsequenceLocation(ctx.rhs().getStart().getLine(), ctx.rhs().getStart().getCharPositionInLine()); // location of "then" - ruleDescr.setConsequence(trimThen(getTextPreservingWhitespace(ctx.rhs()))); // RHS is just a text - } - - return ruleDescr; - } - - private void slimLhsRootDescr(AndDescr root) { - // Root Descr is always AndDescr. - // For example, if there are nested AndDescr like - // AndDescr - // /\ - // P AndDescr - // /\ - // P P - // is slimmed down to - // AndDescr - // / | \ - // P P P - List descrList = new ArrayList<>(root.getDescrs()); - root.getDescrs().clear(); - descrList.forEach(root::addOrMerge); - } - - @Override - public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { - QueryDescr queryDescr = new QueryDescr(safeStripStringDelimiters(ctx.name.getText())); - - DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); - if (formalParametersContext != null) { - DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); - List formalParameterContexts = formalParameterListContext.formalParameter(); - formalParameterContexts.forEach(formalParameterContext -> { - DRLParser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); - DRLParser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); - queryDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); - }); - } - - ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(queryDescr::addAnnotation); - - ctx.lhsExpression().stream() - .flatMap(lhsExpressionContext -> visitDescrChildren(lhsExpressionContext).stream()) - .forEach(descr -> queryDescr.getLhs().addDescr(descr)); - - slimLhsRootDescr(queryDescr.getLhs()); - - return queryDescr; - } - - @Override - public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { - AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); - if (ctx.drlElementValue() != null) { - annotationDescr.setValue(getTextPreservingWhitespace(ctx.drlElementValue())); // single value - } else if (ctx.drlElementValuePairs() != null) { - visitDrlElementValuePairs(ctx.drlElementValuePairs(), annotationDescr); // multiple values - } - return annotationDescr; - } - - @Override - public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { - TypeFieldDescr typeFieldDescr = new TypeFieldDescr(); - typeFieldDescr.setFieldName(ctx.label().IDENTIFIER().getText()); - typeFieldDescr.setPattern(new PatternDescr(ctx.type().getText())); - if (ctx.ASSIGN() != null) { - typeFieldDescr.setInitExpr(getTextPreservingWhitespace(ctx.initExpr)); - } - ctx.drlAnnotation().stream() - .map(this::visitDrlAnnotation) - .forEach(typeFieldDescr::addAnnotation); - return typeFieldDescr; - } - - private void visitDrlElementValuePairs(DRLParser.DrlElementValuePairsContext ctx, AnnotationDescr annotationDescr) { - ctx.drlElementValuePair().forEach(pairCtx -> { - String key = pairCtx.key.getText(); - String value = getTextPreservingWhitespace(pairCtx.value); - annotationDescr.setKeyValue(key, value); - }); - } - - @Override - public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); - attributeDescr.setValue(getTextPreservingWhitespace(ctx.conditionalOrExpression())); - attributeDescr.setType(AttributeDescr.Type.EXPRESSION); - return attributeDescr; - } - - @Override - public AttributeDescr visitBooleanAttribute(DRLParser.BooleanAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); - attributeDescr.setValue(ctx.BOOL_LITERAL() != null ? ctx.BOOL_LITERAL().getText() : "true"); - attributeDescr.setType(AttributeDescr.Type.BOOLEAN); - return attributeDescr; - } - - @Override - public AttributeDescr visitStringAttribute(DRLParser.StringAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); - attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.DRL_STRING_LITERAL().getText()))); - attributeDescr.setType(AttributeDescr.Type.STRING); - return attributeDescr; - } - - @Override - public AttributeDescr visitStringListAttribute(DRLParser.StringListAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); - List valueList = ctx.DRL_STRING_LITERAL().stream() - .map(ParseTree::getText) - .collect(Collectors.toList()); - attributeDescr.setValue(createStringList(valueList)); - attributeDescr.setType(AttributeDescr.Type.LIST); - return attributeDescr; - } - - private static String createStringList(List valueList) { - StringBuilder sb = new StringBuilder(); - sb.append("[ "); - for (int i = 0; i < valueList.size(); i++) { - sb.append(valueList.get(i)); - if (i < valueList.size() - 1) { - sb.append(", "); - } - } - sb.append(" ]"); - return sb.toString(); - } - - @Override - public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); - if (ctx.DECIMAL_LITERAL() != null) { - attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); - attributeDescr.setType(AttributeDescr.Type.NUMBER); - } else { - attributeDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); - attributeDescr.setType(AttributeDescr.Type.EXPRESSION); - } - return attributeDescr; - } - - @Override - public AttributeDescr visitDurationAttribute(DRLParser.DurationAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); - if (ctx.DECIMAL_LITERAL() != null) { - attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); - attributeDescr.setType(AttributeDescr.Type.NUMBER); - } else { - attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.TIME_INTERVAL().getText()))); - attributeDescr.setType(AttributeDescr.Type.EXPRESSION); - } - return attributeDescr; - } - - /** - * entry point for LHS - */ - @Override - public List visitLhs(DRLParser.LhsContext ctx) { - if (ctx.lhsExpression() != null) { - return visitDescrChildren(ctx); - } else { - return new ArrayList<>(); - } - } - - @Override - public BaseDescr visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { - if (ctx.lhsPattern().size() == 1) { - return getSinglePatternDescr(ctx); - } else if (ctx.lhsPattern().size() > 1) { - return getOrDescrWithMultiplePatternDescr(ctx); - } else { - throw new IllegalStateException("ctx.lhsPattern().size() == 0 : " + ctx.getText()); - } - } - - private PatternDescr getSinglePatternDescr(DRLParser.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()); - } - PatternDescr patternDescr = (PatternDescr)patternDescrList.get(0); - - if (ctx.label() != null) { - patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); - } else if (ctx.unif() != null) { - patternDescr.setIdentifier(ctx.unif().IDENTIFIER().getText()); - patternDescr.setUnification(true); - } - return patternDescr; - } - - private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindContext ctx) { - OrDescr orDescr = new OrDescr(); - List descrList = visitDescrChildren(ctx); - descrList.stream() - .filter(PatternDescr.class::isInstance) - .map(PatternDescr.class::cast) - .forEach(patternDescr -> { - if (ctx.label() != null) { - patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); - } - orDescr.addDescr(patternDescr); - }); - - return orDescr; - } - - /** - * entry point for a Pattern - */ - @Override - public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { - PatternDescr patternDescr = new PatternDescr(ctx.objectType.getText()); - if (ctx.QUESTION() != null) { - patternDescr.setQuery(true); - } - if (ctx.patternFilter() != null) { - patternDescr.addBehavior(visitPatternFilter(ctx.patternFilter())); - } - if (ctx.patternSource() != null) { - PatternSourceDescr patternSourceDescr = (PatternSourceDescr) visitPatternSource(ctx.patternSource()); - patternSourceDescr.setResource(patternDescr.getResource()); - patternDescr.setSource(patternSourceDescr); - } - List constraintDescrList = visitConstraints(ctx.positionalConstraints(), ctx.constraints()); - constraintDescrList.forEach(descr -> addToPatternDescr(patternDescr, descr)); - return patternDescr; - } - - private void addToPatternDescr(PatternDescr patternDescr, ExprConstraintDescr exprConstraintDescr) { - exprConstraintDescr.setResource(patternDescr.getResource()); - patternDescr.addConstraint(exprConstraintDescr); - } - - @Override - public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { - ForallDescr forallDescr = new ForallDescr(); - visitDescrChildren(ctx).forEach(forallDescr::addDescr); - return forallDescr; - } - - @Override - public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { - AccumulateDescr accumulateDescr = new AccumulateDescr(); - accumulateDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); - - // accumulate function - for (DRLParser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { - accumulateDescr.addFunction(visitAccumulateFunction(accumulateFunctionContext)); - } - - PatternDescr patternDescr = new PatternDescr("Object"); - patternDescr.setSource(accumulateDescr); - List constraintDescrList = visitConstraints(ctx.constraints()); - constraintDescrList.forEach(patternDescr::addConstraint); - return patternDescr; - } - - @Override - public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { - BehaviorDescr behaviorDescr = new BehaviorDescr(); - behaviorDescr.setType(ctx.DRL_WINDOW().getText()); - behaviorDescr.setSubType(ctx.IDENTIFIER().getText()); - List drlExpressionContexts = ctx.expressionList().drlExpression(); - List parameters = drlExpressionContexts.stream().map(ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); - behaviorDescr.setParameters(parameters); - return behaviorDescr; - } - - @Override - public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { - FromDescr fromDescr = new FromDescr(); - fromDescr.setDataSource(new MVELExprDescr(ctx.getText())); - return fromDescr; - } - - @Override - public CollectDescr visitFromCollect(DRLParser.FromCollectContext ctx) { - CollectDescr collectDescr = new CollectDescr(); - collectDescr.setInputPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); - return collectDescr; - } - - @Override - public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) { - AccumulateDescr accumulateDescr = new AccumulateDescr(); - accumulateDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); - if (ctx.DRL_INIT() != null) { - // inline custom accumulate - accumulateDescr.setInitCode(getTextPreservingWhitespace(ctx.initBlockStatements)); - accumulateDescr.setActionCode(getTextPreservingWhitespace(ctx.actionBlockStatements)); - if (ctx.DRL_REVERSE() != null) { - accumulateDescr.setReverseCode(getTextPreservingWhitespace(ctx.reverseBlockStatements)); - } - accumulateDescr.setResultCode(ctx.expression().getText()); - } else { - // accumulate function - accumulateDescr.addFunction(visitAccumulateFunction(ctx.accumulateFunction())); - } - return accumulateDescr; - } - - @Override - public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLParser.AccumulateFunctionContext ctx) { - String function = ctx.IDENTIFIER().getText(); - String bind = ctx.label() == null ? null : ctx.label().IDENTIFIER().getText(); - String[] params = new String[]{getTextPreservingWhitespace(ctx.drlExpression())}; - return new AccumulateDescr.AccumulateFunctionCallDescr(function, bind, false, params); - } - - @Override - public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) { - return new EntryPointDescr(safeStripStringDelimiters(ctx.stringId().getText())); - } - - /** - * Collect constraints in a Pattern - */ - @Override - public List visitConstraints(DRLParser.ConstraintsContext ctx) { - List exprConstraintDescrList = new ArrayList<>(); - populateExprConstraintDescrList(ctx, exprConstraintDescrList); - return exprConstraintDescrList; - } - - /** - * Collect constraints in a Pattern. Positional constraints comes first with semicolon. - */ - private List visitConstraints(DRLParser.PositionalConstraintsContext positionalCtx, DRLParser.ConstraintsContext ctx) { - List exprConstraintDescrList = new ArrayList<>(); - populateExprConstraintDescrList(positionalCtx, exprConstraintDescrList); - populateExprConstraintDescrList(ctx, exprConstraintDescrList); - return exprConstraintDescrList; - } - - private void populateExprConstraintDescrList(ParserRuleContext ctx, List exprConstraintDescrList) { - if (ctx == null) { - return; - } - List descrList = visitDescrChildren(ctx); - for (BaseDescr descr : descrList) { - if (descr instanceof ExprConstraintDescr) { - ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) descr; - exprConstraintDescr.setType(ctx instanceof DRLParser.PositionalConstraintsContext ? ExprConstraintDescr.Type.POSITIONAL : ExprConstraintDescr.Type.NAMED); - exprConstraintDescr.setPosition(exprConstraintDescrList.size()); - exprConstraintDescrList.add(exprConstraintDescr); - } - } - } - - /** - * Takes one constraint as String and create ExprConstraintDescr - */ - @Override - public ExprConstraintDescr visitConstraint(DRLParser.ConstraintContext ctx) { - String constraint = visitConstraintChildren(ctx); - if (!constraint.isEmpty()) { - ExprConstraintDescr constraintDescr = new ExprConstraintDescr(constraint); - constraintDescr.setType(ExprConstraintDescr.Type.NAMED); - return constraintDescr; - } - return null; - } - - @Override - public String visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { - return ctx.getText(); - } - - @Override - public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { - ExistsDescr existsDescr = new ExistsDescr(); - if (ctx.lhsExpression() != null) { - // exists( A() or B() ) - List baseDescrs = visitDescrChildren(ctx); - if (baseDescrs.size() == 1) { - existsDescr.addDescr(baseDescrs.get(0)); - } else { - throw new IllegalStateException("'exists()' children descr size must be 1 : " + ctx.getText()); - } - } else { - // exists A() - BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); - existsDescr.addDescr(descr); - } - return existsDescr; - } - - @Override - public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { - NotDescr notDescr = new NotDescr(); - if (ctx.lhsExpression() != null) { - // not ( A() or B() ) - List baseDescrs = visitDescrChildren(ctx); - if (baseDescrs.size() == 1) { - notDescr.addDescr(baseDescrs.get(0)); - } else { - throw new IllegalStateException("'not()' children descr size must be 1 : " + ctx.getText()); - } - } else { - // not A() - BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); - notDescr.addDescr(descr); - } - return notDescr; - } - - @Override - public EvalDescr visitLhsEval(DRLParser.LhsEvalContext ctx) { - return new EvalDescr(getTextPreservingWhitespace(ctx.conditionalOrExpression())); - } - - @Override - public BaseDescr visitLhsExpressionEnclosed(DRLParser.LhsExpressionEnclosedContext ctx) { - // enclosed expression is simply stripped because Descr itself is encapsulated - return (BaseDescr) visit(ctx.lhsExpression()); - } - - @Override - public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { - // For flatten nested OrDescr logic, we call visitDescrChildrenForDescrNodePair instead of usual visitDescrChildren - List descrList = visitDescrChildrenForDescrNodePair(ctx); - if (descrList.size() == 1) { - // Avoid nested OrDescr - return descrList.get(0).getDescr(); - } else { - OrDescr orDescr = new OrDescr(); - // For example, in case of A() or B() or C(), - // Parser creates AST like this: - // lhsOr - // / \ - // A() lhsOr - // / \ - // B() C() - // So, we need to flatten it so that OrDescr has A(), B() and C() as children. - List flattenedDescrs = flattenOrDescr(descrList); - flattenedDescrs.forEach(orDescr::addDescr); - return orDescr; - } - } - - private List flattenOrDescr(List descrList) { - List flattenedDescrs = new ArrayList<>(); - for (DescrNodePair descrNodePair : descrList) { - BaseDescr descr = descrNodePair.getDescr(); - ParseTree node = descrNodePair.getNode(); // parser node corresponding to the descr - if (descr instanceof OrDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { - // sibling OrDescr should be flattened unless it's explicitly enclosed by parenthesis - flattenedDescrs.addAll(((OrDescr) descr).getDescrs()); - } else { - flattenedDescrs.add(descr); - } - } - return flattenedDescrs; - } - - @Override - public BaseDescr visitLhsAnd(DRLParser.LhsAndContext ctx) { - return createAndDescr(ctx); - } - - private BaseDescr createAndDescr(ParserRuleContext ctx) { - // For flatten nested AndDescr logic, we call visitDescrChildrenForDescrNodePair instead of usual visitDescrChildren - List descrList = visitDescrChildrenForDescrNodePair(ctx); - if (descrList.size() == 1) { - // Avoid nested AndDescr - return descrList.get(0).getDescr(); - } else { - AndDescr andDescr = new AndDescr(); - // For example, in case of A() and B() and C(), - // Parser creates AST like this: - // lhsAnd - // / \ - // A() lhsAnd - // / \ - // B() C() - // So, we need to flatten it so that AndDescr has A(), B() and C() as children. - List flattenedDescrs = flattenAndDescr(descrList); - flattenedDescrs.forEach(andDescr::addDescr); - return andDescr; - } - } - - private List flattenAndDescr(List descrList) { - List flattenedDescrs = new ArrayList<>(); - for (DescrNodePair descrNodePair : descrList) { - BaseDescr descr = descrNodePair.getDescr(); - ParseTree node = descrNodePair.getNode(); // parser node corresponding to the descr - if (descr instanceof AndDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { - // sibling AndDescr should be flattened unless it's explicitly enclosed by parenthesis - flattenedDescrs.addAll(((AndDescr) descr).getDescrs()); - } else { - flattenedDescrs.add(descr); - } - } - return flattenedDescrs; - } - - @Override - public BaseDescr visitLhsAndDef(DRLParser.LhsAndDefContext ctx) { - return createAndDescr(ctx); - } - - @Override - public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { - return visitDescrChildren(ctx).get(0); // lhsUnary has only one child - } - - private void populateStartEnd(BaseDescr descr, ParserRuleContext ctx) { - descr.setStartCharacter(ctx.getStart().getStartIndex()); - // TODO: Current DRL6Parser adds +1 for EndCharacter but it doesn't look reasonable. At the moment, I don't add. Instead, I fix unit tests. - // I will revisit if this is the right approach. - descr.setEndCharacter(ctx.getStop().getStopIndex()); - } - - /** - * This is a special version of visitChildren(). - * This collects children BaseDescr objects and returns them as a list. - */ - private List visitDescrChildren(RuleNode node) { - List aggregator = new ArrayList<>(); - int n = node.getChildCount(); - - for (int i = 0; i < n && this.shouldVisitNextChild(node, aggregator); ++i) { - ParseTree c = node.getChild(i); - Object childResult = c.accept(this); - if (childResult instanceof BaseDescr) { - aggregator.add((BaseDescr) childResult); - } - } - return aggregator; - } - - // This method is used when the parent descr requires children parser node information for composing the descr. - // Ideally, we should use visitDescrChildren as possible and use the returned Descr object to compose the parent descr. - // However, for example, in flatten OrDescr/AndDescr logic, - // enhancing the returned Descr object of visitLhsExpressionEnclosed() (e.g. adding 'enclosed' flag to OrDescr/AndDescr) could be intrusive just for composing the parent descr. - private List visitDescrChildrenForDescrNodePair(RuleNode node) { - List aggregator = new ArrayList<>(); - int n = node.getChildCount(); - - for (int i = 0; i < n && this.shouldVisitNextChild(node, aggregator); ++i) { - ParseTree c = node.getChild(i); - Object childResult = c.accept(this); - if (childResult instanceof BaseDescr) { - aggregator.add(new DescrNodePair((BaseDescr) childResult, c)); // pairing the returned Descr and the parser node - } - } - return aggregator; - } - - private static class DescrNodePair { - private final BaseDescr descr; // returned Descr object - private final ParseTree node; // parser node corresponding to the descr. This is used for composing the parent descr. - - private DescrNodePair(BaseDescr descr, ParseTree node) { - this.descr = descr; - this.node = node; - } - - public BaseDescr getDescr() { - return descr; - } - - public ParseTree getNode() { - return node; - } - } - - /** - * Return the text of constraint as-is - */ - private String visitConstraintChildren(ParserRuleContext ctx) { - return getTokenTextPreservingWhitespace(ctx, tokenStream); - } -} \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md deleted file mode 100644 index c521ee6d14f..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md +++ /dev/null @@ -1,38 +0,0 @@ -## drools-parser - -This module is a reimplementation of the DRL (Drools Rule Language) parser based on ANTLR4. - -The current [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java) is based on ANTLR3 and contains a lot of custom modifications, which is hard to maintain. This new module should keep the separation between the parser syntax (`DRLParser.g4`) and the Descr generation (`DRLVisitorImpl.java`). - -This module started with a part of LSP to develop DRL editors, but it is not limited to that. This module will also replace DRL6Parser in the drools code base. - -### How is this developed? - -1. The starting point is [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java). While it contains lots of customizations, we can map its javadoc (e.g. `packageStatement := PACKAGE qualifiedIdentifier SEMICOLON?`) to `DRLParser.g4` (e.g. `packagedef : PACKAGE name=drlQualifiedName SEMI? ;`). -2. `DRLLexer.g4` is written to define tokens for DRL. -3. `DRLLexer.g4` imports `JavaLexer.g4` to reuse Java tokens. `DRLParser.g4` imports `JavaParser.g4` to reuse Java grammar. These Java parser files are distributed by ANTLR4 under BSD license. -4. In `DRLLexer.g4`, basically define tokens with a prefix "DRL_" to clarify they are DRL keywords. -5. In `DRLParser.g4`, define parser rules with a prefix "drl" if the rule name conflicts with `JavaParser.g4`. Sometimes we need to do that, because such a rule may contain DRL keywords. -6. (As of 2023/10/31) this parser doesn't deeply parse rule RHS (just multiple `RHS_CHUNK`s), because Drools passes RHS text to drools-compiler as-is. In case of developing DRL editors, we may need to integrate another Java LSP to support RHS code completion, etc. -7. LHS constraint (e.g. `age > 30`) is also handled as text. Further processing will be done in the later compiler phase. -8. `DRLParser` processes a DRL text and produces an AST(abstract syntax tree). Then apply `DRLVisitorImpl` to generate PackageDescr following the visitor pattern. So the main work would be implementing `DRLParser.g4` and `DRLVisitorImpl`. -9. Errors are handled by `DRLErrorListener` -10. (As of 2023/10/31) We have 2 test classes. `DRLParserTest` is a very basic test to check if the parser can parse DRL. `MiscDRLParserTest` contains various DRL syntax to check if the parser generates correct Descr objects. `MiscDRLParserTest` was ported from [RuleParserTest](https://github.com/apache/incubator-kie-drools/blob/main/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java) so that we can ensure the compatibility of generated Descr objects between the current implementation and the new one. -11. As `DRL6Parser` contains hard-coded customizations, sometimes we need to read and understand the `DRL6Parser` source codes to meet the compatibility. -12. (As of 2023/10/31) `MiscDRLParserTest` still has several test cases with `@Disabled` which are relatively lower priority or edge cases. They need to be resolved at some point in the future. To fix the issues, file a JIRA, remove the `@Disabled` annotation, and fix the implementation to pass the test case. - -### Next steps - -1. Create a feature branch in drools repo and replace `DRL6Parser` with this new parser. -2. We will detect issues in the new parser by running the existing tests in drools repo. If we find any issues, we will fix them in the new parser and add new tests to cover them. Such tests would be more or less Descr comparison tests, so we would add a new test class which is similar to `MiscDRLParserTest`. - -### Refactoring candidates -- `DRLParserHelper` and `DRLParserWrapper` have some duplicated code and purpose. We can merge them into one class. -- `MiscDRLParserTest` can be cleaner and fixed to align with SonarLint suggestions. -- Constraint related parser rules after `conditionalOrExpression` are written in antlr3 style. They could be refactored to antlr4 style (like `lhsExpression`). - -### Development tips -- IntelliJ IDEA has an ANTLR4 plugin, which "ANTLR Preview" window displays a parse tree. It is very useful to debug the parser rules. - -### Resources -[The Definitive ANTLR 4 Reference](https://pragprog.com/titles/tpantlr2/the-definitive-antlr-4-reference/) \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java deleted file mode 100644 index 19ec4735363..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -import java.util.Collections; -import java.util.List; - -import org.antlr.v4.runtime.CharStreams; -import org.antlr.v4.runtime.CommonTokenStream; -import org.antlr.v4.runtime.RecognitionException; -import org.drools.drl.ast.descr.BaseDescr; -import org.drools.drl.ast.descr.ConstraintConnectiveDescr; -import org.drools.drl.parser.DrlExprParser; -import org.drools.drl.parser.DroolsParserException; -import org.kie.internal.builder.conf.LanguageLevelOption; - -/** - * This is a helper class that provides helper methods to parse expressions - * using both the DRLExpressions parser and the DRLExprTree parser. - */ -public class Drl10ExprParser implements DrlExprParser { - - private ParserHelper helper = null; - - private final LanguageLevelOption languageLevel; - - public Drl10ExprParser(LanguageLevelOption languageLevel) { - this.languageLevel = languageLevel; - } - - /** Parse an expression from text */ - public ConstraintConnectiveDescr parse(final String text) { - ConstraintConnectiveDescr constraint = null; - try { - DRLLexer lexer = new DRLLexer(CharStreams.fromString(text)); - CommonTokenStream input = new CommonTokenStream(lexer); - helper = new ParserHelper(input, null, languageLevel); - DRLExpressions parser = new DRL6Expressions(input, helper); - 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); - } - } catch (RecognitionException e) { - helper.reportError(e); - } - return constraint; - } - - public String getLeftMostExpr() { - return helper != null ? helper.getLeftMostExpr() : null; - } - - /** - * @return true if there were parser errors. - */ - public boolean hasErrors() { - return helper != null && helper.hasErrors(); - } - - /** - * @return a list of errors found while parsing. - */ - @SuppressWarnings("unchecked") - public List getErrors() { - return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; - } - -} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java deleted file mode 100644 index abf586c55d0..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java +++ /dev/null @@ -1,250 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.antlr.v4.runtime.FailedPredicateException; -import org.antlr.v4.runtime.NoViableAltException; -import org.antlr.v4.runtime.RecognitionException; -import org.antlr.v4.runtime.Token; -import org.drools.drl.parser.DRLFactory; -import org.drools.drl.parser.DroolsParserException; -import org.drools.drl.parser.lang.DroolsParaphraseTypes; -import org.kie.internal.builder.conf.LanguageLevelOption; - -/** - * Helper class that generates DroolsParserException with user friendly error - * messages. - * - * @see DroolsParserException - */ -public class DroolsParserExceptionFactory { - public final static String NO_VIABLE_ALT_MESSAGE = "Line %1$d:%2$d no viable alternative at input '%3$s'%4$s"; - public final static String FAILED_PREDICATE_MESSAGE = "Line %1$d:%2$d rule '%3$s' failed predicate: {%4$s}?%5$s"; - public final static String TRAILING_SEMI_COLON_NOT_ALLOWED_MESSAGE = "Line %1$d:%2$d trailing semi-colon not allowed%3$s"; - public final static String PARSER_LOCATION_MESSAGE_COMPLETE = " in %1$s %2$s"; - public final static String PARSER_LOCATION_MESSAGE_PART = " in %1$s"; - public final static String UNEXPECTED_EXCEPTION = "Line %1$d:%2$d unexpected exception at input '%3$s'. Exception: %4$s. Stack trace:\n %5$s"; - - private final Collection> paraphrases; - - // TODO: need to deal with this array - private String[] tokenNames = null; - - private final LanguageLevelOption languageLevel; - - /** - * DroolsParserErrorMessages constructor. - * - * @param tokenNames - * tokenNames generated by ANTLR - * @param paraphrases - * paraphrases parser structure - */ - public DroolsParserExceptionFactory(Collection> paraphrases, - LanguageLevelOption languageLevel) { - this.paraphrases = paraphrases; - this.languageLevel = languageLevel; - } - - /** - * This method creates a DroolsParserException for trailing semicolon - * exception, full of information. - * - * @param line - * line number - * @param column - * column position - * @param offset - * char offset - * @return DroolsParserException filled. - */ - public DroolsParserException createTrailingSemicolonException( int line, - int column, - int offset ) { - String message = String - .format( - TRAILING_SEMI_COLON_NOT_ALLOWED_MESSAGE, - line, - column, - formatParserLocation() ); - - return new DroolsParserException( "ERR 104", - message, - line, - column, - offset, - null ); - } - - /** - * This method creates a DroolsParserException full of information. - * - * @param e - * original exception - * @return DroolsParserException filled. - */ - public DroolsParserException createDroolsException( RecognitionException e ) { - List codeAndMessage = createErrorMessage( e ); - return new DroolsParserException( codeAndMessage.get( 1 ), - codeAndMessage - .get( 0 ), - // TODO verify this is correct - e.getOffendingToken().getLine(), - e.getOffendingToken().getCharPositionInLine(), - e.getOffendingToken().getStartIndex(), - e ); - } - - /** - * This will take a RecognitionException, and create a sensible error - * message out of it - */ - private List createErrorMessage( RecognitionException e ) { - List codeAndMessage = new ArrayList<>( 2 ); - String message; - if ( e instanceof NoViableAltException ) { - // NoViableAltException nvae = (NoViableAltException) e; - message = String.format( - NO_VIABLE_ALT_MESSAGE, - // TODO verify this is correct - e.getOffendingToken().getLine(), - e.getOffendingToken().getCharPositionInLine(), - getBetterToken( e.getOffendingToken() ), - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 101" ); - } else if ( e instanceof FailedPredicateException ) { - FailedPredicateException fpe = (FailedPredicateException) e; - String ruleName = fpe.getRecognizer().getRuleNames()[fpe.getRuleIndex()]; - message = String.format( - FAILED_PREDICATE_MESSAGE, - // TODO verify this is correct - e.getOffendingToken().getLine(), - e.getOffendingToken().getCharPositionInLine(), - ruleName, - fpe.getPredicate(), - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 103" ); - } - if ( codeAndMessage.get( 0 ).length() == 0 ) { - codeAndMessage.add( "?????" ); - } - return codeAndMessage; - } - - public DroolsParserException createDroolsException( Exception e, - Token token ) { - StringWriter sw = new StringWriter(); - e.printStackTrace( new PrintWriter(sw) ); - return new DroolsParserException( String.format( - DroolsParserExceptionFactory.UNEXPECTED_EXCEPTION, - token.getLine(), - token.getCharPositionInLine(), - getBetterToken( token ), - e.toString(), - sw.toString() ), - e ); - - } - - /** - * This will take Paraphrases stack, and create a sensible location - */ - private String formatParserLocation() { - StringBuilder sb = new StringBuilder(); - if ( paraphrases != null ) { - for ( Map map : paraphrases ) { - for ( Entry activeEntry : map.entrySet() ) { - if ( activeEntry.getValue().length() == 0 ) { - String kStr = getLocationName( activeEntry.getKey() ); - if( kStr.length() > 0 ){ - sb.append( String.format( PARSER_LOCATION_MESSAGE_PART, kStr ) ); - } - } else { - sb.append( String.format( PARSER_LOCATION_MESSAGE_COMPLETE, - getLocationName( activeEntry.getKey() ), - activeEntry.getValue() ) ); - } - } - } - } - return sb.toString(); - } - - /** - * Returns a string based on Paraphrase Type - * - * @param type - * Paraphrase Type - * @return a string representing the - */ - private String getLocationName( DroolsParaphraseTypes type ) { - switch ( type ) { - case PACKAGE : - return "package"; - case IMPORT : - return "import"; - case FUNCTION_IMPORT : - return "function import"; - case ACCUMULATE_IMPORT : - return "accumulate import"; - case GLOBAL : - return "global"; - case FUNCTION : - return "function"; - case QUERY : - return "query"; - case TEMPLATE : - return "template"; - case RULE : - return "rule"; - case RULE_ATTRIBUTE : - return "rule attribute"; - case PATTERN : - return "pattern"; - case EVAL : - return "eval"; - default : - return ""; - } - } - - /** - * Helper method that creates a user friendly token definition - * - * @param token - * token - * @return user friendly token definition - */ - private String getBetterToken( Token token ) { - if ( token == null ) { - return ""; - } - return DRLFactory.getBetterToken(token.getType(), token.getText(), languageLevel); - } -} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java deleted file mode 100644 index f729115b7ca..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java +++ /dev/null @@ -1,678 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.drools.drl10.parser; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Deque; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.antlr.runtime.RecognizerSharedState; -import org.antlr.v4.runtime.CommonToken; -import org.antlr.v4.runtime.RecognitionException; -import org.antlr.v4.runtime.Token; -import org.antlr.v4.runtime.TokenStream; -import org.drools.drl.ast.descr.AttributeDescr; -import org.drools.drl.ast.descr.BaseDescr; -import org.drools.drl.ast.dsl.AbstractClassTypeDeclarationBuilder; -import org.drools.drl.ast.dsl.AccumulateDescrBuilder; -import org.drools.drl.ast.dsl.AccumulateImportDescrBuilder; -import org.drools.drl.ast.dsl.AttributeDescrBuilder; -import org.drools.drl.ast.dsl.AttributeSupportBuilder; -import org.drools.drl.ast.dsl.BehaviorDescrBuilder; -import org.drools.drl.ast.dsl.CEDescrBuilder; -import org.drools.drl.ast.dsl.CollectDescrBuilder; -import org.drools.drl.ast.dsl.ConditionalBranchDescrBuilder; -import org.drools.drl.ast.dsl.DeclareDescrBuilder; -import org.drools.drl.ast.dsl.DescrBuilder; -import org.drools.drl.ast.dsl.DescrFactory; -import org.drools.drl.ast.dsl.EntryPointDeclarationDescrBuilder; -import org.drools.drl.ast.dsl.EnumDeclarationDescrBuilder; -import org.drools.drl.ast.dsl.EnumLiteralDescrBuilder; -import org.drools.drl.ast.dsl.EvalDescrBuilder; -import org.drools.drl.ast.dsl.FieldDescrBuilder; -import org.drools.drl.ast.dsl.ForallDescrBuilder; -import org.drools.drl.ast.dsl.FunctionDescrBuilder; -import org.drools.drl.ast.dsl.GlobalDescrBuilder; -import org.drools.drl.ast.dsl.GroupByDescrBuilder; -import org.drools.drl.ast.dsl.ImportDescrBuilder; -import org.drools.drl.ast.dsl.NamedConsequenceDescrBuilder; -import org.drools.drl.ast.dsl.PackageDescrBuilder; -import org.drools.drl.ast.dsl.PatternContainerDescrBuilder; -import org.drools.drl.ast.dsl.PatternDescrBuilder; -import org.drools.drl.ast.dsl.QueryDescrBuilder; -import org.drools.drl.ast.dsl.RuleDescrBuilder; -import org.drools.drl.ast.dsl.TypeDeclarationDescrBuilder; -import org.drools.drl.ast.dsl.UnitDescrBuilder; -import org.drools.drl.ast.dsl.WindowDeclarationDescrBuilder; -import org.drools.drl.parser.DroolsParserException; -import org.drools.drl.parser.lang.DroolsEditorType; -import org.drools.drl.parser.lang.DroolsParaphraseTypes; -import org.drools.drl.parser.lang.DroolsSentence; -import org.drools.drl.parser.lang.DroolsSentenceType; -import org.drools.drl.parser.lang.DroolsSoftKeywords; -import org.drools.drl.parser.lang.DroolsToken; -import org.kie.internal.builder.conf.LanguageLevelOption; - -/** - * This is a class to hold all the helper functions/methods used - * by the DRL parser - */ -public class ParserHelper { - public final String[] statementKeywords = new String[]{ - DroolsSoftKeywords.PACKAGE, - DroolsSoftKeywords.UNIT, - DroolsSoftKeywords.IMPORT, - DroolsSoftKeywords.GLOBAL, - DroolsSoftKeywords.DECLARE, - DroolsSoftKeywords.FUNCTION, - DroolsSoftKeywords.RULE, - DroolsSoftKeywords.QUERY - }; - - public List errors = new ArrayList<>(); - public LinkedList editorInterface = null; - public boolean isEditorInterfaceEnabled = false; - private Deque> paraphrases = new ArrayDeque<>(); - - // parameters from parser - private DroolsParserExceptionFactory errorMessageFactory = null; - private TokenStream input = null; - private RecognizerSharedState state = null; - - private String leftMostExpr = null; - - // helper attribute - private boolean hasOperator = false; - - private final LanguageLevelOption languageLevel; - - public ParserHelper(TokenStream input, - RecognizerSharedState state, - LanguageLevelOption languageLevel) { - this.errorMessageFactory = new DroolsParserExceptionFactory( paraphrases, languageLevel ); - this.input = input; - this.state = state; - this.languageLevel = languageLevel; - } - - public LinkedList getEditorInterface() { - return editorInterface; - } - - public void setLeftMostExpr( String value ) { - this.leftMostExpr = value; - } - - public String getLeftMostExpr() { - return this.leftMostExpr; - } - - public void enableEditorInterface() { - isEditorInterfaceEnabled = true; - } - - public void disableEditorInterface() { - isEditorInterfaceEnabled = false; - } - - public void setHasOperator( boolean hasOperator ) { - this.hasOperator = hasOperator; - } - - public boolean getHasOperator() { - return hasOperator; - } - - public void beginSentence( DroolsSentenceType sentenceType ) { - if ( isEditorInterfaceEnabled ) { - if ( null == editorInterface ) { - editorInterface = new LinkedList<>(); - } - if (editorInterface.isEmpty()){ - DroolsSentence sentence = new DroolsSentence(); - sentence.setType( sentenceType ); - editorInterface.add( sentence ); - } - } - } - - public DroolsSentence getActiveSentence() { - return editorInterface.getLast(); - } - - public void emit( List< ? > tokens, - DroolsEditorType editorType ) { - if ( isEditorInterfaceEnabled && tokens != null ) { - for ( Object activeObject : tokens ) { - emit( (Token) activeObject, - editorType ); - } - } - } - - public void emit( Token token, - DroolsEditorType editorType ) { - if ( isEditorInterfaceEnabled && token != null && editorType != null ) { - ((DroolsToken) token).setEditorType( editorType ); - getActiveSentence().addContent( (DroolsToken) token ); - } - } - - public void emit( int activeContext ) { - if ( isEditorInterfaceEnabled ) { - getActiveSentence().addContent( activeContext ); - } - } - - public DroolsToken getLastTokenOnList( LinkedList< ? > list ) { - DroolsToken lastToken = null; - for ( Object object : list ) { - if ( object instanceof DroolsToken ) { - lastToken = (DroolsToken) object; - } - } - return lastToken; - } - - public String retrieveLT( int LTNumber ) { - if ( null == input ) return null; - if ( null == input.LT( LTNumber ) ) return null; - if ( null == input.LT( LTNumber ).getText() ) return null; - - return input.LT( LTNumber ).getText(); - } - - public boolean validateLT( int LTNumber, - String text ) { - String text2Validate = retrieveLT( LTNumber ); - return validateText( text, text2Validate ); - } - - private boolean validateText( String text, String text2Validate ) { - return text2Validate != null && text2Validate.equals( text ); - } - - public boolean isPluggableEvaluator( int offset, - boolean negated ) { - String text2Validate = retrieveLT( offset ); - return text2Validate != null && DroolsSoftKeywords.isOperator(text2Validate, negated); - } - - public boolean isPluggableEvaluator( boolean negated ) { - return isPluggableEvaluator( 1, - negated ); - } - - public boolean validateIdentifierKey( String text ) { - return validateLT( 1, - text ); - } - - public boolean validateCEKeyword( int index ) { - String text2Validate = retrieveLT( index ); - return validateText( text2Validate, - DroolsSoftKeywords.NOT ) || - validateText( text2Validate, - DroolsSoftKeywords.EXISTS ) || - validateText( text2Validate, - DroolsSoftKeywords.FORALL ) || - validateText( text2Validate, - DroolsSoftKeywords.AND ) || - validateText( text2Validate, - DroolsSoftKeywords.OR ) || - validateText( text2Validate, - DroolsSoftKeywords.COLLECT ) || - validateText( text2Validate, - DroolsSoftKeywords.FROM ) || - validateText( text2Validate, - DroolsSoftKeywords.END ) || - validateText( text2Validate, - DroolsSoftKeywords.EVAL ) || - validateText( text2Validate, - DroolsSoftKeywords.OVER ) || - validateText( text2Validate, - DroolsSoftKeywords.THEN ); - } - - public boolean validateStatement( int index ) { - boolean ret = false; - String text2Validate = retrieveLT( index ); - for ( String st : statementKeywords ) { - if ( validateText( text2Validate, - st ) ) { - ret = true; - break; - } - } - return ret || validateAttribute( index ); - } - - public boolean validateAttribute( int index ) { - String text2Validate = retrieveLT( index ); - return validateText( text2Validate, - DroolsSoftKeywords.SALIENCE ) || - validateText( text2Validate, - DroolsSoftKeywords.ENABLED ) || - (validateText( text2Validate, - DroolsSoftKeywords.NO ) && - validateLT( index + 1, - "-" ) && - validateLT( index + 2, - DroolsSoftKeywords.LOOP )) || - (validateText( text2Validate, - DroolsSoftKeywords.AUTO ) && - validateLT( index + 1, - "-" ) && - validateLT( index + 2, - DroolsSoftKeywords.FOCUS )) || - (validateText( text2Validate, - DroolsSoftKeywords.LOCK ) && - validateLT( index + 1, - "-" ) && - validateLT( index + 2, - DroolsSoftKeywords.ON ) && - validateLT( index + 3, - "-" ) && - validateLT( index + 4, - DroolsSoftKeywords.ACTIVE )) || - (validateText( text2Validate, - DroolsSoftKeywords.AGENDA ) && - validateLT( index + 1, - "-" ) && - validateLT( index + 2, - DroolsSoftKeywords.GROUP )) || - (validateText( text2Validate, - DroolsSoftKeywords.ACTIVATION ) && - validateLT( index + 1, - "-" ) && - validateLT( index + 2, - DroolsSoftKeywords.GROUP )) || - (validateText( text2Validate, - DroolsSoftKeywords.RULEFLOW ) && - validateLT( index + 1, - "-" ) && - validateLT( index + 2, - DroolsSoftKeywords.GROUP )) || - (validateText( text2Validate, - DroolsSoftKeywords.DATE ) && - validateLT( index + 1, - "-" ) && - validateLT( index + 2, - DroolsSoftKeywords.EFFECTIVE )) || - (validateText( text2Validate, - DroolsSoftKeywords.DATE ) && - validateLT( index + 1, - "-" ) && - validateLT( index + 2, - DroolsSoftKeywords.EXPIRES )) || - validateText( text2Validate, - DroolsSoftKeywords.DIALECT ) || - validateText( text2Validate, - DroolsSoftKeywords.CALENDARS ) || - validateText( text2Validate, - DroolsSoftKeywords.TIMER ) || - validateText( text2Validate, - DroolsSoftKeywords.DURATION ) || - validateText( text2Validate, - DroolsSoftKeywords.REFRACT ) || - validateText( text2Validate, - DroolsSoftKeywords.DIRECT ); - } - - public void reportError( RecognitionException ex ) { - // if we've already reported an error and have not matched a token - // yet successfully, don't report any errors. - if ( state.errorRecovery ) { - return; - } - state.errorRecovery = true; - - errors.add( errorMessageFactory.createDroolsException( ex ) ); - } - - public void reportError( Exception e ) { - try { - errors.add( errorMessageFactory.createDroolsException( e, - input.LT( 1 ) ) ); - } catch (Exception ignored) { - errors.add(new DroolsParserException( "Unexpected error: " + e.getMessage(), e )); - } - } - - /** return the raw DroolsParserException errors */ - public List getErrors() { - return errors; - } - - /** Return a list of pretty strings summarising the errors */ - public List getErrorMessages() { - List messages = new ArrayList<>( errors.size() ); - - for ( DroolsParserException activeException : errors ) { - messages.add( activeException.getMessage() ); - } - - return messages; - } - - /** return true if any parser errors were accumulated */ - public boolean hasErrors() { - return !errors.isEmpty(); - } - - /** - * Method that adds a paraphrase type into paraphrases stack. - * - * @param type - * paraphrase type - */ - public void pushParaphrases( DroolsParaphraseTypes type ) { - Map activeMap = new HashMap<>(); - activeMap.put( type, - "" ); - paraphrases.push( activeMap ); - } - - public Map popParaphrases() { - return paraphrases.pop(); - } - - /** - * Method that sets paraphrase value for a type into paraphrases stack. - * - * @param type - * paraphrase type - * @param value - * paraphrase value - */ - public void setParaphrasesValue( DroolsParaphraseTypes type, - String value ) { - paraphrases.peek().put( type, - value ); - } - - void setStart( DescrBuilder< ? , ? > db ) { - setStart( db, - input.LT( 1 ) ); - } - - void setStart( DescrBuilder< ? , ? > db, - Token first ) { - if ( db != null && first != null ) { - db.startCharacter( ((CommonToken) first).getStartIndex() ).startLocation( first.getLine(), - first.getCharPositionInLine() ); - } - } - - void setStart( BaseDescr descr, - Token first ) { - if ( descr != null && first != null ) { - descr.setLocation( first.getLine(), - first.getCharPositionInLine() ); - descr.setStartCharacter( ((CommonToken) first).getStartIndex() ); - } - } - - void setEnd( BaseDescr descr ) { - Token last = input.LT( -1 ); - if ( descr != null && last != null ) { - int endLocation = last.getText() != null ? last.getCharPositionInLine() + last.getText().length() - 1 : last.getCharPositionInLine(); - descr.setEndCharacter( ((CommonToken) last).getStopIndex() + 1 ); - descr.setEndLocation( last.getLine(), - endLocation ); - } - } - - void setEnd( DescrBuilder< ? , ? > db ) { - Token last = input.LT( -1 ); - if ( db != null && last != null ) { - int endLocation = last.getText() != null ? last.getCharPositionInLine() + last.getText().length() - 1 : last.getCharPositionInLine(); - db.endCharacter( ((CommonToken) last).getStopIndex() + 1 ).endLocation( last.getLine(), - endLocation ); - } - } - - @SuppressWarnings("unchecked") - public > T start( DescrBuilder< ? , ? > ctxBuilder, - Class clazz, - String param ) { - if ( state.backtracking == 0 ) { - if ( PackageDescrBuilder.class.isAssignableFrom( clazz ) ) { - pushParaphrases( DroolsParaphraseTypes.PACKAGE ); - beginSentence( DroolsSentenceType.PACKAGE ); - setStart( ctxBuilder ); - } else if ( ImportDescrBuilder.class.isAssignableFrom( clazz ) ) { - ImportDescrBuilder imp; - if ( validateLT( 2, - DroolsSoftKeywords.FUNCTION ) || - validateLT( 2, - DroolsSoftKeywords.STATIC ) ) { - imp = ctxBuilder == null ? - DescrFactory.newPackage().newFunctionImport() : - ((PackageDescrBuilder) ctxBuilder).newFunctionImport(); - } else { - imp = ctxBuilder == null ? - DescrFactory.newPackage().newImport() : - ((PackageDescrBuilder) ctxBuilder).newImport(); - } - pushParaphrases( DroolsParaphraseTypes.IMPORT ); - beginSentence( DroolsSentenceType.IMPORT_STATEMENT ); - setStart( imp ); - return (T) imp; - } else if ( UnitDescrBuilder.class.isAssignableFrom( clazz ) ) { - UnitDescrBuilder imp = ctxBuilder == null ? - DescrFactory.newPackage().newUnit() : - ((PackageDescrBuilder) ctxBuilder).newUnit(); - pushParaphrases( DroolsParaphraseTypes.UNIT ); - beginSentence( DroolsSentenceType.UNIT ); - setStart( imp ); - return (T) imp; - } else if ( AccumulateImportDescrBuilder.class.isAssignableFrom( clazz ) ) { - AccumulateImportDescrBuilder imp = ctxBuilder == null ? - DescrFactory.newPackage().newAccumulateImport() : - ((PackageDescrBuilder) ctxBuilder).newAccumulateImport(); - pushParaphrases( DroolsParaphraseTypes.ACCUMULATE_IMPORT ); - beginSentence( DroolsSentenceType.ACCUMULATE_IMPORT_STATEMENT ); - setStart( imp ); - return (T) imp; - } else if ( GlobalDescrBuilder.class.isAssignableFrom( clazz ) ) { - GlobalDescrBuilder global = ctxBuilder == null ? - DescrFactory.newPackage().newGlobal() : - ((PackageDescrBuilder) ctxBuilder).newGlobal(); - pushParaphrases( DroolsParaphraseTypes.GLOBAL ); - beginSentence( DroolsSentenceType.GLOBAL ); - setStart( global ); - return (T) global; - } else if ( DeclareDescrBuilder.class.isAssignableFrom( clazz ) ) { - DeclareDescrBuilder declare = ctxBuilder == null ? - DescrFactory.newPackage().newDeclare() : - ((PackageDescrBuilder) ctxBuilder).newDeclare(); - return (T) declare; - } else if ( TypeDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { - TypeDeclarationDescrBuilder declare = ctxBuilder == null ? - DescrFactory.newPackage().newDeclare().type() : - ((DeclareDescrBuilder) ctxBuilder).type(); - pushParaphrases( DroolsParaphraseTypes.TYPE_DECLARE ); - beginSentence( DroolsSentenceType.TYPE_DECLARATION ); - setStart( declare ); - return (T) declare; - } else if ( EnumDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { - EnumDeclarationDescrBuilder declare = ctxBuilder == null ? - DescrFactory.newPackage().newDeclare().enumerative() : - ((DeclareDescrBuilder) ctxBuilder).enumerative(); - pushParaphrases( DroolsParaphraseTypes.ENUM_DECLARE ); - beginSentence( DroolsSentenceType.ENUM_DECLARATION ); - setStart( declare ); - return (T) declare; - }else if ( EntryPointDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { - EntryPointDeclarationDescrBuilder declare = ctxBuilder == null ? - DescrFactory.newPackage().newDeclare().entryPoint() : - ((DeclareDescrBuilder) ctxBuilder).entryPoint(); - pushParaphrases( DroolsParaphraseTypes.ENTRYPOINT_DECLARE ); - beginSentence( DroolsSentenceType.ENTRYPOINT_DECLARATION ); - setStart( declare ); - return (T) declare; - } else if ( WindowDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { - WindowDeclarationDescrBuilder declare = ctxBuilder == null ? - DescrFactory.newPackage().newDeclare().window() : - ((DeclareDescrBuilder) ctxBuilder).window(); - pushParaphrases( DroolsParaphraseTypes.WINDOW_DECLARE ); - beginSentence( DroolsSentenceType.WINDOW_DECLARATION ); - setStart( declare ); - return (T) declare; - } else if ( FieldDescrBuilder.class.isAssignableFrom( clazz ) ) { - FieldDescrBuilder field = ((AbstractClassTypeDeclarationBuilder) ctxBuilder).newField( param ); - setStart( field ); - return (T) field; - } else if ( EnumLiteralDescrBuilder.class.isAssignableFrom( clazz ) ) { - EnumLiteralDescrBuilder literal = ((EnumDeclarationDescrBuilder) ctxBuilder).newEnumLiteral( param ); - setStart( literal ); - return (T) literal; - } else if ( FunctionDescrBuilder.class.isAssignableFrom( clazz ) ) { - FunctionDescrBuilder function; - if ( ctxBuilder == null ) { - function = DescrFactory.newPackage().newFunction(); - } else { - PackageDescrBuilder pkg = (PackageDescrBuilder) ctxBuilder; - function = pkg.newFunction().namespace( pkg.getDescr().getName() ); - AttributeDescr attribute = pkg.getDescr().getAttribute( "dialect" ); - if ( attribute != null ) { - function.dialect( attribute.getValue() ); - } - } - pushParaphrases( DroolsParaphraseTypes.FUNCTION ); - beginSentence( DroolsSentenceType.FUNCTION ); - setStart( function ); - return (T) function; - } else if ( RuleDescrBuilder.class.isAssignableFrom( clazz ) ) { - RuleDescrBuilder rule = ctxBuilder == null ? - DescrFactory.newPackage().newRule() : - ((PackageDescrBuilder) ctxBuilder).newRule(); - pushParaphrases( DroolsParaphraseTypes.RULE ); - beginSentence( DroolsSentenceType.RULE ); - setStart( rule ); - return (T) rule; - } else if ( QueryDescrBuilder.class.isAssignableFrom( clazz ) ) { - QueryDescrBuilder query = ctxBuilder == null ? - DescrFactory.newPackage().newQuery() : - ((PackageDescrBuilder) ctxBuilder).newQuery(); - pushParaphrases( DroolsParaphraseTypes.QUERY ); - beginSentence( DroolsSentenceType.QUERY ); - setStart( query ); - return (T) query; - } else if ( AttributeDescrBuilder.class.isAssignableFrom( clazz ) ) { - AttributeDescrBuilder< ? > attribute = ((AttributeSupportBuilder< ? >) ctxBuilder).attribute(param); - setStart( attribute ); - return (T) attribute; - } else if ( EvalDescrBuilder.class.isAssignableFrom( clazz ) ) { - EvalDescrBuilder< ? > eval = ((CEDescrBuilder< ? , ? >) ctxBuilder).eval(); - pushParaphrases( DroolsParaphraseTypes.EVAL ); - beginSentence( DroolsSentenceType.EVAL ); - setStart( eval ); - return (T) eval; - } else if ( ForallDescrBuilder.class.isAssignableFrom( clazz ) ) { - ForallDescrBuilder< ? > forall = ((CEDescrBuilder< ? , ? >) ctxBuilder).forall(); - setStart( forall ); - return (T) forall; - } else if ( CEDescrBuilder.class.isAssignableFrom( clazz ) ) { - setStart( ctxBuilder ); - return (T) ctxBuilder; - } else if ( PatternDescrBuilder.class.isAssignableFrom( clazz ) ) { - PatternDescrBuilder< ? > pattern = ((PatternContainerDescrBuilder< ? , ? >) ctxBuilder).pattern(); - pushParaphrases( DroolsParaphraseTypes.PATTERN ); - setStart( pattern ); - return (T) pattern; - } else if ( CollectDescrBuilder.class.isAssignableFrom( clazz ) ) { - CollectDescrBuilder< ? > collect = ((PatternDescrBuilder< ? >) ctxBuilder).from().collect(); - setStart( collect ); - return (T) collect; - } else if ( GroupByDescrBuilder.class.isAssignableFrom(clazz) ) { - // GroupBy extends Accumulate and thus need to be before it - GroupByDescrBuilder< ? > groupBy = ((PatternDescrBuilder< ? >) ctxBuilder).from().groupBy(); - setStart( groupBy ); - return (T) groupBy; - } else if ( AccumulateDescrBuilder.class.isAssignableFrom( clazz ) ) { - AccumulateDescrBuilder< ? > accumulate = ((PatternDescrBuilder< ? >) ctxBuilder).from().accumulate(); - setStart( accumulate ); - return (T) accumulate; - } else if ( BehaviorDescrBuilder.class.isAssignableFrom( clazz ) ) { - BehaviorDescrBuilder< ? > behavior = ((PatternDescrBuilder< ? >) ctxBuilder).behavior(); - setStart( behavior ); - return (T) behavior; - } else if ( NamedConsequenceDescrBuilder.class.isAssignableFrom( clazz ) ) { - NamedConsequenceDescrBuilder< ? > namedConsequence = ((CEDescrBuilder< ? , ? >) ctxBuilder).namedConsequence(); - setStart( namedConsequence ); - return (T) namedConsequence; - } else if ( ConditionalBranchDescrBuilder.class.isAssignableFrom( clazz ) ) { - ConditionalBranchDescrBuilder< ? > conditionalBranch = ((CEDescrBuilder< ? , ? >) ctxBuilder).conditionalBranch(); - setStart( conditionalBranch ); - return (T) conditionalBranch; - } - } - return null; - } - - @SuppressWarnings("unchecked") - public > T end( Class clazz, - DescrBuilder< ? , ? > builder ) { - if ( state.backtracking == 0 ) { - if ( !(FieldDescrBuilder.class.isAssignableFrom( clazz ) || - AttributeDescrBuilder.class.isAssignableFrom( clazz ) || - CEDescrBuilder.class.isAssignableFrom( clazz ) || - CollectDescrBuilder.class.isAssignableFrom( clazz ) || - AccumulateDescrBuilder.class.isAssignableFrom( clazz ) || - ForallDescrBuilder.class.isAssignableFrom( clazz ) || - BehaviorDescrBuilder.class.isAssignableFrom( clazz ) || - ConditionalBranchDescrBuilder.class.isAssignableFrom( clazz ) || - NamedConsequenceDescrBuilder.class.isAssignableFrom( clazz )) ) { - popParaphrases(); - } - - if (RuleDescrBuilder.class.isAssignableFrom(clazz)) { - RuleDescrBuilder ruleDescrBuilder = (RuleDescrBuilder)builder; - ruleDescrBuilder.end().getDescr().afterRuleAdded(ruleDescrBuilder.getDescr()); - } - - setEnd( builder ); - return (T) builder; - } - return null; - } - - public String[] getStatementKeywords() { - return statementKeywords; - } -} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java deleted file mode 100644 index ef22da2dce3..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl10.parser; - -import org.antlr.v4.runtime.ParserRuleContext; -import org.antlr.v4.runtime.TokenStream; -import org.antlr.v4.runtime.misc.Interval; - -/** - * Collection of String utilities used by DRLParser. - * This may be merged in drools-util - */ -public class ParserStringUtils { - - private ParserStringUtils() { - } - - /** - * Strip string delimiters (e.g. "foo" -> foo) - */ - public static String safeStripStringDelimiters(String value) { - if (value != null) { - value = value.trim(); - if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { - value = value.substring(1, value.length() - 1); - } - } - return value; - } - - /** - * Get text from ParserRuleContext's CharStream without trimming whitespace - */ - public static String getTextPreservingWhitespace(ParserRuleContext ctx) { - // Using raw CharStream - int startIndex = ctx.start.getStartIndex(); - int stopIndex = ctx.stop.getStopIndex(); - if (startIndex > stopIndex) { - // no text - return ""; - } - Interval interval = new Interval(startIndex, stopIndex); - return ctx.start.getTokenSource().getInputStream().getText(interval); - } - - /** - * Get text from ParserRuleContext's CharStream without trimming whitespace - * tokenStream is required to get hidden channel token (e.g. whitespace). - * Unlike getTextPreservingWhitespace, this method reflects Lexer normalizeString - */ - public static String getTokenTextPreservingWhitespace(ParserRuleContext ctx, TokenStream tokenStream) { - return tokenStream.getText(ctx.start, ctx.stop); - } - - /** - * Just remove leading "then" - */ - public static String trimThen(String rhs) { - if (rhs.startsWith("then")) { - return rhs.substring("then".length()); - } else { - throw new DRLParserException("rhs has to start with 'then' : rhs = " + rhs); - } - } -} diff --git a/drools-drl/pom.xml b/drools-drl/pom.xml index 2fb61bb3006..91f12f3d758 100644 --- a/drools-drl/pom.xml +++ b/drools-drl/pom.xml @@ -39,7 +39,6 @@ drools-drl-ast drools-drl-extensions drools-drl-parser - drools-drl-parser-tests diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java index c7357aad4de..08eeb33edae 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java @@ -25,7 +25,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.junit.After; import org.junit.Before; import org.junit.Test; @@ -43,7 +42,7 @@ public class DRLExprParserTest { @Before public void setUp() throws Exception { new EvaluatorRegistry(); - this.parser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL6); + this.parser = new DrlExprParser(LanguageLevelOption.DRL6); } @After diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java index 5eb52e62830..649b43c37fe 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java @@ -24,7 +24,6 @@ import org.drools.drl.ast.descr.AtomicExprDescr; import org.drools.drl.ast.descr.BindingDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; -import org.drools.drl.parser.DrlExprParserFactory; import org.drools.mvel.evaluators.MatchesEvaluatorsDefinition; import org.drools.mvel.evaluators.SetEvaluatorsDefinition; import org.junit.Before; @@ -359,7 +358,7 @@ public void testProcessImplicitConstraints() throws Exception { } public ConstraintConnectiveDescr parse( final String constraint ) { - DrlExprParser parser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL6); + DrlExprParser parser = new DrlExprParser(LanguageLevelOption.DRL6); ConstraintConnectiveDescr result = parser.parse( constraint ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java index 6d14f2355c6..d4089c34601 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java @@ -48,8 +48,6 @@ public static Collection getParameters() { @Test public void testAlpha() { - - String str = "import " + Person.class.getCanonicalName() + "\n" + "rule R1 when\n" + diff --git a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java index 6e6ef96a82a..ba67c653c3e 100644 --- a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java +++ b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java @@ -20,7 +20,6 @@ import java.util.List; -import org.drools.drl.parser.DrlExprParserFactory; import org.drools.drl.parser.impl.Operator; import org.drools.drl.parser.DrlExprParser; import org.drools.drl.ast.descr.AtomicExprDescr; @@ -58,7 +57,7 @@ public ExprConstraintDescrVisitor(Pattern pattern, VerifierData data, OrderNumbe public void visit(ExprConstraintDescr descr) { - DrlExprParser drlExprParser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL5); + DrlExprParser drlExprParser = new DrlExprParser(LanguageLevelOption.DRL5); ConstraintConnectiveDescr constraintConnectiveDescr = drlExprParser.parse(descr.getExpression()); visit(constraintConnectiveDescr.getDescrs()); 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 86266a0f2d3..ca8b96ee91a 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), DRL10(false); + DRL5(false), DRL6(false), DRL6_STRICT(true); private final boolean useJavaAnnotations; diff --git a/pom.xml b/pom.xml index 40f4d9d7240..5fae74ed325 100644 --- a/pom.xml +++ b/pom.xml @@ -310,28 +310,6 @@ - - - DRL10 - - - DRL10 - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - DRL10 - - - - - - From 15854b98cc7fdde375e2044e61abe38e96114cfd Mon Sep 17 00:00:00 2001 From: mariofusco Date: Fri, 14 Jan 2022 17:19:41 +0100 Subject: [PATCH 006/141] add antlr4 based drl parser --- drools-drl/drools-drl10-parser/.gitignore | 17 +++++ drools-drl/drools-drl10-parser/pom.xml | 76 +++++++++++++++++++ .../src/main/antlr4/org/drools/parser/DRL.g4 | 64 ++++++++++++++++ .../org/drools/parser/DRLParserHelper.java | 64 ++++++++++++++++ .../org/drools/parser/DRLVisitorImpl.java | 40 ++++++++++ .../java/org/drools/parser/DRLParserTest.java | 59 ++++++++++++++ 6 files changed, 320 insertions(+) create mode 100644 drools-drl/drools-drl10-parser/.gitignore create mode 100644 drools-drl/drools-drl10-parser/pom.xml create mode 100644 drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java create mode 100644 drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java diff --git a/drools-drl/drools-drl10-parser/.gitignore b/drools-drl/drools-drl10-parser/.gitignore new file mode 100644 index 00000000000..372e03f0268 --- /dev/null +++ b/drools-drl/drools-drl10-parser/.gitignore @@ -0,0 +1,17 @@ +target/ +local/ + +# Eclipse, Netbeans and IntelliJ files +.* +!.gitignore +!.github +nbproject +*.ipr +*.iws +*.iml + +# generated files +dependency-reduced-pom.xml + +#CI +!.ci diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml new file mode 100644 index 00000000000..624344d2683 --- /dev/null +++ b/drools-drl/drools-drl10-parser/pom.xml @@ -0,0 +1,76 @@ + + + + 4.0.0 + + + org.drools + drools-lsp + 1.0.0-SNAPSHOT + + + org.drools + drools-parser + 1.0.0-SNAPSHOT + + Drools :: Parser + + + + org.drools + drools-drl-ast + 8.16.0-SNAPSHOT + + + + + org.antlr + antlr4-runtime + ${version.org.antlr4} + + + org.antlr + antlr4 + ${version.org.antlr4} + test + + + org.glassfish + javax.json + + + + + + + junit + junit + ${version.junit} + test + + + + + + + org.antlr + antlr4-maven-plugin + ${version.org.antlr4} + + + + antlr4 + + + true + false + + + + + + + + + diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 new file mode 100644 index 00000000000..e83e84dd5ff --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 @@ -0,0 +1,64 @@ +grammar DRL; + +// KEYWORDS + +PACKAGE : 'package'; +IMPORT : 'import'; +RULE : 'rule'; +WHEN : 'when'; +THEN : 'then'; +END : 'end'; + +// PARSER + +compilationunit : packagedef? importdef* ruledef* ; + +packagedef : PACKAGE FQNAME SEMICOLON? ; + +importdef : IMPORT FQNAME (DOT STAR)? SEMICOLON? ; + +ruledef : RULE IDENTIFIER WHEN lhs THEN rhs END ; + +lhs : TEXT ; + +rhs : TEXT ; + +// LITERALS + +fragment DIGIT : [0-9] ; +NUMBER : DIGIT+ ([.,] DIGIT+)? ; + +fragment LOWERCASE : [a-z] ; +fragment UPPERCASE : [A-Z] ; +LETTER : (LOWERCASE | UPPERCASE | '_' | '$') ; + +IDENTIFIER : LETTER (LETTER | DIGIT)* ; +FQNAME : IDENTIFIER (DOT IDENTIFIER)* ; + +// SEPARATORS + +LPAREN : '('; +RPAREN : ')'; +LBRACE : '{'; +RBRACE : '}'; +LBRACK : '['; +RBRACK : ']'; +COMMA : ','; +ELIPSIS : '..'; +DOT : '.'; +COLON : ':'; +SEMICOLON : ';'; +STAR : '*'; + +// OPERATORS + +EQUAL : '='; +GT : '>'; +LT : '<'; +LE : '<='; +GE : '>='; +NOTEQUAL : '!='; + +WS : [ \t\r\n\u000C\u00A0]+ -> skip ; + +fragment TEXT : .+ ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java new file mode 100644 index 00000000000..826517a0c24 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -0,0 +1,64 @@ +package org.drools.parser; + +import org.antlr.v4.runtime.CharStream; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.RuleContext; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.drools.drl.ast.descr.PackageDescr; + +public class DRLParserHelper { + + public static PackageDescr parse(String drl) { + return parseTree2PackageDescr(createParseTree(drl)); + } + + public static ParseTree createParseTree(String drl) { + CharStream inputStream = CharStreams.fromString(drl); + DRLLexer drlLexer = new DRLLexer(inputStream); + CommonTokenStream commonTokenStream = new CommonTokenStream(drlLexer); + DRLParser drlParser = new DRLParser(commonTokenStream); + return drlParser.compilationunit(); + } + + public static PackageDescr parseTree2PackageDescr(ParseTree parseTree) { + DRLVisitorImpl visitor = new DRLVisitorImpl(); + visitor.visit(parseTree); + return visitor.getPackageDescr(); + } + + public static ParseTree findNodeAtPosition(ParseTree root, int row, int col) { + for (int i = 0; i < root.getChildCount(); i++) { + ParseTree child = root.getChild(i); + Token stopToken = child instanceof TerminalNode ? ((TerminalNode)child).getSymbol() : ((ParserRuleContext)child).getStop(); + + if (endsAfter(stopToken, row, col)) { + return findNodeAtPosition(child, row, col); + } + } + return root; + } + + private static boolean endsAfter(Token token, int row, int col) { + if (token.getLine() != row) { + return token.getLine() > row; + } + int tokenLength = (token.getStopIndex() - token.getStartIndex()) + 1; + int lastTokenPosition = token.getCharPositionInLine() + tokenLength; + return lastTokenPosition >= col; + } + + public static boolean hasParentOfType(ParseTree leaf, int type) { + return findParentOfType(leaf, type) != null; + } + + public static ParseTree findParentOfType(ParseTree leaf, int type) { + if (leaf == null || (leaf instanceof RuleContext && ((RuleContext) leaf).getRuleIndex() == type)) { + return leaf; + } + return findParentOfType(leaf.getParent(), type); + } +} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java new file mode 100644 index 00000000000..780076b9ab5 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -0,0 +1,40 @@ +package org.drools.parser; + +import org.drools.drl.ast.descr.ImportDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.RuleDescr; + +public class DRLVisitorImpl extends DRLBaseVisitor { + + private final PackageDescr packageDescr = new PackageDescr(); + + @Override + public Object visitCompilationunit(DRLParser.CompilationunitContext ctx) { + return super.visitCompilationunit(ctx); + } + + @Override + public Object visitPackagedef(DRLParser.PackagedefContext ctx) { + packageDescr.setName(ctx.FQNAME().getText()); + return super.visitPackagedef(ctx); + } + + @Override + public Object visitImportdef(DRLParser.ImportdefContext ctx) { + String imp = ctx.FQNAME().getText() + (ctx.STAR() != null ? ".*" : ""); + packageDescr.addImport(new ImportDescr(imp)); + return super.visitImportdef(ctx); + } + + @Override + public Object visitRuledef(DRLParser.RuledefContext ctx) { + RuleDescr rule = new RuleDescr(ctx.IDENTIFIER().getText()); + rule.setConsequence(ctx.rhs().getText()); + packageDescr.addRule(rule); + return super.visitRuledef(ctx); + } + + public PackageDescr getPackageDescr() { + return packageDescr; + } +} diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java new file mode 100644 index 00000000000..4e4e27e8d7d --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java @@ -0,0 +1,59 @@ +package org.drools.parser; + +import org.antlr.v4.runtime.RuleContext; +import org.antlr.v4.runtime.tree.ParseTree; +import org.drools.drl.ast.descr.PackageDescr; +import org.junit.Test; + +import static org.drools.parser.DRLParserHelper.createParseTree; +import static org.drools.parser.DRLParserHelper.findNodeAtPosition; +import static org.drools.parser.DRLParserHelper.findParentOfType; +import static org.drools.parser.DRLParserHelper.parse; +import static org.junit.Assert.assertEquals; + +public class DRLParserTest { + + @Test + public void testParse() { + String drl = + "package org.test;\n" + + "import org.test.model.Person;\n" + + "rule TestRule when\n" + + " $p:Person()\n" + + "then\n" + + " System.out.println($p.getName());\n" + + "end\n"; + + PackageDescr packageDescr = parse(drl); + assertEquals("org.test", packageDescr.getName()); + + assertEquals(1, packageDescr.getImports().size()); + assertEquals("org.test.model.Person", packageDescr.getImports().get(0).getTarget()); + + assertEquals(1, packageDescr.getRules().size()); + assertEquals("TestRule", packageDescr.getRules().get(0).getName()); + assertEquals("System.out.println($p.getName());", packageDescr.getRules().get(0).getConsequence()); + } + + @Test + public void testCursorPosition() { + String drl = + "package org.test;\n" + + "import org.test.model.Person;\n" + + "rule TestRule when\n" + + " $p:Person()\n" + + "then\n" + + " System.out.println($p.getName());\n" + + "end\n"; + + int row = 4; + int col = 7; + + ParseTree parseTree = createParseTree(drl); + ParseTree node = findNodeAtPosition(parseTree, row, col); + assertEquals("Person", node.getText()); + ParseTree lhs = findParentOfType(node, DRLParser.RULE_lhs); + assertEquals(DRLParser.RULE_lhs, ((RuleContext) lhs).getRuleIndex()); + assertEquals("$p:Person()", lhs.getText()); + } +} From 4c14a0725e078b03ec0ff3d9bdc8ba9af29e88d2 Mon Sep 17 00:00:00 2001 From: mariofusco Date: Thu, 20 Jan 2022 11:02:33 +0100 Subject: [PATCH 007/141] bump to drools 8.16.0.Beta --- drools-drl/drools-drl10-parser/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml index 624344d2683..c8231a66e7d 100644 --- a/drools-drl/drools-drl10-parser/pom.xml +++ b/drools-drl/drools-drl10-parser/pom.xml @@ -20,7 +20,7 @@ org.drools drools-drl-ast - 8.16.0-SNAPSHOT + 8.16.0.Beta From 1c4bc9aa316427ddcdaa1c68a83e0b5e7280e94d Mon Sep 17 00:00:00 2001 From: mariofusco Date: Thu, 27 Jan 2022 14:01:07 +0100 Subject: [PATCH 008/141] improve node position discovery --- .../org/drools/parser/DRLParserHelper.java | 54 +++++++++++++++++-- .../java/org/drools/parser/DRLParserTest.java | 42 +++++++-------- 2 files changed, 71 insertions(+), 25 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index 826517a0c24..421624010cb 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -31,18 +31,43 @@ public static PackageDescr parseTree2PackageDescr(ParseTree parseTree) { } public static ParseTree findNodeAtPosition(ParseTree root, int row, int col) { + ParseTree lastChild = null; for (int i = 0; i < root.getChildCount(); i++) { ParseTree child = root.getChild(i); - Token stopToken = child instanceof TerminalNode ? ((TerminalNode)child).getSymbol() : ((ParserRuleContext)child).getStop(); - if (endsAfter(stopToken, row, col)) { + if (i > 0 && startsAfter(child, row, col)) { + return findNodeAtPosition(lastChild, row, col); + } + + if (endsAfter(child, row, col)) { return findNodeAtPosition(child, row, col); } + + lastChild = child; } return root; } - private static boolean endsAfter(Token token, int row, int col) { + public static Token getStartToken(ParseTree child) { + return child instanceof TerminalNode ? ((TerminalNode) child).getSymbol() : ((ParserRuleContext) child).getStart(); + } + + public static Token getStopToken(ParseTree child) { + return child instanceof TerminalNode ? ((TerminalNode) child).getSymbol() : ((ParserRuleContext) child).getStop(); + } + + private static boolean endsBefore(ParseTree node, int row, int col) { + Token token = getStopToken(node); + if (token.getLine() != row) { + return token.getLine() < row; + } + int tokenLength = (token.getStopIndex() - token.getStartIndex()) + 1; + int lastTokenPosition = token.getCharPositionInLine() + tokenLength; + return lastTokenPosition < col; + } + + private static boolean endsAfter(ParseTree node, int row, int col) { + Token token = getStopToken(node); if (token.getLine() != row) { return token.getLine() > row; } @@ -51,6 +76,14 @@ private static boolean endsAfter(Token token, int row, int col) { return lastTokenPosition >= col; } + private static boolean startsAfter(ParseTree node, int row, int col) { + Token token = getStartToken(node); + if (token.getLine() != row) { + return token.getLine() > row; + } + return token.getCharPositionInLine() > col; + } + public static boolean hasParentOfType(ParseTree leaf, int type) { return findParentOfType(leaf, type) != null; } @@ -61,4 +94,19 @@ public static ParseTree findParentOfType(ParseTree leaf, int type) { } return findParentOfType(leaf.getParent(), type); } + + public static int symbolType(ParseTree node) { + if (node instanceof TerminalNode) { + return ((TerminalNode) node).getSymbol().getType(); + } + return -1; + } + + public static boolean isSymbol(ParseTree node, int symbol) { + return symbolType(node) == symbol; + } + + public static boolean isAfterSymbol(ParseTree node, int symbol, int row, int col) { + return isSymbol(node, symbol) && endsBefore(node, row, col); + } } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java index 4e4e27e8d7d..fc99fc644cc 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java @@ -8,22 +8,24 @@ import static org.drools.parser.DRLParserHelper.createParseTree; import static org.drools.parser.DRLParserHelper.findNodeAtPosition; import static org.drools.parser.DRLParserHelper.findParentOfType; +import static org.drools.parser.DRLParserHelper.isAfterSymbol; import static org.drools.parser.DRLParserHelper.parse; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class DRLParserTest { + private static final String drl = + "package org.test;\n" + + "import org.test.model.Person;\n" + + "rule TestRule when \n" + + " $p:Person()\n" + + "then\n" + + " System.out.println($p.getName());\n" + + "end\n"; + @Test public void testParse() { - String drl = - "package org.test;\n" + - "import org.test.model.Person;\n" + - "rule TestRule when\n" + - " $p:Person()\n" + - "then\n" + - " System.out.println($p.getName());\n" + - "end\n"; - PackageDescr packageDescr = parse(drl); assertEquals("org.test", packageDescr.getName()); @@ -37,23 +39,19 @@ public void testParse() { @Test public void testCursorPosition() { - String drl = - "package org.test;\n" + - "import org.test.model.Person;\n" + - "rule TestRule when\n" + - " $p:Person()\n" + - "then\n" + - " System.out.println($p.getName());\n" + - "end\n"; - - int row = 4; - int col = 7; - ParseTree parseTree = createParseTree(drl); - ParseTree node = findNodeAtPosition(parseTree, row, col); + ParseTree node = findNodeAtPosition(parseTree, 4, 7); assertEquals("Person", node.getText()); ParseTree lhs = findParentOfType(node, DRLParser.RULE_lhs); assertEquals(DRLParser.RULE_lhs, ((RuleContext) lhs).getRuleIndex()); assertEquals("$p:Person()", lhs.getText()); } + + @Test + public void testCursorPosition2() { + ParseTree parseTree = createParseTree(drl); + ParseTree node = findNodeAtPosition(parseTree, 3, 19); + assertEquals("when", node.getText()); + assertTrue(isAfterSymbol(node, DRLParser.WHEN, 3, 19)); + } } From 5b86b4995ccfefe9d02f4260aac257dc63195d02 Mon Sep 17 00:00:00 2001 From: mariofusco Date: Fri, 28 Jan 2022 17:18:45 +0100 Subject: [PATCH 009/141] first c3 integration --- .../java/org/drools/parser/DRLParserHelper.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index 421624010cb..3387a85a9c1 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -17,11 +17,15 @@ public static PackageDescr parse(String drl) { } public static ParseTree createParseTree(String drl) { + return createDrlParser(drl).compilationunit(); + } + + public static DRLParser createDrlParser(String drl) { CharStream inputStream = CharStreams.fromString(drl); DRLLexer drlLexer = new DRLLexer(inputStream); CommonTokenStream commonTokenStream = new CommonTokenStream(drlLexer); DRLParser drlParser = new DRLParser(commonTokenStream); - return drlParser.compilationunit(); + return drlParser; } public static PackageDescr parseTree2PackageDescr(ParseTree parseTree) { @@ -109,4 +113,11 @@ public static boolean isSymbol(ParseTree node, int symbol) { public static boolean isAfterSymbol(ParseTree node, int symbol, int row, int col) { return isSymbol(node, symbol) && endsBefore(node, row, col); } + + public static int getNodeIndex(ParseTree node) { + if (node instanceof TerminalNode) { + return ((TerminalNode) node).getSymbol().getTokenIndex(); + } + return getNodeIndex(node.getChild(node.getChildCount()-1)); + } } From d20f3af4416ac443e7ef3e5df0799d07a3984218 Mon Sep 17 00:00:00 2001 From: Gabriele Cardosi Date: Thu, 10 Feb 2022 16:20:08 +0100 Subject: [PATCH 010/141] Module reorganization (#2) * WIP * Ignore directories * Add debug. Minor modifications * WIP * Fix tests - add comments --- drools-drl/drools-drl10-parser/pom.xml | 4 +--- .../src/main/java/org/drools/parser/DRLParserHelper.java | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml index c8231a66e7d..53ae3c502c0 100644 --- a/drools-drl/drools-drl10-parser/pom.xml +++ b/drools-drl/drools-drl10-parser/pom.xml @@ -10,9 +10,7 @@ 1.0.0-SNAPSHOT - org.drools drools-parser - 1.0.0-SNAPSHOT Drools :: Parser @@ -20,7 +18,7 @@ org.drools drools-drl-ast - 8.16.0.Beta + ${version.drools-drl-ast} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index 3387a85a9c1..52ecb80a693 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -115,6 +115,7 @@ public static boolean isAfterSymbol(ParseTree node, int symbol, int row, int col } public static int getNodeIndex(ParseTree node) { + // TODO Fix NPE if (node instanceof TerminalNode) { return ((TerminalNode) node).getSymbol().getTokenIndex(); } From c5bd78de30d487516adcc3d8f7d1e6c2079d3b80 Mon Sep 17 00:00:00 2001 From: mariofusco Date: Fri, 11 Feb 2022 14:21:02 +0100 Subject: [PATCH 011/141] manage null ast nodes and fix failing test --- .../src/main/java/org/drools/parser/DRLParserHelper.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index 52ecb80a693..f036bc90d62 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -115,10 +115,9 @@ public static boolean isAfterSymbol(ParseTree node, int symbol, int row, int col } public static int getNodeIndex(ParseTree node) { - // TODO Fix NPE if (node instanceof TerminalNode) { return ((TerminalNode) node).getSymbol().getTokenIndex(); } - return getNodeIndex(node.getChild(node.getChildCount()-1)); + return node.getChildCount() == 0 ? 0: getNodeIndex(node.getChild(node.getChildCount()-1)); } } From 2aab14c705531584e13382e97b6cbc7d7bcfc2d3 Mon Sep 17 00:00:00 2001 From: mariofusco Date: Mon, 14 Feb 2022 19:08:30 +0100 Subject: [PATCH 012/141] improve drl parser --- .../src/main/antlr4/org/drools/parser/DRL.g4 | 1023 ++++++++++++++++- .../org/drools/parser/DRLParserHelper.java | 2 +- .../org/drools/parser/DRLVisitorImpl.java | 64 +- .../java/org/drools/parser/DRLParserTest.java | 43 +- 4 files changed, 1085 insertions(+), 47 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 index e83e84dd5ff..6cc31c5e2bd 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 @@ -1,64 +1,1019 @@ grammar DRL; +@members { + public String normalizeString( String input ) { + if( input != null && (input.length() == 2 || input.length() >= 4) ) { + input = input.substring( 1, input.length() - 1 ); + input = input.replaceAll( "\'", "'" ); + input = input.replaceAll( "\"", "\\\"" ); + input = "\"" + input + "\""; + } + return input; + } +} + +///////////////// // KEYWORDS +///////////////// PACKAGE : 'package'; +UNIT : 'unit'; IMPORT : 'import'; +FUNCTION : 'function'; +STATIC : 'static'; +GLOBAL : 'global'; RULE : 'rule'; +QUERY : 'query'; +EXTENDS : 'extends'; +SUPER : 'super'; WHEN : 'when'; THEN : 'then'; END : 'end'; +///////////////// +// LEXER +///////////////// + +WS : [ \t\r\n\u000C\u00A0]+ -> skip ; + +fragment +EOL : + ( '\r' // Macintosh + | '\n' // Unix (the right way) + ) + ; + +FLOAT + : ('0'..'9')+ '.' ('0'..'9')* Exponent? FloatTypeSuffix? + | '.' ('0'..'9')+ Exponent? FloatTypeSuffix? + | ('0'..'9')+ Exponent FloatTypeSuffix? + | ('0'..'9')+ FloatTypeSuffix + ; + +fragment +Exponent : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; + +fragment +FloatTypeSuffix : ('f'|'F'|'d'|'D'|'B') ; + +HEX : '0' ('x'|'X') HexDigit+ IntegerTypeSuffix? ; + +DECIMAL : ('0'..'9')+ IntegerTypeSuffix? ; + +fragment +IntegerTypeSuffix : ('l'|'L'|'I') ; + +STRING + : ('"' ( EscapeSequence | ~('\\'|'"') )* '"') + | ('\'' ( EscapeSequence | ~('\\'|'\'') )* '\'') { setText( normalizeString( getText() ) ); } + ; + + +TIME_INTERVAL + : (('0'..'9')+ 'd') (('0'..'9')+ 'h')?(('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'h') (('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'm') (('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 's') (('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'ms'?) + ; + +fragment +HexDigit : ('0'..'9'|'a'..'f'|'A'..'F') ; + +fragment +EscapeSequence + : '\\' ('b'|'B'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\'|'.'|'o'| + 'x'|'a'|'e'|'c'|'d'|'D'|'s'|'S'|'w'|'W'|'p'|'A'| + 'G'|'Z'|'z'|'Q'|'E'|'*'|'['|']'|'('|')'|'$'|'^'| + '{'|'}'|'?'|'+'|'-'|'&'|'|') + | UnicodeEscape + | OctalEscape + ; + +fragment +OctalEscape + : '\\' ('0'..'3') ('0'..'7') ('0'..'7') + | '\\' ('0'..'7') ('0'..'7') + | '\\' ('0'..'7') + ; + +fragment +UnicodeEscape + : '\\' 'u' HexDigit HexDigit HexDigit HexDigit + ; + +///////////////// +// SYMBOLS +///////////////// + +BOOL : ('true'|'false') ; +NULL : 'null' ; +AT : '@' ; +PLUS_ASSIGN : '+=' ; +MINUS_ASSIGN : '-=' ; +MULT_ASSIGN : '*=' ; +DIV_ASSIGN : '/=' ; +AND_ASSIGN : '&=' ; +OR_ASSIGN : '|=' ; +XOR_ASSIGN : '^=' ; +MOD_ASSIGN : '%=' ; +UNIFY : ':=' ; +DECR : '--' ; +INCR : '++' ; +ARROW : '->' ; +SEMICOLON : ';' ; +COLON : ':' ; +EQUALS : '==' ; +NOT_EQUALS : '!=' ; +GREATER_EQUALS : '>=' ; +LESS_EQUALS : '<=' ; +GREATER : '>' ; +LESS : '<' ; +EQUALS_ASSIGN : '=' ; +LEFT_PAREN : '(' ; +RIGHT_PAREN : ')' ; + +LEFT_SQUARE + : '[' + ; + +RIGHT_SQUARE + : ']' + ; + +LEFT_CURLY + : '{' + ; + +RIGHT_CURLY + : '}' + ; + +COMMA : ',' + ; + +DOT : '.' + ; + +NULL_SAFE_DOT : '!.' + ; + +DOUBLE_AMPER + : '&&' + ; + +DOUBLE_PIPE + : '||' + ; + +QUESTION + : '?' + ; + +NEGATION + : '!' + ; + +TILDE + : '~' + ; + +PIPE + : '|' + ; + +AMPER + : '&' + ; + +XOR + : '^' + ; + +MOD + : '%' + ; + +STAR : '*' + ; + +MINUS : '-' + ; + +PLUS : '+' + ; + +HASH : '#' + ; + +C_STYLE_SINGLE_LINE_COMMENT + : '//' (~('\r'|'\n'))* (EOL|EOF) -> skip + ; + +MULTI_LINE_COMMENT + : '/*' (options{greedy=false;} : .)* '*/' -> skip + ; + +ID + : IdentifierStart IdentifierPart* + | '`' IdentifierStart IdentifierPart* '`' + ; + +// must come after the commentaries that use 2-character sequences with / +DIV : '/' + ; + +QUESTION_DIV + : '?/' + ; + +MISC : + '\'' | '\\' | '$' + ; + +fragment +IdentifierStart + : '\u0024' + | '\u0041'..'\u005a' + | '\u005f' + | '\u0061'..'\u007a' + | '\u00a2'..'\u00a5' + | '\u00aa' + | '\u00b5' + | '\u00ba' + | '\u00c0'..'\u00d6' + | '\u00d8'..'\u00f6' + | '\u00f8'..'\u0236' + | '\u0250'..'\u02c1' + | '\u02c6'..'\u02d1' + | '\u02e0'..'\u02e4' + | '\u02ee' + | '\u037a' + | '\u0386' + | '\u0388'..'\u038a' + | '\u038c' + | '\u038e'..'\u03a1' + | '\u03a3'..'\u03ce' + | '\u03d0'..'\u03f5' + | '\u03f7'..'\u03fb' + | '\u0400'..'\u0481' + | '\u048a'..'\u04ce' + | '\u04d0'..'\u04f5' + | '\u04f8'..'\u04f9' + | '\u0500'..'\u050f' + | '\u0531'..'\u0556' + | '\u0559' + | '\u0561'..'\u0587' + | '\u05d0'..'\u05ea' + | '\u05f0'..'\u05f2' + | '\u0621'..'\u063a' + | '\u0640'..'\u064a' + | '\u066e'..'\u066f' + | '\u0671'..'\u06d3' + | '\u06d5' + | '\u06e5'..'\u06e6' + | '\u06ee'..'\u06ef' + | '\u06fa'..'\u06fc' + | '\u06ff' + | '\u0710' + | '\u0712'..'\u072f' + | '\u074d'..'\u074f' + | '\u0780'..'\u07a5' + | '\u07b1' + | '\u0904'..'\u0939' + | '\u093d' + | '\u0950' + | '\u0958'..'\u0961' + | '\u0985'..'\u098c' + | '\u098f'..'\u0990' + | '\u0993'..'\u09a8' + | '\u09aa'..'\u09b0' + | '\u09b2' + | '\u09b6'..'\u09b9' + | '\u09bd' + | '\u09dc'..'\u09dd' + | '\u09df'..'\u09e1' + | '\u09f0'..'\u09f3' + | '\u0a05'..'\u0a0a' + | '\u0a0f'..'\u0a10' + | '\u0a13'..'\u0a28' + | '\u0a2a'..'\u0a30' + | '\u0a32'..'\u0a33' + | '\u0a35'..'\u0a36' + | '\u0a38'..'\u0a39' + | '\u0a59'..'\u0a5c' + | '\u0a5e' + | '\u0a72'..'\u0a74' + | '\u0a85'..'\u0a8d' + | '\u0a8f'..'\u0a91' + | '\u0a93'..'\u0aa8' + | '\u0aaa'..'\u0ab0' + | '\u0ab2'..'\u0ab3' + | '\u0ab5'..'\u0ab9' + | '\u0abd' + | '\u0ad0' + | '\u0ae0'..'\u0ae1' + | '\u0af1' + | '\u0b05'..'\u0b0c' + | '\u0b0f'..'\u0b10' + | '\u0b13'..'\u0b28' + | '\u0b2a'..'\u0b30' + | '\u0b32'..'\u0b33' + | '\u0b35'..'\u0b39' + | '\u0b3d' + | '\u0b5c'..'\u0b5d' + | '\u0b5f'..'\u0b61' + | '\u0b71' + | '\u0b83' + | '\u0b85'..'\u0b8a' + | '\u0b8e'..'\u0b90' + | '\u0b92'..'\u0b95' + | '\u0b99'..'\u0b9a' + | '\u0b9c' + | '\u0b9e'..'\u0b9f' + | '\u0ba3'..'\u0ba4' + | '\u0ba8'..'\u0baa' + | '\u0bae'..'\u0bb5' + | '\u0bb7'..'\u0bb9' + | '\u0bf9' + | '\u0c05'..'\u0c0c' + | '\u0c0e'..'\u0c10' + | '\u0c12'..'\u0c28' + | '\u0c2a'..'\u0c33' + | '\u0c35'..'\u0c39' + | '\u0c60'..'\u0c61' + | '\u0c85'..'\u0c8c' + | '\u0c8e'..'\u0c90' + | '\u0c92'..'\u0ca8' + | '\u0caa'..'\u0cb3' + | '\u0cb5'..'\u0cb9' + | '\u0cbd' + | '\u0cde' + | '\u0ce0'..'\u0ce1' + | '\u0d05'..'\u0d0c' + | '\u0d0e'..'\u0d10' + | '\u0d12'..'\u0d28' + | '\u0d2a'..'\u0d39' + | '\u0d60'..'\u0d61' + | '\u0d85'..'\u0d96' + | '\u0d9a'..'\u0db1' + | '\u0db3'..'\u0dbb' + | '\u0dbd' + | '\u0dc0'..'\u0dc6' + | '\u0e01'..'\u0e30' + | '\u0e32'..'\u0e33' + | '\u0e3f'..'\u0e46' + | '\u0e81'..'\u0e82' + | '\u0e84' + | '\u0e87'..'\u0e88' + | '\u0e8a' + | '\u0e8d' + | '\u0e94'..'\u0e97' + | '\u0e99'..'\u0e9f' + | '\u0ea1'..'\u0ea3' + | '\u0ea5' + | '\u0ea7' + | '\u0eaa'..'\u0eab' + | '\u0ead'..'\u0eb0' + | '\u0eb2'..'\u0eb3' + | '\u0ebd' + | '\u0ec0'..'\u0ec4' + | '\u0ec6' + | '\u0edc'..'\u0edd' + | '\u0f00' + | '\u0f40'..'\u0f47' + | '\u0f49'..'\u0f6a' + | '\u0f88'..'\u0f8b' + | '\u1000'..'\u1021' + | '\u1023'..'\u1027' + | '\u1029'..'\u102a' + | '\u1050'..'\u1055' + | '\u10a0'..'\u10c5' + | '\u10d0'..'\u10f8' + | '\u1100'..'\u1159' + | '\u115f'..'\u11a2' + | '\u11a8'..'\u11f9' + | '\u1200'..'\u1206' + | '\u1208'..'\u1246' + | '\u1248' + | '\u124a'..'\u124d' + | '\u1250'..'\u1256' + | '\u1258' + | '\u125a'..'\u125d' + | '\u1260'..'\u1286' + | '\u1288' + | '\u128a'..'\u128d' + | '\u1290'..'\u12ae' + | '\u12b0' + | '\u12b2'..'\u12b5' + | '\u12b8'..'\u12be' + | '\u12c0' + | '\u12c2'..'\u12c5' + | '\u12c8'..'\u12ce' + | '\u12d0'..'\u12d6' + | '\u12d8'..'\u12ee' + | '\u12f0'..'\u130e' + | '\u1310' + | '\u1312'..'\u1315' + | '\u1318'..'\u131e' + | '\u1320'..'\u1346' + | '\u1348'..'\u135a' + | '\u13a0'..'\u13f4' + | '\u1401'..'\u166c' + | '\u166f'..'\u1676' + | '\u1681'..'\u169a' + | '\u16a0'..'\u16ea' + | '\u16ee'..'\u16f0' + | '\u1700'..'\u170c' + | '\u170e'..'\u1711' + | '\u1720'..'\u1731' + | '\u1740'..'\u1751' + | '\u1760'..'\u176c' + | '\u176e'..'\u1770' + | '\u1780'..'\u17b3' + | '\u17d7' + | '\u17db'..'\u17dc' + | '\u1820'..'\u1877' + | '\u1880'..'\u18a8' + | '\u1900'..'\u191c' + | '\u1950'..'\u196d' + | '\u1970'..'\u1974' + | '\u1d00'..'\u1d6b' + | '\u1e00'..'\u1e9b' + | '\u1ea0'..'\u1ef9' + | '\u1f00'..'\u1f15' + | '\u1f18'..'\u1f1d' + | '\u1f20'..'\u1f45' + | '\u1f48'..'\u1f4d' + | '\u1f50'..'\u1f57' + | '\u1f59' + | '\u1f5b' + | '\u1f5d' + | '\u1f5f'..'\u1f7d' + | '\u1f80'..'\u1fb4' + | '\u1fb6'..'\u1fbc' + | '\u1fbe' + | '\u1fc2'..'\u1fc4' + | '\u1fc6'..'\u1fcc' + | '\u1fd0'..'\u1fd3' + | '\u1fd6'..'\u1fdb' + | '\u1fe0'..'\u1fec' + | '\u1ff2'..'\u1ff4' + | '\u1ff6'..'\u1ffc' + | '\u203f'..'\u2040' + | '\u2054' + | '\u2071' + | '\u207f' + | '\u20a0'..'\u20b1' + | '\u2102' + | '\u2107' + | '\u210a'..'\u2113' + | '\u2115' + | '\u2119'..'\u211d' + | '\u2124' + | '\u2126' + | '\u2128' + | '\u212a'..'\u212d' + | '\u212f'..'\u2131' + | '\u2133'..'\u2139' + | '\u213d'..'\u213f' + | '\u2145'..'\u2149' + | '\u2160'..'\u2183' + | '\u3005'..'\u3007' + | '\u3021'..'\u3029' + | '\u3031'..'\u3035' + | '\u3038'..'\u303c' + | '\u3041'..'\u3096' + | '\u309d'..'\u309f' + | '\u30a1'..'\u30ff' + | '\u3105'..'\u312c' + | '\u3131'..'\u318e' + | '\u31a0'..'\u31b7' + | '\u31f0'..'\u31ff' + | '\u3400'..'\u4db5' + | '\u4e00'..'\u9fa5' + | '\ua000'..'\ua48c' + | '\uac00'..'\ud7a3' + | '\uf900'..'\ufa2d' + | '\ufa30'..'\ufa6a' + | '\ufb00'..'\ufb06' + | '\ufb13'..'\ufb17' + | '\ufb1d' + | '\ufb1f'..'\ufb28' + | '\ufb2a'..'\ufb36' + | '\ufb38'..'\ufb3c' + | '\ufb3e' + | '\ufb40'..'\ufb41' + | '\ufb43'..'\ufb44' + | '\ufb46'..'\ufbb1' + | '\ufbd3'..'\ufd3d' + | '\ufd50'..'\ufd8f' + | '\ufd92'..'\ufdc7' + | '\ufdf0'..'\ufdfc' + | '\ufe33'..'\ufe34' + | '\ufe4d'..'\ufe4f' + | '\ufe69' + | '\ufe70'..'\ufe74' + | '\ufe76'..'\ufefc' + | '\uff04' + | '\uff21'..'\uff3a' + | '\uff3f' + | '\uff41'..'\uff5a' + | '\uff65'..'\uffbe' + | '\uffc2'..'\uffc7' + | '\uffca'..'\uffcf' + | '\uffd2'..'\uffd7' + | '\uffda'..'\uffdc' + | '\uffe0'..'\uffe1' + | '\uffe5'..'\uffe6' +// UTF-16: | ('\ud800'..'\udbff') ('\udc00'..'\udfff') + ; + +fragment +IdentifierPart + : '\u0000'..'\u0008' + | '\u000e'..'\u001b' + | '\u0024' + | '\u0030'..'\u0039' + | '\u0041'..'\u005a' + | '\u005f' + | '\u0061'..'\u007a' + | '\u007f'..'\u009f' + | '\u00a2'..'\u00a5' + | '\u00aa' + | '\u00ad' + | '\u00b5' + | '\u00ba' + | '\u00c0'..'\u00d6' + | '\u00d8'..'\u00f6' + | '\u00f8'..'\u0236' + | '\u0250'..'\u02c1' + | '\u02c6'..'\u02d1' + | '\u02e0'..'\u02e4' + | '\u02ee' + | '\u0300'..'\u0357' + | '\u035d'..'\u036f' + | '\u037a' + | '\u0386' + | '\u0388'..'\u038a' + | '\u038c' + | '\u038e'..'\u03a1' + | '\u03a3'..'\u03ce' + | '\u03d0'..'\u03f5' + | '\u03f7'..'\u03fb' + | '\u0400'..'\u0481' + | '\u0483'..'\u0486' + | '\u048a'..'\u04ce' + | '\u04d0'..'\u04f5' + | '\u04f8'..'\u04f9' + | '\u0500'..'\u050f' + | '\u0531'..'\u0556' + | '\u0559' + | '\u0561'..'\u0587' + | '\u0591'..'\u05a1' + | '\u05a3'..'\u05b9' + | '\u05bb'..'\u05bd' + | '\u05bf' + | '\u05c1'..'\u05c2' + | '\u05c4' + | '\u05d0'..'\u05ea' + | '\u05f0'..'\u05f2' + | '\u0600'..'\u0603' + | '\u0610'..'\u0615' + | '\u0621'..'\u063a' + | '\u0640'..'\u0658' + | '\u0660'..'\u0669' + | '\u066e'..'\u06d3' + | '\u06d5'..'\u06dd' + | '\u06df'..'\u06e8' + | '\u06ea'..'\u06fc' + | '\u06ff' + | '\u070f'..'\u074a' + | '\u074d'..'\u074f' + | '\u0780'..'\u07b1' + | '\u0901'..'\u0939' + | '\u093c'..'\u094d' + | '\u0950'..'\u0954' + | '\u0958'..'\u0963' + | '\u0966'..'\u096f' + | '\u0981'..'\u0983' + | '\u0985'..'\u098c' + | '\u098f'..'\u0990' + | '\u0993'..'\u09a8' + | '\u09aa'..'\u09b0' + | '\u09b2' + | '\u09b6'..'\u09b9' + | '\u09bc'..'\u09c4' + | '\u09c7'..'\u09c8' + | '\u09cb'..'\u09cd' + | '\u09d7' + | '\u09dc'..'\u09dd' + | '\u09df'..'\u09e3' + | '\u09e6'..'\u09f3' + | '\u0a01'..'\u0a03' + | '\u0a05'..'\u0a0a' + | '\u0a0f'..'\u0a10' + | '\u0a13'..'\u0a28' + | '\u0a2a'..'\u0a30' + | '\u0a32'..'\u0a33' + | '\u0a35'..'\u0a36' + | '\u0a38'..'\u0a39' + | '\u0a3c' + | '\u0a3e'..'\u0a42' + | '\u0a47'..'\u0a48' + | '\u0a4b'..'\u0a4d' + | '\u0a59'..'\u0a5c' + | '\u0a5e' + | '\u0a66'..'\u0a74' + | '\u0a81'..'\u0a83' + | '\u0a85'..'\u0a8d' + | '\u0a8f'..'\u0a91' + | '\u0a93'..'\u0aa8' + | '\u0aaa'..'\u0ab0' + | '\u0ab2'..'\u0ab3' + | '\u0ab5'..'\u0ab9' + | '\u0abc'..'\u0ac5' + | '\u0ac7'..'\u0ac9' + | '\u0acb'..'\u0acd' + | '\u0ad0' + | '\u0ae0'..'\u0ae3' + | '\u0ae6'..'\u0aef' + | '\u0af1' + | '\u0b01'..'\u0b03' + | '\u0b05'..'\u0b0c' + | '\u0b0f'..'\u0b10' + | '\u0b13'..'\u0b28' + | '\u0b2a'..'\u0b30' + | '\u0b32'..'\u0b33' + | '\u0b35'..'\u0b39' + | '\u0b3c'..'\u0b43' + | '\u0b47'..'\u0b48' + | '\u0b4b'..'\u0b4d' + | '\u0b56'..'\u0b57' + | '\u0b5c'..'\u0b5d' + | '\u0b5f'..'\u0b61' + | '\u0b66'..'\u0b6f' + | '\u0b71' + | '\u0b82'..'\u0b83' + | '\u0b85'..'\u0b8a' + | '\u0b8e'..'\u0b90' + | '\u0b92'..'\u0b95' + | '\u0b99'..'\u0b9a' + | '\u0b9c' + | '\u0b9e'..'\u0b9f' + | '\u0ba3'..'\u0ba4' + | '\u0ba8'..'\u0baa' + | '\u0bae'..'\u0bb5' + | '\u0bb7'..'\u0bb9' + | '\u0bbe'..'\u0bc2' + | '\u0bc6'..'\u0bc8' + | '\u0bca'..'\u0bcd' + | '\u0bd7' + | '\u0be7'..'\u0bef' + | '\u0bf9' + | '\u0c01'..'\u0c03' + | '\u0c05'..'\u0c0c' + | '\u0c0e'..'\u0c10' + | '\u0c12'..'\u0c28' + | '\u0c2a'..'\u0c33' + | '\u0c35'..'\u0c39' + | '\u0c3e'..'\u0c44' + | '\u0c46'..'\u0c48' + | '\u0c4a'..'\u0c4d' + | '\u0c55'..'\u0c56' + | '\u0c60'..'\u0c61' + | '\u0c66'..'\u0c6f' + | '\u0c82'..'\u0c83' + | '\u0c85'..'\u0c8c' + | '\u0c8e'..'\u0c90' + | '\u0c92'..'\u0ca8' + | '\u0caa'..'\u0cb3' + | '\u0cb5'..'\u0cb9' + | '\u0cbc'..'\u0cc4' + | '\u0cc6'..'\u0cc8' + | '\u0cca'..'\u0ccd' + | '\u0cd5'..'\u0cd6' + | '\u0cde' + | '\u0ce0'..'\u0ce1' + | '\u0ce6'..'\u0cef' + | '\u0d02'..'\u0d03' + | '\u0d05'..'\u0d0c' + | '\u0d0e'..'\u0d10' + | '\u0d12'..'\u0d28' + | '\u0d2a'..'\u0d39' + | '\u0d3e'..'\u0d43' + | '\u0d46'..'\u0d48' + | '\u0d4a'..'\u0d4d' + | '\u0d57' + | '\u0d60'..'\u0d61' + | '\u0d66'..'\u0d6f' + | '\u0d82'..'\u0d83' + | '\u0d85'..'\u0d96' + | '\u0d9a'..'\u0db1' + | '\u0db3'..'\u0dbb' + | '\u0dbd' + | '\u0dc0'..'\u0dc6' + | '\u0dca' + | '\u0dcf'..'\u0dd4' + | '\u0dd6' + | '\u0dd8'..'\u0ddf' + | '\u0df2'..'\u0df3' + | '\u0e01'..'\u0e3a' + | '\u0e3f'..'\u0e4e' + | '\u0e50'..'\u0e59' + | '\u0e81'..'\u0e82' + | '\u0e84' + | '\u0e87'..'\u0e88' + | '\u0e8a' + | '\u0e8d' + | '\u0e94'..'\u0e97' + | '\u0e99'..'\u0e9f' + | '\u0ea1'..'\u0ea3' + | '\u0ea5' + | '\u0ea7' + | '\u0eaa'..'\u0eab' + | '\u0ead'..'\u0eb9' + | '\u0ebb'..'\u0ebd' + | '\u0ec0'..'\u0ec4' + | '\u0ec6' + | '\u0ec8'..'\u0ecd' + | '\u0ed0'..'\u0ed9' + | '\u0edc'..'\u0edd' + | '\u0f00' + | '\u0f18'..'\u0f19' + | '\u0f20'..'\u0f29' + | '\u0f35' + | '\u0f37' + | '\u0f39' + | '\u0f3e'..'\u0f47' + | '\u0f49'..'\u0f6a' + | '\u0f71'..'\u0f84' + | '\u0f86'..'\u0f8b' + | '\u0f90'..'\u0f97' + | '\u0f99'..'\u0fbc' + | '\u0fc6' + | '\u1000'..'\u1021' + | '\u1023'..'\u1027' + | '\u1029'..'\u102a' + | '\u102c'..'\u1032' + | '\u1036'..'\u1039' + | '\u1040'..'\u1049' + | '\u1050'..'\u1059' + | '\u10a0'..'\u10c5' + | '\u10d0'..'\u10f8' + | '\u1100'..'\u1159' + | '\u115f'..'\u11a2' + | '\u11a8'..'\u11f9' + | '\u1200'..'\u1206' + | '\u1208'..'\u1246' + | '\u1248' + | '\u124a'..'\u124d' + | '\u1250'..'\u1256' + | '\u1258' + | '\u125a'..'\u125d' + | '\u1260'..'\u1286' + | '\u1288' + | '\u128a'..'\u128d' + | '\u1290'..'\u12ae' + | '\u12b0' + | '\u12b2'..'\u12b5' + | '\u12b8'..'\u12be' + | '\u12c0' + | '\u12c2'..'\u12c5' + | '\u12c8'..'\u12ce' + | '\u12d0'..'\u12d6' + | '\u12d8'..'\u12ee' + | '\u12f0'..'\u130e' + | '\u1310' + | '\u1312'..'\u1315' + | '\u1318'..'\u131e' + | '\u1320'..'\u1346' + | '\u1348'..'\u135a' + | '\u1369'..'\u1371' + | '\u13a0'..'\u13f4' + | '\u1401'..'\u166c' + | '\u166f'..'\u1676' + | '\u1681'..'\u169a' + | '\u16a0'..'\u16ea' + | '\u16ee'..'\u16f0' + | '\u1700'..'\u170c' + | '\u170e'..'\u1714' + | '\u1720'..'\u1734' + | '\u1740'..'\u1753' + | '\u1760'..'\u176c' + | '\u176e'..'\u1770' + | '\u1772'..'\u1773' + | '\u1780'..'\u17d3' + | '\u17d7' + | '\u17db'..'\u17dd' + | '\u17e0'..'\u17e9' + | '\u180b'..'\u180d' + | '\u1810'..'\u1819' + | '\u1820'..'\u1877' + | '\u1880'..'\u18a9' + | '\u1900'..'\u191c' + | '\u1920'..'\u192b' + | '\u1930'..'\u193b' + | '\u1946'..'\u196d' + | '\u1970'..'\u1974' + | '\u1d00'..'\u1d6b' + | '\u1e00'..'\u1e9b' + | '\u1ea0'..'\u1ef9' + | '\u1f00'..'\u1f15' + | '\u1f18'..'\u1f1d' + | '\u1f20'..'\u1f45' + | '\u1f48'..'\u1f4d' + | '\u1f50'..'\u1f57' + | '\u1f59' + | '\u1f5b' + | '\u1f5d' + | '\u1f5f'..'\u1f7d' + | '\u1f80'..'\u1fb4' + | '\u1fb6'..'\u1fbc' + | '\u1fbe' + | '\u1fc2'..'\u1fc4' + | '\u1fc6'..'\u1fcc' + | '\u1fd0'..'\u1fd3' + | '\u1fd6'..'\u1fdb' + | '\u1fe0'..'\u1fec' + | '\u1ff2'..'\u1ff4' + | '\u1ff6'..'\u1ffc' + | '\u200c'..'\u200f' + | '\u202a'..'\u202e' + | '\u203f'..'\u2040' + | '\u2054' + | '\u2060'..'\u2063' + | '\u206a'..'\u206f' + | '\u2071' + | '\u207f' + | '\u20a0'..'\u20b1' + | '\u20d0'..'\u20dc' + | '\u20e1' + | '\u20e5'..'\u20ea' + | '\u2102' + | '\u2107' + | '\u210a'..'\u2113' + | '\u2115' + | '\u2119'..'\u211d' + | '\u2124' + | '\u2126' + | '\u2128' + | '\u212a'..'\u212d' + | '\u212f'..'\u2131' + | '\u2133'..'\u2139' + | '\u213d'..'\u213f' + | '\u2145'..'\u2149' + | '\u2160'..'\u2183' + | '\u3005'..'\u3007' + | '\u3021'..'\u302f' + | '\u3031'..'\u3035' + | '\u3038'..'\u303c' + | '\u3041'..'\u3096' + | '\u3099'..'\u309a' + | '\u309d'..'\u309f' + | '\u30a1'..'\u30ff' + | '\u3105'..'\u312c' + | '\u3131'..'\u318e' + | '\u31a0'..'\u31b7' + | '\u31f0'..'\u31ff' + | '\u3400'..'\u4db5' + | '\u4e00'..'\u9fa5' + | '\ua000'..'\ua48c' + | '\uac00'..'\ud7a3' + | '\uf900'..'\ufa2d' + | '\ufa30'..'\ufa6a' + | '\ufb00'..'\ufb06' + | '\ufb13'..'\ufb17' + | '\ufb1d'..'\ufb28' + | '\ufb2a'..'\ufb36' + | '\ufb38'..'\ufb3c' + | '\ufb3e' + | '\ufb40'..'\ufb41' + | '\ufb43'..'\ufb44' + | '\ufb46'..'\ufbb1' + | '\ufbd3'..'\ufd3d' + | '\ufd50'..'\ufd8f' + | '\ufd92'..'\ufdc7' + | '\ufdf0'..'\ufdfc' + | '\ufe00'..'\ufe0f' + | '\ufe20'..'\ufe23' + | '\ufe33'..'\ufe34' + | '\ufe4d'..'\ufe4f' + | '\ufe69' + | '\ufe70'..'\ufe74' + | '\ufe76'..'\ufefc' + | '\ufeff' + | '\uff04' + | '\uff10'..'\uff19' + | '\uff21'..'\uff3a' + | '\uff3f' + | '\uff41'..'\uff5a' + | '\uff65'..'\uffbe' + | '\uffc2'..'\uffc7' + | '\uffca'..'\uffcf' + | '\uffd2'..'\uffd7' + | '\uffda'..'\uffdc' + | '\uffe0'..'\uffe1' + | '\uffe5'..'\uffe6' + | '\ufff9'..'\ufffb' +// UTF-16 | ('\ud800'..'\udbff') ('\udc00'..'\udfff') + ; + +///////////////// // PARSER +///////////////// + +compilationunit : packagedef? unitdef? importdef* globaldef* ruledef* ; -compilationunit : packagedef? importdef* ruledef* ; +packagedef : PACKAGE name=qualifiedIdentifier SEMICOLON? ; -packagedef : PACKAGE FQNAME SEMICOLON? ; +unitdef : UNIT name=qualifiedIdentifier SEMICOLON? ; -importdef : IMPORT FQNAME (DOT STAR)? SEMICOLON? ; +importdef : IMPORT (FUNCTION|STATIC)? qualifiedIdentifier (DOT STAR)? SEMICOLON? ; -ruledef : RULE IDENTIFIER WHEN lhs THEN rhs END ; +globaldef : GLOBAL type ID SEMICOLON? ; -lhs : TEXT ; +ruledef : RULE name=stringId (EXTENDS stringId)? annotation* attributes? WHEN lhs THEN rhs END ; + +lhs : lhsExpression ; +lhsExpression : lhsOr* ; +lhsOr : LEFT_PAREN OR lhsAnd+ RIGHT_PAREN | lhsAnd (OR lhsAnd)* ; +lhsAnd : LEFT_PAREN AND lhsUnary+ RIGHT_PAREN | lhsUnary (AND lhsUnary)* ; + +/* +lhsUnary : ( lhsExists namedConsequence? + | lhsNot namedConsequence? + | lhsEval consequenceInvocation* + | lhsForall + | lhsAccumulate + | LEFT_PAREN lhsOr RIGHT_PAREN namedConsequence? + | lhsPatternBind consequenceInvocation* + ) SEMICOLON? ; +*/ + +lhsUnary : lhsPatternBind ; +lhsPatternBind : label? ( LEFT_PAREN lhsPattern (OR lhsPattern)* RIGHT_PAREN | lhsPattern ) ; + +/* +lhsPattern : xpathPrimary (OVER patternFilter)? | + ( QUESTION? qualifiedIdentifier LEFT_PAREN positionalConstraints? constraints? RIGHT_PAREN (OVER patternFilter)? (FROM patternSource)? ) ; +*/ + +lhsPattern : QUESTION? objectType=qualifiedIdentifier LEFT_PAREN positionalConstraints? constraints? RIGHT_PAREN ; +positionalConstraints : constraint (COMMA constraint)* SEMICOLON ; +constraints : constraint (COMMA constraint)* ; +constraint : nestedConstraint | conditionalOrExpression ; +nestedConstraint : ( ID ( DOT | HASH ) )* ID DOT LEFT_PAREN constraints RIGHT_PAREN ; +conditionalOrExpression : left=conditionalAndExpression (DOUBLE_PIPE right=conditionalAndExpression)* ; +conditionalAndExpression : left=inclusiveOrExpression (DOUBLE_AMPER right=inclusiveOrExpression)* ; +inclusiveOrExpression : left=exclusiveOrExpression (PIPE right=exclusiveOrExpression)* ; +exclusiveOrExpression : left=andExpression (XOR right=andExpression)* ; +andExpression : left=equalityExpression (AMPER right=equalityExpression)* ; +equalityExpression : left=instanceOfExpression ( ( op=EQUALS | op=NOT_EQUALS ) right=instanceOfExpression )* ; +instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; +inExpression : left=relationalExpression ( 'not'? 'in' LEFT_PAREN expression (COMMA expression)* RIGHT_PAREN )? ; +relationalExpression : TEXT? ; // TODO + +expression : conditionalExpression ( op=assignmentOperator right=expression )? ; +conditionalExpression : left=conditionalOrExpression ternaryExpression? ; +ternaryExpression : QUESTION ts=expression COLON fs=expression ; rhs : TEXT ; -// LITERALS +stringId : ( ID | STRING ) ; -fragment DIGIT : [0-9] ; -NUMBER : DIGIT+ ([.,] DIGIT+)? ; +qualifiedIdentifier : ID ( DOT ID )* ; -fragment LOWERCASE : [a-z] ; -fragment UPPERCASE : [A-Z] ; -LETTER : (LOWERCASE | UPPERCASE | '_' | '$') ; +type : ID typeArguments? ( DOT ID typeArguments? )* (LEFT_SQUARE RIGHT_SQUARE)* ; -IDENTIFIER : LETTER (LETTER | DIGIT)* ; -FQNAME : IDENTIFIER (DOT IDENTIFIER)* ; +typeArguments : LESS typeArgument (COMMA typeArgument)* GREATER ; +typeArgument : QUESTION (( EXTENDS | SUPER ) type )? | type ; -// SEPARATORS +arguments : LEFT_PAREN argument (COMMA argument)* RIGHT_PAREN ; +argument : ( stringId | FLOAT | BOOL | NULL ) ; -LPAREN : '('; -RPAREN : ')'; -LBRACE : '{'; -RBRACE : '}'; -LBRACK : '['; -RBRACK : ']'; -COMMA : ','; -ELIPSIS : '..'; -DOT : '.'; -COLON : ':'; -SEMICOLON : ';'; -STAR : '*'; +annotation : AT name=qualifiedIdentifier arguments? ; -// OPERATORS +attributes : attribute ( COMMA? attribute )* ; +attribute : ( 'salience' DECIMAL ) + | ( 'enabled' | 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOLEAN? + | ( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) STRING + | 'calendars' STRING ( COMMA STRING )* + | 'timer' ( DECIMAL | TEXT ) + | 'duration' ( DECIMAL | TEXT ) ; -EQUAL : '='; -GT : '>'; -LT : '<'; -LE : '<='; -GE : '>='; -NOTEQUAL : '!='; +assignmentOperator : EQUALS_ASSIGN + | PLUS_ASSIGN + | MINUS_ASSIGN + | MULT_ASSIGN + | DIV_ASSIGN + | AND_ASSIGN + | OR_ASSIGN + | XOR_ASSIGN + | MOD_ASSIGN + | LESS LESS EQUALS_ASSIGN ; -WS : [ \t\r\n\u000C\u00A0]+ -> skip ; +label : ID COLON ; +unif : ID UNIFY ; fragment TEXT : .+ ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index f036bc90d62..f1c254fa332 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -118,6 +118,6 @@ public static int getNodeIndex(ParseTree node) { if (node instanceof TerminalNode) { return ((TerminalNode) node).getSymbol().getTokenIndex(); } - return node.getChildCount() == 0 ? 0: getNodeIndex(node.getChild(node.getChildCount()-1)); + return node.getChildCount() == 0 ? 0: getNodeIndex(node.getChild(0)); } } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 780076b9ab5..9aa2fbce870 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -1,13 +1,20 @@ package org.drools.parser; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.ImportDescr; import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.UnitDescr; public class DRLVisitorImpl extends DRLBaseVisitor { private final PackageDescr packageDescr = new PackageDescr(); + private RuleDescr ruleDescr; + @Override public Object visitCompilationunit(DRLParser.CompilationunitContext ctx) { return super.visitCompilationunit(ctx); @@ -15,23 +22,68 @@ public Object visitCompilationunit(DRLParser.CompilationunitContext ctx) { @Override public Object visitPackagedef(DRLParser.PackagedefContext ctx) { - packageDescr.setName(ctx.FQNAME().getText()); + packageDescr.setName(ctx.name.getText()); return super.visitPackagedef(ctx); } + @Override + public Object visitUnitdef(DRLParser.UnitdefContext ctx) { + packageDescr.setUnit(new UnitDescr(ctx.name.getText())); + return super.visitUnitdef(ctx); + } + + @Override + public Object visitGlobaldef(DRLParser.GlobaldefContext ctx) { + packageDescr.addGlobal(new GlobalDescr(ctx.ID().getText(), ctx.type().getText())); + return super.visitGlobaldef(ctx); + } + @Override public Object visitImportdef(DRLParser.ImportdefContext ctx) { - String imp = ctx.FQNAME().getText() + (ctx.STAR() != null ? ".*" : ""); + String imp = ctx.qualifiedIdentifier().getText() + (ctx.STAR() != null ? ".*" : ""); packageDescr.addImport(new ImportDescr(imp)); return super.visitImportdef(ctx); } @Override public Object visitRuledef(DRLParser.RuledefContext ctx) { - RuleDescr rule = new RuleDescr(ctx.IDENTIFIER().getText()); - rule.setConsequence(ctx.rhs().getText()); - packageDescr.addRule(rule); - return super.visitRuledef(ctx); + ruleDescr = new RuleDescr(ctx.name.getText()); + ruleDescr.setConsequence(ctx.rhs().getText()); + packageDescr.addRule(ruleDescr); + + Object result = super.visitRuledef(ctx); + ruleDescr = null; + return result; + } + + @Override + public Object visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { + if ( ctx.lhsPattern().size() == 1 ) { + PatternDescr patternDescr = new PatternDescr(ctx.lhsPattern(0).objectType.getText()); + if (ctx.label() != null) { + patternDescr.setIdentifier(ctx.label().ID().getText()); + } + ruleDescr.getLhs().addDescr(patternDescr); + } + return super.visitLhsPatternBind(ctx); + } + + @Override + public Object visitAnnotation(DRLParser.AnnotationContext ctx) { + AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); + annotationDescr.setValue(ctx.arguments().argument(0).getText()); + ruleDescr.addAnnotation(annotationDescr); + return super.visitAnnotation(ctx); + } + + @Override + public Object visitAttribute(DRLParser.AttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr( ctx.getChild(0).getText() ); + if (ctx.getChildCount() > 1) { + attributeDescr.setValue( ctx.getChild(1).getText() ); + } + ruleDescr.addAttribute(attributeDescr); + return super.visitAttribute(ctx); } public PackageDescr getPackageDescr() { diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java index fc99fc644cc..5d8bd5b42dd 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java @@ -2,7 +2,13 @@ import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.tree.ParseTree; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.RuleDescr; import org.junit.Test; import static org.drools.parser.DRLParserHelper.createParseTree; @@ -11,6 +17,7 @@ import static org.drools.parser.DRLParserHelper.isAfterSymbol; import static org.drools.parser.DRLParserHelper.parse; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class DRLParserTest { @@ -18,7 +25,8 @@ public class DRLParserTest { private static final String drl = "package org.test;\n" + "import org.test.model.Person;\n" + - "rule TestRule when \n" + + "global String result;\n" + + "rule TestRule @Test(true) no-loop salience 15 when \n" + " $p:Person()\n" + "then\n" + " System.out.println($p.getName());\n" + @@ -32,15 +40,38 @@ public void testParse() { assertEquals(1, packageDescr.getImports().size()); assertEquals("org.test.model.Person", packageDescr.getImports().get(0).getTarget()); + assertEquals(1, packageDescr.getGlobals().size()); + GlobalDescr globalDescr = packageDescr.getGlobals().get(0); + assertEquals("String", globalDescr.getType()); + assertEquals("result", globalDescr.getIdentifier()); + assertEquals(1, packageDescr.getRules().size()); - assertEquals("TestRule", packageDescr.getRules().get(0).getName()); - assertEquals("System.out.println($p.getName());", packageDescr.getRules().get(0).getConsequence()); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + AnnotationDescr annotationDescr = ruleDescr.getAnnotation("Test"); + assertNotNull(annotationDescr); + assertEquals("true", annotationDescr.getValue()); + + assertEquals( 2, ruleDescr.getAttributes().size() ); + assertNotNull( ruleDescr.getAttributes().get("no-loop") ); + AttributeDescr salience = ruleDescr.getAttributes().get("salience"); + assertNotNull( salience ); + assertEquals( "15", salience.getValue() ); + + assertEquals("TestRule", ruleDescr.getName()); + + assertEquals( 1, ruleDescr.getLhs().getDescrs().size() ); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + assertEquals("$p", patternDescr.getIdentifier()); + assertEquals("Person", patternDescr.getObjectType()); + + assertEquals("System.out.println($p.getName());", ruleDescr.getConsequence()); } @Test public void testCursorPosition() { ParseTree parseTree = createParseTree(drl); - ParseTree node = findNodeAtPosition(parseTree, 4, 7); + ParseTree node = findNodeAtPosition(parseTree, 5, 7); assertEquals("Person", node.getText()); ParseTree lhs = findParentOfType(node, DRLParser.RULE_lhs); assertEquals(DRLParser.RULE_lhs, ((RuleContext) lhs).getRuleIndex()); @@ -50,8 +81,8 @@ public void testCursorPosition() { @Test public void testCursorPosition2() { ParseTree parseTree = createParseTree(drl); - ParseTree node = findNodeAtPosition(parseTree, 3, 19); + ParseTree node = findNodeAtPosition(parseTree, 4, 51); assertEquals("when", node.getText()); - assertTrue(isAfterSymbol(node, DRLParser.WHEN, 3, 19)); + assertTrue(isAfterSymbol(node, DRLParser.WHEN, 4, 51)); } } From 19594b8c07779a5e941b7c4dd6d45195d3db8381 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Livio=20Ben=C4=8Dik?= Date: Fri, 25 Mar 2022 14:57:25 +0100 Subject: [PATCH 013/141] Fix basic completion (#4) * Add Java grammar, fix DRL grammar, simplify token index calculation, remove template code * Add ignored tokens to completion Co-authored-by: livio --- drools-drl/drools-drl10-parser/.gitignore | 1 + drools-drl/drools-drl10-parser/pom.xml | 1 + .../src/main/antlr4/org/drools/parser/DRL.g4 | 1019 ----------------- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 77 ++ .../antlr4/org/drools/parser/DRLParser.g4 | 97 ++ .../antlr4/org/drools/parser/JavaLexer.g4 | 245 ++++ .../antlr4/org/drools/parser/JavaParser.g4 | 752 ++++++++++++ .../org/drools/parser/DRLParserHelper.java | 100 +- .../org/drools/parser/DRLVisitorImpl.java | 33 +- .../java/org/drools/parser/DRLParserTest.java | 67 +- 10 files changed, 1231 insertions(+), 1161 deletions(-) delete mode 100644 drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 create mode 100644 drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 create mode 100644 drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 create mode 100644 drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaLexer.g4 create mode 100644 drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaParser.g4 diff --git a/drools-drl/drools-drl10-parser/.gitignore b/drools-drl/drools-drl10-parser/.gitignore index 372e03f0268..6fc57b48ec6 100644 --- a/drools-drl/drools-drl10-parser/.gitignore +++ b/drools-drl/drools-drl10-parser/.gitignore @@ -1,4 +1,5 @@ target/ +gen/ local/ # Eclipse, Netbeans and IntelliJ files diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml index 53ae3c502c0..2b88baa153b 100644 --- a/drools-drl/drools-drl10-parser/pom.xml +++ b/drools-drl/drools-drl10-parser/pom.xml @@ -63,6 +63,7 @@ true false + src/main/antlr4/org/drools/parser/ diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 deleted file mode 100644 index 6cc31c5e2bd..00000000000 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL.g4 +++ /dev/null @@ -1,1019 +0,0 @@ -grammar DRL; - -@members { - public String normalizeString( String input ) { - if( input != null && (input.length() == 2 || input.length() >= 4) ) { - input = input.substring( 1, input.length() - 1 ); - input = input.replaceAll( "\'", "'" ); - input = input.replaceAll( "\"", "\\\"" ); - input = "\"" + input + "\""; - } - return input; - } -} - -///////////////// -// KEYWORDS -///////////////// - -PACKAGE : 'package'; -UNIT : 'unit'; -IMPORT : 'import'; -FUNCTION : 'function'; -STATIC : 'static'; -GLOBAL : 'global'; -RULE : 'rule'; -QUERY : 'query'; -EXTENDS : 'extends'; -SUPER : 'super'; -WHEN : 'when'; -THEN : 'then'; -END : 'end'; - -///////////////// -// LEXER -///////////////// - -WS : [ \t\r\n\u000C\u00A0]+ -> skip ; - -fragment -EOL : - ( '\r' // Macintosh - | '\n' // Unix (the right way) - ) - ; - -FLOAT - : ('0'..'9')+ '.' ('0'..'9')* Exponent? FloatTypeSuffix? - | '.' ('0'..'9')+ Exponent? FloatTypeSuffix? - | ('0'..'9')+ Exponent FloatTypeSuffix? - | ('0'..'9')+ FloatTypeSuffix - ; - -fragment -Exponent : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; - -fragment -FloatTypeSuffix : ('f'|'F'|'d'|'D'|'B') ; - -HEX : '0' ('x'|'X') HexDigit+ IntegerTypeSuffix? ; - -DECIMAL : ('0'..'9')+ IntegerTypeSuffix? ; - -fragment -IntegerTypeSuffix : ('l'|'L'|'I') ; - -STRING - : ('"' ( EscapeSequence | ~('\\'|'"') )* '"') - | ('\'' ( EscapeSequence | ~('\\'|'\'') )* '\'') { setText( normalizeString( getText() ) ); } - ; - - -TIME_INTERVAL - : (('0'..'9')+ 'd') (('0'..'9')+ 'h')?(('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? - | (('0'..'9')+ 'h') (('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? - | (('0'..'9')+ 'm') (('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? - | (('0'..'9')+ 's') (('0'..'9')+ 'ms'?)? - | (('0'..'9')+ 'ms'?) - ; - -fragment -HexDigit : ('0'..'9'|'a'..'f'|'A'..'F') ; - -fragment -EscapeSequence - : '\\' ('b'|'B'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\'|'.'|'o'| - 'x'|'a'|'e'|'c'|'d'|'D'|'s'|'S'|'w'|'W'|'p'|'A'| - 'G'|'Z'|'z'|'Q'|'E'|'*'|'['|']'|'('|')'|'$'|'^'| - '{'|'}'|'?'|'+'|'-'|'&'|'|') - | UnicodeEscape - | OctalEscape - ; - -fragment -OctalEscape - : '\\' ('0'..'3') ('0'..'7') ('0'..'7') - | '\\' ('0'..'7') ('0'..'7') - | '\\' ('0'..'7') - ; - -fragment -UnicodeEscape - : '\\' 'u' HexDigit HexDigit HexDigit HexDigit - ; - -///////////////// -// SYMBOLS -///////////////// - -BOOL : ('true'|'false') ; -NULL : 'null' ; -AT : '@' ; -PLUS_ASSIGN : '+=' ; -MINUS_ASSIGN : '-=' ; -MULT_ASSIGN : '*=' ; -DIV_ASSIGN : '/=' ; -AND_ASSIGN : '&=' ; -OR_ASSIGN : '|=' ; -XOR_ASSIGN : '^=' ; -MOD_ASSIGN : '%=' ; -UNIFY : ':=' ; -DECR : '--' ; -INCR : '++' ; -ARROW : '->' ; -SEMICOLON : ';' ; -COLON : ':' ; -EQUALS : '==' ; -NOT_EQUALS : '!=' ; -GREATER_EQUALS : '>=' ; -LESS_EQUALS : '<=' ; -GREATER : '>' ; -LESS : '<' ; -EQUALS_ASSIGN : '=' ; -LEFT_PAREN : '(' ; -RIGHT_PAREN : ')' ; - -LEFT_SQUARE - : '[' - ; - -RIGHT_SQUARE - : ']' - ; - -LEFT_CURLY - : '{' - ; - -RIGHT_CURLY - : '}' - ; - -COMMA : ',' - ; - -DOT : '.' - ; - -NULL_SAFE_DOT : '!.' - ; - -DOUBLE_AMPER - : '&&' - ; - -DOUBLE_PIPE - : '||' - ; - -QUESTION - : '?' - ; - -NEGATION - : '!' - ; - -TILDE - : '~' - ; - -PIPE - : '|' - ; - -AMPER - : '&' - ; - -XOR - : '^' - ; - -MOD - : '%' - ; - -STAR : '*' - ; - -MINUS : '-' - ; - -PLUS : '+' - ; - -HASH : '#' - ; - -C_STYLE_SINGLE_LINE_COMMENT - : '//' (~('\r'|'\n'))* (EOL|EOF) -> skip - ; - -MULTI_LINE_COMMENT - : '/*' (options{greedy=false;} : .)* '*/' -> skip - ; - -ID - : IdentifierStart IdentifierPart* - | '`' IdentifierStart IdentifierPart* '`' - ; - -// must come after the commentaries that use 2-character sequences with / -DIV : '/' - ; - -QUESTION_DIV - : '?/' - ; - -MISC : - '\'' | '\\' | '$' - ; - -fragment -IdentifierStart - : '\u0024' - | '\u0041'..'\u005a' - | '\u005f' - | '\u0061'..'\u007a' - | '\u00a2'..'\u00a5' - | '\u00aa' - | '\u00b5' - | '\u00ba' - | '\u00c0'..'\u00d6' - | '\u00d8'..'\u00f6' - | '\u00f8'..'\u0236' - | '\u0250'..'\u02c1' - | '\u02c6'..'\u02d1' - | '\u02e0'..'\u02e4' - | '\u02ee' - | '\u037a' - | '\u0386' - | '\u0388'..'\u038a' - | '\u038c' - | '\u038e'..'\u03a1' - | '\u03a3'..'\u03ce' - | '\u03d0'..'\u03f5' - | '\u03f7'..'\u03fb' - | '\u0400'..'\u0481' - | '\u048a'..'\u04ce' - | '\u04d0'..'\u04f5' - | '\u04f8'..'\u04f9' - | '\u0500'..'\u050f' - | '\u0531'..'\u0556' - | '\u0559' - | '\u0561'..'\u0587' - | '\u05d0'..'\u05ea' - | '\u05f0'..'\u05f2' - | '\u0621'..'\u063a' - | '\u0640'..'\u064a' - | '\u066e'..'\u066f' - | '\u0671'..'\u06d3' - | '\u06d5' - | '\u06e5'..'\u06e6' - | '\u06ee'..'\u06ef' - | '\u06fa'..'\u06fc' - | '\u06ff' - | '\u0710' - | '\u0712'..'\u072f' - | '\u074d'..'\u074f' - | '\u0780'..'\u07a5' - | '\u07b1' - | '\u0904'..'\u0939' - | '\u093d' - | '\u0950' - | '\u0958'..'\u0961' - | '\u0985'..'\u098c' - | '\u098f'..'\u0990' - | '\u0993'..'\u09a8' - | '\u09aa'..'\u09b0' - | '\u09b2' - | '\u09b6'..'\u09b9' - | '\u09bd' - | '\u09dc'..'\u09dd' - | '\u09df'..'\u09e1' - | '\u09f0'..'\u09f3' - | '\u0a05'..'\u0a0a' - | '\u0a0f'..'\u0a10' - | '\u0a13'..'\u0a28' - | '\u0a2a'..'\u0a30' - | '\u0a32'..'\u0a33' - | '\u0a35'..'\u0a36' - | '\u0a38'..'\u0a39' - | '\u0a59'..'\u0a5c' - | '\u0a5e' - | '\u0a72'..'\u0a74' - | '\u0a85'..'\u0a8d' - | '\u0a8f'..'\u0a91' - | '\u0a93'..'\u0aa8' - | '\u0aaa'..'\u0ab0' - | '\u0ab2'..'\u0ab3' - | '\u0ab5'..'\u0ab9' - | '\u0abd' - | '\u0ad0' - | '\u0ae0'..'\u0ae1' - | '\u0af1' - | '\u0b05'..'\u0b0c' - | '\u0b0f'..'\u0b10' - | '\u0b13'..'\u0b28' - | '\u0b2a'..'\u0b30' - | '\u0b32'..'\u0b33' - | '\u0b35'..'\u0b39' - | '\u0b3d' - | '\u0b5c'..'\u0b5d' - | '\u0b5f'..'\u0b61' - | '\u0b71' - | '\u0b83' - | '\u0b85'..'\u0b8a' - | '\u0b8e'..'\u0b90' - | '\u0b92'..'\u0b95' - | '\u0b99'..'\u0b9a' - | '\u0b9c' - | '\u0b9e'..'\u0b9f' - | '\u0ba3'..'\u0ba4' - | '\u0ba8'..'\u0baa' - | '\u0bae'..'\u0bb5' - | '\u0bb7'..'\u0bb9' - | '\u0bf9' - | '\u0c05'..'\u0c0c' - | '\u0c0e'..'\u0c10' - | '\u0c12'..'\u0c28' - | '\u0c2a'..'\u0c33' - | '\u0c35'..'\u0c39' - | '\u0c60'..'\u0c61' - | '\u0c85'..'\u0c8c' - | '\u0c8e'..'\u0c90' - | '\u0c92'..'\u0ca8' - | '\u0caa'..'\u0cb3' - | '\u0cb5'..'\u0cb9' - | '\u0cbd' - | '\u0cde' - | '\u0ce0'..'\u0ce1' - | '\u0d05'..'\u0d0c' - | '\u0d0e'..'\u0d10' - | '\u0d12'..'\u0d28' - | '\u0d2a'..'\u0d39' - | '\u0d60'..'\u0d61' - | '\u0d85'..'\u0d96' - | '\u0d9a'..'\u0db1' - | '\u0db3'..'\u0dbb' - | '\u0dbd' - | '\u0dc0'..'\u0dc6' - | '\u0e01'..'\u0e30' - | '\u0e32'..'\u0e33' - | '\u0e3f'..'\u0e46' - | '\u0e81'..'\u0e82' - | '\u0e84' - | '\u0e87'..'\u0e88' - | '\u0e8a' - | '\u0e8d' - | '\u0e94'..'\u0e97' - | '\u0e99'..'\u0e9f' - | '\u0ea1'..'\u0ea3' - | '\u0ea5' - | '\u0ea7' - | '\u0eaa'..'\u0eab' - | '\u0ead'..'\u0eb0' - | '\u0eb2'..'\u0eb3' - | '\u0ebd' - | '\u0ec0'..'\u0ec4' - | '\u0ec6' - | '\u0edc'..'\u0edd' - | '\u0f00' - | '\u0f40'..'\u0f47' - | '\u0f49'..'\u0f6a' - | '\u0f88'..'\u0f8b' - | '\u1000'..'\u1021' - | '\u1023'..'\u1027' - | '\u1029'..'\u102a' - | '\u1050'..'\u1055' - | '\u10a0'..'\u10c5' - | '\u10d0'..'\u10f8' - | '\u1100'..'\u1159' - | '\u115f'..'\u11a2' - | '\u11a8'..'\u11f9' - | '\u1200'..'\u1206' - | '\u1208'..'\u1246' - | '\u1248' - | '\u124a'..'\u124d' - | '\u1250'..'\u1256' - | '\u1258' - | '\u125a'..'\u125d' - | '\u1260'..'\u1286' - | '\u1288' - | '\u128a'..'\u128d' - | '\u1290'..'\u12ae' - | '\u12b0' - | '\u12b2'..'\u12b5' - | '\u12b8'..'\u12be' - | '\u12c0' - | '\u12c2'..'\u12c5' - | '\u12c8'..'\u12ce' - | '\u12d0'..'\u12d6' - | '\u12d8'..'\u12ee' - | '\u12f0'..'\u130e' - | '\u1310' - | '\u1312'..'\u1315' - | '\u1318'..'\u131e' - | '\u1320'..'\u1346' - | '\u1348'..'\u135a' - | '\u13a0'..'\u13f4' - | '\u1401'..'\u166c' - | '\u166f'..'\u1676' - | '\u1681'..'\u169a' - | '\u16a0'..'\u16ea' - | '\u16ee'..'\u16f0' - | '\u1700'..'\u170c' - | '\u170e'..'\u1711' - | '\u1720'..'\u1731' - | '\u1740'..'\u1751' - | '\u1760'..'\u176c' - | '\u176e'..'\u1770' - | '\u1780'..'\u17b3' - | '\u17d7' - | '\u17db'..'\u17dc' - | '\u1820'..'\u1877' - | '\u1880'..'\u18a8' - | '\u1900'..'\u191c' - | '\u1950'..'\u196d' - | '\u1970'..'\u1974' - | '\u1d00'..'\u1d6b' - | '\u1e00'..'\u1e9b' - | '\u1ea0'..'\u1ef9' - | '\u1f00'..'\u1f15' - | '\u1f18'..'\u1f1d' - | '\u1f20'..'\u1f45' - | '\u1f48'..'\u1f4d' - | '\u1f50'..'\u1f57' - | '\u1f59' - | '\u1f5b' - | '\u1f5d' - | '\u1f5f'..'\u1f7d' - | '\u1f80'..'\u1fb4' - | '\u1fb6'..'\u1fbc' - | '\u1fbe' - | '\u1fc2'..'\u1fc4' - | '\u1fc6'..'\u1fcc' - | '\u1fd0'..'\u1fd3' - | '\u1fd6'..'\u1fdb' - | '\u1fe0'..'\u1fec' - | '\u1ff2'..'\u1ff4' - | '\u1ff6'..'\u1ffc' - | '\u203f'..'\u2040' - | '\u2054' - | '\u2071' - | '\u207f' - | '\u20a0'..'\u20b1' - | '\u2102' - | '\u2107' - | '\u210a'..'\u2113' - | '\u2115' - | '\u2119'..'\u211d' - | '\u2124' - | '\u2126' - | '\u2128' - | '\u212a'..'\u212d' - | '\u212f'..'\u2131' - | '\u2133'..'\u2139' - | '\u213d'..'\u213f' - | '\u2145'..'\u2149' - | '\u2160'..'\u2183' - | '\u3005'..'\u3007' - | '\u3021'..'\u3029' - | '\u3031'..'\u3035' - | '\u3038'..'\u303c' - | '\u3041'..'\u3096' - | '\u309d'..'\u309f' - | '\u30a1'..'\u30ff' - | '\u3105'..'\u312c' - | '\u3131'..'\u318e' - | '\u31a0'..'\u31b7' - | '\u31f0'..'\u31ff' - | '\u3400'..'\u4db5' - | '\u4e00'..'\u9fa5' - | '\ua000'..'\ua48c' - | '\uac00'..'\ud7a3' - | '\uf900'..'\ufa2d' - | '\ufa30'..'\ufa6a' - | '\ufb00'..'\ufb06' - | '\ufb13'..'\ufb17' - | '\ufb1d' - | '\ufb1f'..'\ufb28' - | '\ufb2a'..'\ufb36' - | '\ufb38'..'\ufb3c' - | '\ufb3e' - | '\ufb40'..'\ufb41' - | '\ufb43'..'\ufb44' - | '\ufb46'..'\ufbb1' - | '\ufbd3'..'\ufd3d' - | '\ufd50'..'\ufd8f' - | '\ufd92'..'\ufdc7' - | '\ufdf0'..'\ufdfc' - | '\ufe33'..'\ufe34' - | '\ufe4d'..'\ufe4f' - | '\ufe69' - | '\ufe70'..'\ufe74' - | '\ufe76'..'\ufefc' - | '\uff04' - | '\uff21'..'\uff3a' - | '\uff3f' - | '\uff41'..'\uff5a' - | '\uff65'..'\uffbe' - | '\uffc2'..'\uffc7' - | '\uffca'..'\uffcf' - | '\uffd2'..'\uffd7' - | '\uffda'..'\uffdc' - | '\uffe0'..'\uffe1' - | '\uffe5'..'\uffe6' -// UTF-16: | ('\ud800'..'\udbff') ('\udc00'..'\udfff') - ; - -fragment -IdentifierPart - : '\u0000'..'\u0008' - | '\u000e'..'\u001b' - | '\u0024' - | '\u0030'..'\u0039' - | '\u0041'..'\u005a' - | '\u005f' - | '\u0061'..'\u007a' - | '\u007f'..'\u009f' - | '\u00a2'..'\u00a5' - | '\u00aa' - | '\u00ad' - | '\u00b5' - | '\u00ba' - | '\u00c0'..'\u00d6' - | '\u00d8'..'\u00f6' - | '\u00f8'..'\u0236' - | '\u0250'..'\u02c1' - | '\u02c6'..'\u02d1' - | '\u02e0'..'\u02e4' - | '\u02ee' - | '\u0300'..'\u0357' - | '\u035d'..'\u036f' - | '\u037a' - | '\u0386' - | '\u0388'..'\u038a' - | '\u038c' - | '\u038e'..'\u03a1' - | '\u03a3'..'\u03ce' - | '\u03d0'..'\u03f5' - | '\u03f7'..'\u03fb' - | '\u0400'..'\u0481' - | '\u0483'..'\u0486' - | '\u048a'..'\u04ce' - | '\u04d0'..'\u04f5' - | '\u04f8'..'\u04f9' - | '\u0500'..'\u050f' - | '\u0531'..'\u0556' - | '\u0559' - | '\u0561'..'\u0587' - | '\u0591'..'\u05a1' - | '\u05a3'..'\u05b9' - | '\u05bb'..'\u05bd' - | '\u05bf' - | '\u05c1'..'\u05c2' - | '\u05c4' - | '\u05d0'..'\u05ea' - | '\u05f0'..'\u05f2' - | '\u0600'..'\u0603' - | '\u0610'..'\u0615' - | '\u0621'..'\u063a' - | '\u0640'..'\u0658' - | '\u0660'..'\u0669' - | '\u066e'..'\u06d3' - | '\u06d5'..'\u06dd' - | '\u06df'..'\u06e8' - | '\u06ea'..'\u06fc' - | '\u06ff' - | '\u070f'..'\u074a' - | '\u074d'..'\u074f' - | '\u0780'..'\u07b1' - | '\u0901'..'\u0939' - | '\u093c'..'\u094d' - | '\u0950'..'\u0954' - | '\u0958'..'\u0963' - | '\u0966'..'\u096f' - | '\u0981'..'\u0983' - | '\u0985'..'\u098c' - | '\u098f'..'\u0990' - | '\u0993'..'\u09a8' - | '\u09aa'..'\u09b0' - | '\u09b2' - | '\u09b6'..'\u09b9' - | '\u09bc'..'\u09c4' - | '\u09c7'..'\u09c8' - | '\u09cb'..'\u09cd' - | '\u09d7' - | '\u09dc'..'\u09dd' - | '\u09df'..'\u09e3' - | '\u09e6'..'\u09f3' - | '\u0a01'..'\u0a03' - | '\u0a05'..'\u0a0a' - | '\u0a0f'..'\u0a10' - | '\u0a13'..'\u0a28' - | '\u0a2a'..'\u0a30' - | '\u0a32'..'\u0a33' - | '\u0a35'..'\u0a36' - | '\u0a38'..'\u0a39' - | '\u0a3c' - | '\u0a3e'..'\u0a42' - | '\u0a47'..'\u0a48' - | '\u0a4b'..'\u0a4d' - | '\u0a59'..'\u0a5c' - | '\u0a5e' - | '\u0a66'..'\u0a74' - | '\u0a81'..'\u0a83' - | '\u0a85'..'\u0a8d' - | '\u0a8f'..'\u0a91' - | '\u0a93'..'\u0aa8' - | '\u0aaa'..'\u0ab0' - | '\u0ab2'..'\u0ab3' - | '\u0ab5'..'\u0ab9' - | '\u0abc'..'\u0ac5' - | '\u0ac7'..'\u0ac9' - | '\u0acb'..'\u0acd' - | '\u0ad0' - | '\u0ae0'..'\u0ae3' - | '\u0ae6'..'\u0aef' - | '\u0af1' - | '\u0b01'..'\u0b03' - | '\u0b05'..'\u0b0c' - | '\u0b0f'..'\u0b10' - | '\u0b13'..'\u0b28' - | '\u0b2a'..'\u0b30' - | '\u0b32'..'\u0b33' - | '\u0b35'..'\u0b39' - | '\u0b3c'..'\u0b43' - | '\u0b47'..'\u0b48' - | '\u0b4b'..'\u0b4d' - | '\u0b56'..'\u0b57' - | '\u0b5c'..'\u0b5d' - | '\u0b5f'..'\u0b61' - | '\u0b66'..'\u0b6f' - | '\u0b71' - | '\u0b82'..'\u0b83' - | '\u0b85'..'\u0b8a' - | '\u0b8e'..'\u0b90' - | '\u0b92'..'\u0b95' - | '\u0b99'..'\u0b9a' - | '\u0b9c' - | '\u0b9e'..'\u0b9f' - | '\u0ba3'..'\u0ba4' - | '\u0ba8'..'\u0baa' - | '\u0bae'..'\u0bb5' - | '\u0bb7'..'\u0bb9' - | '\u0bbe'..'\u0bc2' - | '\u0bc6'..'\u0bc8' - | '\u0bca'..'\u0bcd' - | '\u0bd7' - | '\u0be7'..'\u0bef' - | '\u0bf9' - | '\u0c01'..'\u0c03' - | '\u0c05'..'\u0c0c' - | '\u0c0e'..'\u0c10' - | '\u0c12'..'\u0c28' - | '\u0c2a'..'\u0c33' - | '\u0c35'..'\u0c39' - | '\u0c3e'..'\u0c44' - | '\u0c46'..'\u0c48' - | '\u0c4a'..'\u0c4d' - | '\u0c55'..'\u0c56' - | '\u0c60'..'\u0c61' - | '\u0c66'..'\u0c6f' - | '\u0c82'..'\u0c83' - | '\u0c85'..'\u0c8c' - | '\u0c8e'..'\u0c90' - | '\u0c92'..'\u0ca8' - | '\u0caa'..'\u0cb3' - | '\u0cb5'..'\u0cb9' - | '\u0cbc'..'\u0cc4' - | '\u0cc6'..'\u0cc8' - | '\u0cca'..'\u0ccd' - | '\u0cd5'..'\u0cd6' - | '\u0cde' - | '\u0ce0'..'\u0ce1' - | '\u0ce6'..'\u0cef' - | '\u0d02'..'\u0d03' - | '\u0d05'..'\u0d0c' - | '\u0d0e'..'\u0d10' - | '\u0d12'..'\u0d28' - | '\u0d2a'..'\u0d39' - | '\u0d3e'..'\u0d43' - | '\u0d46'..'\u0d48' - | '\u0d4a'..'\u0d4d' - | '\u0d57' - | '\u0d60'..'\u0d61' - | '\u0d66'..'\u0d6f' - | '\u0d82'..'\u0d83' - | '\u0d85'..'\u0d96' - | '\u0d9a'..'\u0db1' - | '\u0db3'..'\u0dbb' - | '\u0dbd' - | '\u0dc0'..'\u0dc6' - | '\u0dca' - | '\u0dcf'..'\u0dd4' - | '\u0dd6' - | '\u0dd8'..'\u0ddf' - | '\u0df2'..'\u0df3' - | '\u0e01'..'\u0e3a' - | '\u0e3f'..'\u0e4e' - | '\u0e50'..'\u0e59' - | '\u0e81'..'\u0e82' - | '\u0e84' - | '\u0e87'..'\u0e88' - | '\u0e8a' - | '\u0e8d' - | '\u0e94'..'\u0e97' - | '\u0e99'..'\u0e9f' - | '\u0ea1'..'\u0ea3' - | '\u0ea5' - | '\u0ea7' - | '\u0eaa'..'\u0eab' - | '\u0ead'..'\u0eb9' - | '\u0ebb'..'\u0ebd' - | '\u0ec0'..'\u0ec4' - | '\u0ec6' - | '\u0ec8'..'\u0ecd' - | '\u0ed0'..'\u0ed9' - | '\u0edc'..'\u0edd' - | '\u0f00' - | '\u0f18'..'\u0f19' - | '\u0f20'..'\u0f29' - | '\u0f35' - | '\u0f37' - | '\u0f39' - | '\u0f3e'..'\u0f47' - | '\u0f49'..'\u0f6a' - | '\u0f71'..'\u0f84' - | '\u0f86'..'\u0f8b' - | '\u0f90'..'\u0f97' - | '\u0f99'..'\u0fbc' - | '\u0fc6' - | '\u1000'..'\u1021' - | '\u1023'..'\u1027' - | '\u1029'..'\u102a' - | '\u102c'..'\u1032' - | '\u1036'..'\u1039' - | '\u1040'..'\u1049' - | '\u1050'..'\u1059' - | '\u10a0'..'\u10c5' - | '\u10d0'..'\u10f8' - | '\u1100'..'\u1159' - | '\u115f'..'\u11a2' - | '\u11a8'..'\u11f9' - | '\u1200'..'\u1206' - | '\u1208'..'\u1246' - | '\u1248' - | '\u124a'..'\u124d' - | '\u1250'..'\u1256' - | '\u1258' - | '\u125a'..'\u125d' - | '\u1260'..'\u1286' - | '\u1288' - | '\u128a'..'\u128d' - | '\u1290'..'\u12ae' - | '\u12b0' - | '\u12b2'..'\u12b5' - | '\u12b8'..'\u12be' - | '\u12c0' - | '\u12c2'..'\u12c5' - | '\u12c8'..'\u12ce' - | '\u12d0'..'\u12d6' - | '\u12d8'..'\u12ee' - | '\u12f0'..'\u130e' - | '\u1310' - | '\u1312'..'\u1315' - | '\u1318'..'\u131e' - | '\u1320'..'\u1346' - | '\u1348'..'\u135a' - | '\u1369'..'\u1371' - | '\u13a0'..'\u13f4' - | '\u1401'..'\u166c' - | '\u166f'..'\u1676' - | '\u1681'..'\u169a' - | '\u16a0'..'\u16ea' - | '\u16ee'..'\u16f0' - | '\u1700'..'\u170c' - | '\u170e'..'\u1714' - | '\u1720'..'\u1734' - | '\u1740'..'\u1753' - | '\u1760'..'\u176c' - | '\u176e'..'\u1770' - | '\u1772'..'\u1773' - | '\u1780'..'\u17d3' - | '\u17d7' - | '\u17db'..'\u17dd' - | '\u17e0'..'\u17e9' - | '\u180b'..'\u180d' - | '\u1810'..'\u1819' - | '\u1820'..'\u1877' - | '\u1880'..'\u18a9' - | '\u1900'..'\u191c' - | '\u1920'..'\u192b' - | '\u1930'..'\u193b' - | '\u1946'..'\u196d' - | '\u1970'..'\u1974' - | '\u1d00'..'\u1d6b' - | '\u1e00'..'\u1e9b' - | '\u1ea0'..'\u1ef9' - | '\u1f00'..'\u1f15' - | '\u1f18'..'\u1f1d' - | '\u1f20'..'\u1f45' - | '\u1f48'..'\u1f4d' - | '\u1f50'..'\u1f57' - | '\u1f59' - | '\u1f5b' - | '\u1f5d' - | '\u1f5f'..'\u1f7d' - | '\u1f80'..'\u1fb4' - | '\u1fb6'..'\u1fbc' - | '\u1fbe' - | '\u1fc2'..'\u1fc4' - | '\u1fc6'..'\u1fcc' - | '\u1fd0'..'\u1fd3' - | '\u1fd6'..'\u1fdb' - | '\u1fe0'..'\u1fec' - | '\u1ff2'..'\u1ff4' - | '\u1ff6'..'\u1ffc' - | '\u200c'..'\u200f' - | '\u202a'..'\u202e' - | '\u203f'..'\u2040' - | '\u2054' - | '\u2060'..'\u2063' - | '\u206a'..'\u206f' - | '\u2071' - | '\u207f' - | '\u20a0'..'\u20b1' - | '\u20d0'..'\u20dc' - | '\u20e1' - | '\u20e5'..'\u20ea' - | '\u2102' - | '\u2107' - | '\u210a'..'\u2113' - | '\u2115' - | '\u2119'..'\u211d' - | '\u2124' - | '\u2126' - | '\u2128' - | '\u212a'..'\u212d' - | '\u212f'..'\u2131' - | '\u2133'..'\u2139' - | '\u213d'..'\u213f' - | '\u2145'..'\u2149' - | '\u2160'..'\u2183' - | '\u3005'..'\u3007' - | '\u3021'..'\u302f' - | '\u3031'..'\u3035' - | '\u3038'..'\u303c' - | '\u3041'..'\u3096' - | '\u3099'..'\u309a' - | '\u309d'..'\u309f' - | '\u30a1'..'\u30ff' - | '\u3105'..'\u312c' - | '\u3131'..'\u318e' - | '\u31a0'..'\u31b7' - | '\u31f0'..'\u31ff' - | '\u3400'..'\u4db5' - | '\u4e00'..'\u9fa5' - | '\ua000'..'\ua48c' - | '\uac00'..'\ud7a3' - | '\uf900'..'\ufa2d' - | '\ufa30'..'\ufa6a' - | '\ufb00'..'\ufb06' - | '\ufb13'..'\ufb17' - | '\ufb1d'..'\ufb28' - | '\ufb2a'..'\ufb36' - | '\ufb38'..'\ufb3c' - | '\ufb3e' - | '\ufb40'..'\ufb41' - | '\ufb43'..'\ufb44' - | '\ufb46'..'\ufbb1' - | '\ufbd3'..'\ufd3d' - | '\ufd50'..'\ufd8f' - | '\ufd92'..'\ufdc7' - | '\ufdf0'..'\ufdfc' - | '\ufe00'..'\ufe0f' - | '\ufe20'..'\ufe23' - | '\ufe33'..'\ufe34' - | '\ufe4d'..'\ufe4f' - | '\ufe69' - | '\ufe70'..'\ufe74' - | '\ufe76'..'\ufefc' - | '\ufeff' - | '\uff04' - | '\uff10'..'\uff19' - | '\uff21'..'\uff3a' - | '\uff3f' - | '\uff41'..'\uff5a' - | '\uff65'..'\uffbe' - | '\uffc2'..'\uffc7' - | '\uffca'..'\uffcf' - | '\uffd2'..'\uffd7' - | '\uffda'..'\uffdc' - | '\uffe0'..'\uffe1' - | '\uffe5'..'\uffe6' - | '\ufff9'..'\ufffb' -// UTF-16 | ('\ud800'..'\udbff') ('\udc00'..'\udfff') - ; - -///////////////// -// PARSER -///////////////// - -compilationunit : packagedef? unitdef? importdef* globaldef* ruledef* ; - -packagedef : PACKAGE name=qualifiedIdentifier SEMICOLON? ; - -unitdef : UNIT name=qualifiedIdentifier SEMICOLON? ; - -importdef : IMPORT (FUNCTION|STATIC)? qualifiedIdentifier (DOT STAR)? SEMICOLON? ; - -globaldef : GLOBAL type ID SEMICOLON? ; - -ruledef : RULE name=stringId (EXTENDS stringId)? annotation* attributes? WHEN lhs THEN rhs END ; - -lhs : lhsExpression ; -lhsExpression : lhsOr* ; -lhsOr : LEFT_PAREN OR lhsAnd+ RIGHT_PAREN | lhsAnd (OR lhsAnd)* ; -lhsAnd : LEFT_PAREN AND lhsUnary+ RIGHT_PAREN | lhsUnary (AND lhsUnary)* ; - -/* -lhsUnary : ( lhsExists namedConsequence? - | lhsNot namedConsequence? - | lhsEval consequenceInvocation* - | lhsForall - | lhsAccumulate - | LEFT_PAREN lhsOr RIGHT_PAREN namedConsequence? - | lhsPatternBind consequenceInvocation* - ) SEMICOLON? ; -*/ - -lhsUnary : lhsPatternBind ; -lhsPatternBind : label? ( LEFT_PAREN lhsPattern (OR lhsPattern)* RIGHT_PAREN | lhsPattern ) ; - -/* -lhsPattern : xpathPrimary (OVER patternFilter)? | - ( QUESTION? qualifiedIdentifier LEFT_PAREN positionalConstraints? constraints? RIGHT_PAREN (OVER patternFilter)? (FROM patternSource)? ) ; -*/ - -lhsPattern : QUESTION? objectType=qualifiedIdentifier LEFT_PAREN positionalConstraints? constraints? RIGHT_PAREN ; -positionalConstraints : constraint (COMMA constraint)* SEMICOLON ; -constraints : constraint (COMMA constraint)* ; -constraint : nestedConstraint | conditionalOrExpression ; -nestedConstraint : ( ID ( DOT | HASH ) )* ID DOT LEFT_PAREN constraints RIGHT_PAREN ; -conditionalOrExpression : left=conditionalAndExpression (DOUBLE_PIPE right=conditionalAndExpression)* ; -conditionalAndExpression : left=inclusiveOrExpression (DOUBLE_AMPER right=inclusiveOrExpression)* ; -inclusiveOrExpression : left=exclusiveOrExpression (PIPE right=exclusiveOrExpression)* ; -exclusiveOrExpression : left=andExpression (XOR right=andExpression)* ; -andExpression : left=equalityExpression (AMPER right=equalityExpression)* ; -equalityExpression : left=instanceOfExpression ( ( op=EQUALS | op=NOT_EQUALS ) right=instanceOfExpression )* ; -instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; -inExpression : left=relationalExpression ( 'not'? 'in' LEFT_PAREN expression (COMMA expression)* RIGHT_PAREN )? ; -relationalExpression : TEXT? ; // TODO - -expression : conditionalExpression ( op=assignmentOperator right=expression )? ; -conditionalExpression : left=conditionalOrExpression ternaryExpression? ; -ternaryExpression : QUESTION ts=expression COLON fs=expression ; - -rhs : TEXT ; - -stringId : ( ID | STRING ) ; - -qualifiedIdentifier : ID ( DOT ID )* ; - -type : ID typeArguments? ( DOT ID typeArguments? )* (LEFT_SQUARE RIGHT_SQUARE)* ; - -typeArguments : LESS typeArgument (COMMA typeArgument)* GREATER ; -typeArgument : QUESTION (( EXTENDS | SUPER ) type )? | type ; - -arguments : LEFT_PAREN argument (COMMA argument)* RIGHT_PAREN ; -argument : ( stringId | FLOAT | BOOL | NULL ) ; - -annotation : AT name=qualifiedIdentifier arguments? ; - -attributes : attribute ( COMMA? attribute )* ; -attribute : ( 'salience' DECIMAL ) - | ( 'enabled' | 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOLEAN? - | ( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) STRING - | 'calendars' STRING ( COMMA STRING )* - | 'timer' ( DECIMAL | TEXT ) - | 'duration' ( DECIMAL | TEXT ) ; - -assignmentOperator : EQUALS_ASSIGN - | PLUS_ASSIGN - | MINUS_ASSIGN - | MULT_ASSIGN - | DIV_ASSIGN - | AND_ASSIGN - | OR_ASSIGN - | XOR_ASSIGN - | MOD_ASSIGN - | LESS LESS EQUALS_ASSIGN ; - -label : ID COLON ; -unif : ID UNIFY ; - -fragment TEXT : .+ ; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 new file mode 100644 index 00000000000..732a0d3bcc9 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -0,0 +1,77 @@ +lexer grammar DRLLexer; + +import JavaLexer; + +@members { + public String normalizeString( String input ) { + if( input != null && (input.length() == 2 || input.length() >= 4) ) { + input = input.substring( 1, input.length() - 1 ); + input = input.replaceAll( "\'", "'" ); + input = input.replaceAll( "\"", "\\\"" ); + input = "\"" + input + "\""; + } + return input; + } +} + +///////////////// +// KEYWORDS +///////////////// + +PACKAGE : 'package'; +UNIT : 'unit'; +IMPORT : 'import'; +FUNCTION : 'function'; +STATIC : 'static'; +GLOBAL : 'global'; +RULE : 'rule'; +QUERY : 'query'; +EXTENDS : 'extends'; +SUPER : 'super'; +WHEN : 'when'; +THEN : 'then'; +END : 'end'; + +NOT : 'not'; +IN : 'in'; + +SALIENCE : 'salience'; +ENABLED : 'enabled'; +NO_LOOP : 'no-loop'; +AUTO_FOCUS : 'auto-focus'; +LOCK_ON_ACTIVE : 'lock-on-active'; +REFRACT : 'refract'; +DIRECT : 'direct'; +AGENDA_GROUP : 'agenda-group'; +ACTIVATION_GROUP : 'activation-group'; +RULEFLOW_GROUP : 'ruleflow-group'; +DATE_EFFECTIVE : 'date-effective'; +DATE_EXPIRES : 'date-expires'; +DIALECT : 'dialect'; +CALENDARS : 'calendars'; +TIMER : 'timer'; +DURATION : 'duration'; + +///////////////// +// LEXER +///////////////// + +TIME_INTERVAL + : (('0'..'9')+ 'd') (('0'..'9')+ 'h')?(('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'h') (('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'm') (('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 's') (('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'ms') + ; + + +///////////////// +// SYMBOLS +///////////////// + +HASH : '#'; +UNIFY : ':=' ; +NULL_SAFE_DOT : '!.' ; +QUESTION_DIV : '?/' ; + +MISC : '\'' | '\\' | '$' ; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 new file mode 100644 index 00000000000..31bf8c80eed --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -0,0 +1,97 @@ +parser grammar DRLParser; + +options { tokenVocab=DRLLexer; } + +import JavaParser; + + +compilationUnit : packagedef? unitdef? importdef* globaldef* ruledef* ; + +packagedef : PACKAGE name=qualifiedName SEMI? ; + +unitdef : UNIT name=qualifiedName SEMI? ; + +importdef : IMPORT (FUNCTION|STATIC)? qualifiedName (DOT MUL)? SEMI? ; + +globaldef : GLOBAL type IDENTIFIER SEMI? ; + +ruledef : RULE name=stringId (EXTENDS stringId)? drlAnnotation* attributes? WHEN lhs THEN rhs END ; + +lhs : lhsExpression ; +lhsExpression : lhsOr* ; +lhsOr : LPAREN OR lhsAnd+ RPAREN | lhsAnd (OR lhsAnd)* ; +lhsAnd : LPAREN AND lhsUnary+ RPAREN | lhsUnary (AND lhsUnary)* ; + +/* +lhsUnary : ( lhsExists namedConsequence? + | lhsNot namedConsequence? + | lhsEval consequenceInvocation* + | lhsForall + | lhsAccumulate + | LPAREN lhsOr RPAREN namedConsequence? + | lhsPatternBind consequenceInvocation* + ) SEMI? ; +*/ + +lhsUnary : lhsPatternBind ; +lhsPatternBind : label? ( LPAREN lhsPattern (OR lhsPattern)* RPAREN | lhsPattern ) ; + +/* +lhsPattern : xpathPrimary (OVER patternFilter)? | + ( QUESTION? qualifiedIdentifier LPAREN positionalConstraints? constraints? RPAREN (OVER patternFilter)? (FROM patternSource)? ) ; +*/ + +lhsPattern : QUESTION? objectType=qualifiedName LPAREN positionalConstraints? constraints? RPAREN ; +positionalConstraints : constraint (COMMA constraint)* SEMI ; +constraints : constraint (COMMA constraint)* ; +constraint : label? ( nestedConstraint | conditionalOrExpression ) ; +nestedConstraint : ( IDENTIFIER ( DOT | HASH ) )* IDENTIFIER DOT LPAREN constraints RPAREN ; +conditionalOrExpression : left=conditionalAndExpression (OR right=conditionalAndExpression)* ; +conditionalAndExpression : left=inclusiveOrExpression (AND right=inclusiveOrExpression)* ; +inclusiveOrExpression : left=exclusiveOrExpression (BITOR right=exclusiveOrExpression)* ; +exclusiveOrExpression : left=andExpression (CARET right=andExpression)* ; +andExpression : left=equalityExpression (BITAND right=equalityExpression)* ; +equalityExpression : left=instanceOfExpression ( ( op=EQUAL | op=NOTEQUAL ) right=instanceOfExpression )* ; +instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; +inExpression : left=relationalExpression ( 'not'? 'in' LPAREN drlExpression (COMMA drlExpression)* RPAREN )? ; +relationalExpression : expression? ; // TODO + +drlExpression : conditionalExpression ( op=assignmentOperator right=drlExpression )? ; +conditionalExpression : left=conditionalOrExpression ternaryExpression? ; +ternaryExpression : QUESTION ts=drlExpression COLON fs=drlExpression ; + +rhs : blockStatement+ ; + +stringId : ( IDENTIFIER | STRING_LITERAL ) ; + +type : IDENTIFIER typeArguments? ( DOT IDENTIFIER typeArguments? )* (LBRACK RBRACK)* ; + +//typeArguments : LT typeArgument (COMMA typeArgument)* GT ; +//typeArgument : QUESTION (( EXTENDS | SUPER ) type )? | type ; + +drlArguments : LPAREN drlArgument (COMMA drlArgument)* RPAREN ; +drlArgument : ( stringId | floatLiteral | BOOL_LITERAL | NULL_LITERAL ) ; + +drlAnnotation : AT name=qualifiedName drlArguments? ; + +attributes : attribute ( COMMA? attribute )* ; +attribute : ( 'salience' DECIMAL_LITERAL ) + | ( 'enabled' | 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOLEAN? + | ( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) STRING_LITERAL + | 'calendars' STRING_LITERAL ( COMMA STRING_LITERAL )* + | 'timer' ( DECIMAL_LITERAL | TEXT ) + | 'duration' ( DECIMAL_LITERAL | TEXT ) ; + +assignmentOperator : ASSIGN + | ADD_ASSIGN + | SUB_ASSIGN + | MUL_ASSIGN + | DIV_ASSIGN + | AND_ASSIGN + | OR_ASSIGN + | XOR_ASSIGN + | MOD_ASSIGN + | LT LT ASSIGN ; + +label : IDENTIFIER COLON ; +unif : IDENTIFIER UNIFY ; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaLexer.g4 new file mode 100644 index 00000000000..1af884db096 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaLexer.g4 @@ -0,0 +1,245 @@ +/* + [The "BSD licence"] + Copyright (c) 2013 Terence Parr, Sam Harwell + Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) + Copyright (c) 2021 Michał Lorek (upgrade to Java 11) + Copyright (c) 2022 Michał Lorek (upgrade to Java 17) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// source: https://github.com/antlr/grammars-v4/tree/master/java/java + +lexer grammar JavaLexer; + +// Keywords + +ABSTRACT: 'abstract'; +ASSERT: 'assert'; +BOOLEAN: 'boolean'; +BREAK: 'break'; +BYTE: 'byte'; +CASE: 'case'; +CATCH: 'catch'; +CHAR: 'char'; +CLASS: 'class'; +CONST: 'const'; +CONTINUE: 'continue'; +DEFAULT: 'default'; +DO: 'do'; +DOUBLE: 'double'; +ELSE: 'else'; +ENUM: 'enum'; +EXTENDS: 'extends'; +FINAL: 'final'; +FINALLY: 'finally'; +FLOAT: 'float'; +FOR: 'for'; +IF: 'if'; +GOTO: 'goto'; +IMPLEMENTS: 'implements'; +IMPORT: 'import'; +INSTANCEOF: 'instanceof'; +INT: 'int'; +INTERFACE: 'interface'; +LONG: 'long'; +NATIVE: 'native'; +NEW: 'new'; +PACKAGE: 'package'; +PRIVATE: 'private'; +PROTECTED: 'protected'; +PUBLIC: 'public'; +RETURN: 'return'; +SHORT: 'short'; +STATIC: 'static'; +STRICTFP: 'strictfp'; +SUPER: 'super'; +SWITCH: 'switch'; +SYNCHRONIZED: 'synchronized'; +THIS: 'this'; +THROW: 'throw'; +THROWS: 'throws'; +TRANSIENT: 'transient'; +TRY: 'try'; +VOID: 'void'; +VOLATILE: 'volatile'; +WHILE: 'while'; + +// Module related keywords +MODULE: 'module'; +OPEN: 'open'; +REQUIRES: 'requires'; +EXPORTS: 'exports'; +OPENS: 'opens'; +TO: 'to'; +USES: 'uses'; +PROVIDES: 'provides'; +WITH: 'with'; +TRANSITIVE: 'transitive'; + +// Local Variable Type Inference +VAR: 'var'; // reserved type name + +// Switch Expressions +YIELD: 'yield'; + +// Records +RECORD: 'record'; + +// Sealed Classes +SEALED: 'sealed'; +PERMITS: 'permits'; +NON_SEALED: 'non-sealed'; + +// Literals + +DECIMAL_LITERAL: ('0' | [1-9] (Digits? | '_'+ Digits)) [lL]?; +HEX_LITERAL: '0' [xX] [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? [lL]?; +OCT_LITERAL: '0' '_'* [0-7] ([0-7_]* [0-7])? [lL]?; +BINARY_LITERAL: '0' [bB] [01] ([01_]* [01])? [lL]?; + +FLOAT_LITERAL: (Digits '.' Digits? | '.' Digits) ExponentPart? [fFdD]? + | Digits (ExponentPart [fFdD]? | [fFdD]) + ; + +HEX_FLOAT_LITERAL: '0' [xX] (HexDigits '.'? | HexDigits? '.' HexDigits) [pP] [+-]? Digits [fFdD]?; + +BOOL_LITERAL: 'true' + | 'false' + ; + +CHAR_LITERAL: '\'' (~['\\\r\n] | EscapeSequence) '\''; + +STRING_LITERAL: '"' (~["\\\r\n] | EscapeSequence)* '"'; + +TEXT_BLOCK: '"""' [ \t]* [\r\n] (. | EscapeSequence)*? '"""'; + +NULL_LITERAL: 'null'; + +// Separators + +LPAREN: '('; +RPAREN: ')'; +LBRACE: '{'; +RBRACE: '}'; +LBRACK: '['; +RBRACK: ']'; +SEMI: ';'; +COMMA: ','; +DOT: '.'; + +// Operators + +ASSIGN: '='; +GT: '>'; +LT: '<'; +BANG: '!'; +TILDE: '~'; +QUESTION: '?'; +COLON: ':'; +EQUAL: '=='; +LE: '<='; +GE: '>='; +NOTEQUAL: '!='; +AND: '&&'; +OR: '||'; +INC: '++'; +DEC: '--'; +ADD: '+'; +SUB: '-'; +MUL: '*'; +DIV: '/'; +BITAND: '&'; +BITOR: '|'; +CARET: '^'; +MOD: '%'; + +ADD_ASSIGN: '+='; +SUB_ASSIGN: '-='; +MUL_ASSIGN: '*='; +DIV_ASSIGN: '/='; +AND_ASSIGN: '&='; +OR_ASSIGN: '|='; +XOR_ASSIGN: '^='; +MOD_ASSIGN: '%='; +LSHIFT_ASSIGN: '<<='; +RSHIFT_ASSIGN: '>>='; +URSHIFT_ASSIGN: '>>>='; + +// Java 8 tokens + +ARROW: '->'; +COLONCOLON: '::'; + +// Additional symbols not defined in the lexical specification + +AT: '@'; +ELLIPSIS: '...'; + +// Whitespace and comments + +WS: [ \t\r\n\u000C]+ -> channel(HIDDEN); +COMMENT: '/*' .*? '*/' -> channel(HIDDEN); +LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN); + +// Identifiers + +IDENTIFIER: Letter LetterOrDigit*; + +// Fragment rules + +fragment ExponentPart + : [eE] [+-]? Digits + ; + +fragment EscapeSequence + : '\\' [btnfr"'\\] + | '\\' ([0-3]? [0-7])? [0-7] + | '\\' 'u'+ HexDigit HexDigit HexDigit HexDigit + ; + +fragment HexDigits + : HexDigit ((HexDigit | '_')* HexDigit)? + ; + +fragment HexDigit + : [0-9a-fA-F] + ; + +fragment Digits + : [0-9] ([0-9_]* [0-9])? + ; + +fragment LetterOrDigit + : Letter + | [0-9] + ; + +fragment Letter + : [a-zA-Z$_] // these are the "java letters" below 0x7F + | ~[\u0000-\u007F\uD800-\uDBFF] // covers all characters above 0x7F which are not a surrogate + | [\uD800-\uDBFF] [\uDC00-\uDFFF] // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF + ; + +TEXT : .+? ; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaParser.g4 new file mode 100644 index 00000000000..9e9f0a68513 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaParser.g4 @@ -0,0 +1,752 @@ +/* + [The "BSD licence"] + Copyright (c) 2013 Terence Parr, Sam Harwell + Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) + Copyright (c) 2021 Michał Lorek (upgrade to Java 11) + Copyright (c) 2022 Michał Lorek (upgrade to Java 17) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// source: https://github.com/antlr/grammars-v4/tree/master/java/java + +parser grammar JavaParser; + +options { tokenVocab=JavaLexer; } + +compilationUnit + : packageDeclaration? importDeclaration* typeDeclaration* + | moduleDeclaration EOF + ; + +packageDeclaration + : annotation* PACKAGE qualifiedName SEMI + ; + +importDeclaration + : IMPORT STATIC? qualifiedName (DOT MUL)? SEMI + ; + +typeDeclaration + : classOrInterfaceModifier* + (classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration | recordDeclaration) + | SEMI + ; + +modifier + : classOrInterfaceModifier + | NATIVE + | SYNCHRONIZED + | TRANSIENT + | VOLATILE + ; + +classOrInterfaceModifier + : annotation + | PUBLIC + | PROTECTED + | PRIVATE + | STATIC + | ABSTRACT + | FINAL // FINAL for class only -- does not apply to interfaces + | STRICTFP + | SEALED // Java17 + | NON_SEALED // Java17 + ; + +variableModifier + : FINAL + | annotation + ; + +classDeclaration + : CLASS identifier typeParameters? + (EXTENDS typeType)? + (IMPLEMENTS typeList)? + (PERMITS typeList)? // Java17 + classBody + ; + +typeParameters + : LT typeParameter (COMMA typeParameter)* GT + ; + +typeParameter + : annotation* identifier (EXTENDS annotation* typeBound)? + ; + +typeBound + : typeType (BITAND typeType)* + ; + +enumDeclaration + : ENUM identifier (IMPLEMENTS typeList)? LBRACE enumConstants? COMMA? enumBodyDeclarations? RBRACE + ; + +enumConstants + : enumConstant (COMMA enumConstant)* + ; + +enumConstant + : annotation* identifier arguments? classBody? + ; + +enumBodyDeclarations + : SEMI classBodyDeclaration* + ; + +interfaceDeclaration + : INTERFACE identifier typeParameters? (EXTENDS typeList)? (PERMITS typeList)? interfaceBody + ; + +classBody + : LBRACE classBodyDeclaration* RBRACE + ; + +interfaceBody + : LBRACE interfaceBodyDeclaration* RBRACE + ; + +classBodyDeclaration + : SEMI + | STATIC? block + | modifier* memberDeclaration + ; + +memberDeclaration + : methodDeclaration + | genericMethodDeclaration + | fieldDeclaration + | constructorDeclaration + | genericConstructorDeclaration + | interfaceDeclaration + | annotationTypeDeclaration + | classDeclaration + | enumDeclaration + | recordDeclaration //Java17 + ; + +/* We use rule this even for void methods which cannot have [] after parameters. + This simplifies grammar and we can consider void to be a type, which + renders the [] matching as a context-sensitive issue or a semantic check + for invalid return type after parsing. + */ +methodDeclaration + : typeTypeOrVoid identifier formalParameters (LBRACK RBRACK)* + (THROWS qualifiedNameList)? + methodBody + ; + +methodBody + : block + | SEMI + ; + +typeTypeOrVoid + : typeType + | VOID + ; + +genericMethodDeclaration + : typeParameters methodDeclaration + ; + +genericConstructorDeclaration + : typeParameters constructorDeclaration + ; + +constructorDeclaration + : identifier formalParameters (THROWS qualifiedNameList)? constructorBody=block + ; + +fieldDeclaration + : typeType variableDeclarators SEMI + ; + +interfaceBodyDeclaration + : modifier* interfaceMemberDeclaration + | SEMI + ; + +interfaceMemberDeclaration + : constDeclaration + | interfaceMethodDeclaration + | genericInterfaceMethodDeclaration + | interfaceDeclaration + | annotationTypeDeclaration + | classDeclaration + | enumDeclaration + | recordDeclaration // Java17 + ; + +constDeclaration + : typeType constantDeclarator (COMMA constantDeclarator)* SEMI + ; + +constantDeclarator + : identifier (LBRACK RBRACK)* ASSIGN variableInitializer + ; + +// Early versions of Java allows brackets after the method name, eg. +// public int[] return2DArray() [] { ... } +// is the same as +// public int[][] return2DArray() { ... } +interfaceMethodDeclaration + : interfaceMethodModifier* interfaceCommonBodyDeclaration + ; + +// Java8 +interfaceMethodModifier + : annotation + | PUBLIC + | ABSTRACT + | DEFAULT + | STATIC + | STRICTFP + ; + +genericInterfaceMethodDeclaration + : interfaceMethodModifier* typeParameters interfaceCommonBodyDeclaration + ; + +interfaceCommonBodyDeclaration + : annotation* typeTypeOrVoid identifier formalParameters (LBRACK RBRACK)* (THROWS qualifiedNameList)? methodBody + ; + +variableDeclarators + : variableDeclarator (COMMA variableDeclarator)* + ; + +variableDeclarator + : variableDeclaratorId (ASSIGN variableInitializer)? + ; + +variableDeclaratorId + : identifier (LBRACK RBRACK)* + ; + +variableInitializer + : arrayInitializer + | expression + ; + +arrayInitializer + : LBRACE (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RBRACE + ; + +classOrInterfaceType + : identifier typeArguments? (DOT identifier typeArguments?)* + ; + +typeArgument + : typeType + | annotation* QUESTION ((EXTENDS | SUPER) typeType)? + ; + +qualifiedNameList + : qualifiedName (COMMA qualifiedName)* + ; + +formalParameters + : LPAREN ( receiverParameter? + | receiverParameter (COMMA formalParameterList)? + | formalParameterList? + ) RPAREN + ; + +receiverParameter + : typeType (identifier DOT)* THIS + ; + +formalParameterList + : formalParameter (COMMA formalParameter)* (COMMA lastFormalParameter)? + | lastFormalParameter + ; + +formalParameter + : variableModifier* typeType variableDeclaratorId + ; + +lastFormalParameter + : variableModifier* typeType annotation* ELLIPSIS variableDeclaratorId + ; + +// local variable type inference +lambdaLVTIList + : lambdaLVTIParameter (COMMA lambdaLVTIParameter)* + ; + +lambdaLVTIParameter + : variableModifier* VAR identifier + ; + +qualifiedName + : identifier (DOT identifier)* + ; + +literal + : integerLiteral + | floatLiteral + | CHAR_LITERAL + | STRING_LITERAL + | BOOL_LITERAL + | NULL_LITERAL + | TEXT_BLOCK // Java17 + ; + +integerLiteral + : DECIMAL_LITERAL + | HEX_LITERAL + | OCT_LITERAL + | BINARY_LITERAL + ; + +floatLiteral + : FLOAT_LITERAL + | HEX_FLOAT_LITERAL + ; + +// ANNOTATIONS +altAnnotationQualifiedName + : (identifier DOT)* AT identifier + ; + +annotation + : (AT qualifiedName | altAnnotationQualifiedName) (LPAREN ( elementValuePairs | elementValue )? RPAREN)? + ; + +elementValuePairs + : elementValuePair (COMMA elementValuePair)* + ; + +elementValuePair + : identifier ASSIGN elementValue + ; + +elementValue + : expression + | annotation + | elementValueArrayInitializer + ; + +elementValueArrayInitializer + : LBRACE (elementValue (COMMA elementValue)*)? (COMMA)? RBRACE + ; + +annotationTypeDeclaration + : AT INTERFACE identifier annotationTypeBody + ; + +annotationTypeBody + : LBRACE (annotationTypeElementDeclaration)* RBRACE + ; + +annotationTypeElementDeclaration + : modifier* annotationTypeElementRest + | SEMI // this is not allowed by the grammar, but apparently allowed by the actual compiler + ; + +annotationTypeElementRest + : typeType annotationMethodOrConstantRest SEMI + | classDeclaration SEMI? + | interfaceDeclaration SEMI? + | enumDeclaration SEMI? + | annotationTypeDeclaration SEMI? + | recordDeclaration SEMI? // Java17 + ; + +annotationMethodOrConstantRest + : annotationMethodRest + | annotationConstantRest + ; + +annotationMethodRest + : identifier LPAREN RPAREN defaultValue? + ; + +annotationConstantRest + : variableDeclarators + ; + +defaultValue + : DEFAULT elementValue + ; + +// MODULES - Java9 + +moduleDeclaration + : OPEN? MODULE qualifiedName moduleBody + ; + +moduleBody + : LBRACE moduleDirective* RBRACE + ; + +moduleDirective + : REQUIRES requiresModifier* qualifiedName SEMI + | EXPORTS qualifiedName (TO qualifiedName)? SEMI + | OPENS qualifiedName (TO qualifiedName)? SEMI + | USES qualifiedName SEMI + | PROVIDES qualifiedName WITH qualifiedName SEMI + ; + +requiresModifier + : TRANSITIVE + | STATIC + ; + +// RECORDS - Java 17 + +recordDeclaration + : RECORD identifier typeParameters? recordHeader + (IMPLEMENTS typeList)? + recordBody + ; + +recordHeader + : LPAREN recordComponentList? RPAREN + ; + +recordComponentList + : recordComponent (COMMA recordComponent)* + ; + +recordComponent + : typeType identifier + ; + +recordBody + : LBRACE classBodyDeclaration* RBRACE + ; + +// STATEMENTS / BLOCKS + +block + : LBRACE blockStatement* RBRACE + ; + +blockStatement + : localVariableDeclaration SEMI + | statement + | localTypeDeclaration + ; + +localVariableDeclaration + : variableModifier* (typeType variableDeclarators | VAR identifier ASSIGN expression) + ; + +identifier + : IDENTIFIER + | MODULE + | OPEN + | REQUIRES + | EXPORTS + | OPENS + | TO + | USES + | PROVIDES + | WITH + | TRANSITIVE + | YIELD + | SEALED + | PERMITS + | RECORD + | VAR + ; + +localTypeDeclaration + : classOrInterfaceModifier* + (classDeclaration | interfaceDeclaration | recordDeclaration) + | SEMI + ; + +statement + : blockLabel=block + | ASSERT expression (COLON expression)? SEMI + | IF parExpression statement (ELSE statement)? + | FOR LPAREN forControl RPAREN statement + | WHILE parExpression statement + | DO statement WHILE parExpression SEMI + | TRY block (catchClause+ finallyBlock? | finallyBlock) + | TRY resourceSpecification block catchClause* finallyBlock? + | SWITCH parExpression LBRACE switchBlockStatementGroup* switchLabel* RBRACE + | SYNCHRONIZED parExpression block + | RETURN expression? SEMI + | THROW expression SEMI + | BREAK identifier? SEMI + | CONTINUE identifier? SEMI + | YIELD expression SEMI // Java17 + | SEMI + | statementExpression=expression SEMI + | switchExpression SEMI? // Java17 + | identifierLabel=identifier COLON statement + ; + +catchClause + : CATCH LPAREN variableModifier* catchType identifier RPAREN block + ; + +catchType + : qualifiedName (BITOR qualifiedName)* + ; + +finallyBlock + : FINALLY block + ; + +resourceSpecification + : LPAREN resources SEMI? RPAREN + ; + +resources + : resource (SEMI resource)* + ; + +resource + : variableModifier* ( classOrInterfaceType variableDeclaratorId | VAR identifier ) ASSIGN expression + | identifier + ; + +/** Matches cases then statements, both of which are mandatory. + * To handle empty cases at the end, we add switchLabel* to statement. + */ +switchBlockStatementGroup + : switchLabel+ blockStatement+ + ; + +switchLabel + : CASE (constantExpression=expression | enumConstantName=IDENTIFIER | typeType varName=identifier) COLON + | DEFAULT COLON + ; + +forControl + : enhancedForControl + | forInit? SEMI expression? SEMI forUpdate=expressionList? + ; + +forInit + : localVariableDeclaration + | expressionList + ; + +enhancedForControl + : variableModifier* (typeType | VAR) variableDeclaratorId COLON expression + ; + +// EXPRESSIONS + +parExpression + : LPAREN expression RPAREN + ; + +expressionList + : expression (COMMA expression)* + ; + +methodCall + : identifier LPAREN expressionList? RPAREN + | THIS LPAREN expressionList? RPAREN + | SUPER LPAREN expressionList? RPAREN + ; + +expression + : primary + | expression bop=DOT + ( + identifier + | methodCall + | THIS + | NEW nonWildcardTypeArguments? innerCreator + | SUPER superSuffix + | explicitGenericInvocation + ) + | expression LBRACK expression RBRACK + | methodCall + | NEW creator + | LPAREN annotation* typeType (BITAND typeType)* RPAREN expression + | expression postfix=(INC | DEC) + | prefix=(ADD|SUB|INC|DEC) expression + | prefix=(TILDE|BANG) expression + | expression bop=(MUL|DIV|MOD) expression + | expression bop=(ADD|SUB) expression + | expression (LT LT | GT GT GT | GT GT) expression + | expression bop=(LE | GE | GT | LT) expression + | expression bop=INSTANCEOF (typeType | pattern) + | expression bop=(EQUAL | NOTEQUAL) expression + | expression bop=BITAND expression + | expression bop=CARET expression + | expression bop=BITOR expression + | expression bop=AND expression + | expression bop=OR expression + | expression bop=QUESTION expression COLON expression + | expression + bop=(ASSIGN | ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | RSHIFT_ASSIGN | URSHIFT_ASSIGN | LSHIFT_ASSIGN | MOD_ASSIGN) + expression + | lambdaExpression // Java8 + | switchExpression // Java17 + + // Java 8 methodReference + | expression COLONCOLON typeArguments? identifier + | typeType COLONCOLON (typeArguments? identifier | NEW) + | classType COLONCOLON typeArguments? NEW + ; + +// Java17 +pattern + : variableModifier* typeType annotation* identifier + ; + +// Java8 +lambdaExpression + : lambdaParameters ARROW lambdaBody + ; + +// Java8 +lambdaParameters + : identifier + | LPAREN formalParameterList? RPAREN + | LPAREN identifier (COMMA identifier)* RPAREN + | LPAREN lambdaLVTIList? RPAREN + ; + +// Java8 +lambdaBody + : expression + | block + ; + +primary + : LPAREN expression RPAREN + | THIS + | SUPER + | literal + | identifier + | typeTypeOrVoid DOT CLASS + | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) + ; + +// Java17 +switchExpression + : SWITCH parExpression LBRACE switchLabeledRule* RBRACE + ; + +// Java17 +switchLabeledRule + : CASE (expressionList | NULL_LITERAL | guardedPattern) (ARROW | COLON) switchRuleOutcome + | DEFAULT (ARROW | COLON) switchRuleOutcome + ; + +// Java17 +guardedPattern + : LPAREN guardedPattern RPAREN + | variableModifier* typeType annotation* identifier (AND expression)* + | guardedPattern AND expression + ; + +// Java17 +switchRuleOutcome + : block + | blockStatement* + ; + +classType + : (classOrInterfaceType DOT)? annotation* identifier typeArguments? + ; + +creator + : nonWildcardTypeArguments createdName classCreatorRest + | createdName (arrayCreatorRest | classCreatorRest) + ; + +createdName + : identifier typeArgumentsOrDiamond? (DOT identifier typeArgumentsOrDiamond?)* + | primitiveType + ; + +innerCreator + : identifier nonWildcardTypeArgumentsOrDiamond? classCreatorRest + ; + +arrayCreatorRest + : LBRACK (RBRACK (LBRACK RBRACK)* arrayInitializer | expression RBRACK (LBRACK expression RBRACK)* (LBRACK RBRACK)*) + ; + +classCreatorRest + : arguments classBody? + ; + +explicitGenericInvocation + : nonWildcardTypeArguments explicitGenericInvocationSuffix + ; + +typeArgumentsOrDiamond + : LT GT + | typeArguments + ; + +nonWildcardTypeArgumentsOrDiamond + : LT GT + | nonWildcardTypeArguments + ; + +nonWildcardTypeArguments + : LT typeList GT + ; + +typeList + : typeType (COMMA typeType)* + ; + +typeType + : annotation* (classOrInterfaceType | primitiveType) (annotation* LBRACK RBRACK)* + ; + +primitiveType + : BOOLEAN + | CHAR + | BYTE + | SHORT + | INT + | LONG + | FLOAT + | DOUBLE + ; + +typeArguments + : LT typeArgument (COMMA typeArgument)* GT + ; + +superSuffix + : arguments + | DOT typeArguments? identifier arguments? + ; + +explicitGenericInvocationSuffix + : SUPER superSuffix + | identifier arguments + ; + +arguments + : LPAREN expressionList? RPAREN + ; \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index f1c254fa332..6c39a733235 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -3,11 +3,8 @@ import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; -import org.antlr.v4.runtime.ParserRuleContext; -import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; -import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.PackageDescr; public class DRLParserHelper { @@ -17,7 +14,7 @@ public static PackageDescr parse(String drl) { } public static ParseTree createParseTree(String drl) { - return createDrlParser(drl).compilationunit(); + return createDrlParser(drl).compilationUnit(); } public static DRLParser createDrlParser(String drl) { @@ -34,90 +31,19 @@ public static PackageDescr parseTree2PackageDescr(ParseTree parseTree) { return visitor.getPackageDescr(); } - public static ParseTree findNodeAtPosition(ParseTree root, int row, int col) { - ParseTree lastChild = null; - for (int i = 0; i < root.getChildCount(); i++) { - ParseTree child = root.getChild(i); - if (i > 0 && startsAfter(child, row, col)) { - return findNodeAtPosition(lastChild, row, col); - } - - if (endsAfter(child, row, col)) { - return findNodeAtPosition(child, row, col); - } - - lastChild = child; - } - return root; - } - - public static Token getStartToken(ParseTree child) { - return child instanceof TerminalNode ? ((TerminalNode) child).getSymbol() : ((ParserRuleContext) child).getStart(); - } - - public static Token getStopToken(ParseTree child) { - return child instanceof TerminalNode ? ((TerminalNode) child).getSymbol() : ((ParserRuleContext) child).getStop(); - } - - private static boolean endsBefore(ParseTree node, int row, int col) { - Token token = getStopToken(node); - if (token.getLine() != row) { - return token.getLine() < row; - } - int tokenLength = (token.getStopIndex() - token.getStartIndex()) + 1; - int lastTokenPosition = token.getCharPositionInLine() + tokenLength; - return lastTokenPosition < col; - } - - private static boolean endsAfter(ParseTree node, int row, int col) { - Token token = getStopToken(node); - if (token.getLine() != row) { - return token.getLine() > row; - } - int tokenLength = (token.getStopIndex() - token.getStartIndex()) + 1; - int lastTokenPosition = token.getCharPositionInLine() + tokenLength; - return lastTokenPosition >= col; - } - - private static boolean startsAfter(ParseTree node, int row, int col) { - Token token = getStartToken(node); - if (token.getLine() != row) { - return token.getLine() > row; - } - return token.getCharPositionInLine() > col; - } - - public static boolean hasParentOfType(ParseTree leaf, int type) { - return findParentOfType(leaf, type) != null; - } - - public static ParseTree findParentOfType(ParseTree leaf, int type) { - if (leaf == null || (leaf instanceof RuleContext && ((RuleContext) leaf).getRuleIndex() == type)) { - return leaf; - } - return findParentOfType(leaf.getParent(), type); - } - - public static int symbolType(ParseTree node) { - if (node instanceof TerminalNode) { - return ((TerminalNode) node).getSymbol().getType(); - } - return -1; - } - - public static boolean isSymbol(ParseTree node, int symbol) { - return symbolType(node) == symbol; - } - - public static boolean isAfterSymbol(ParseTree node, int symbol, int row, int col) { - return isSymbol(node, symbol) && endsBefore(node, row, col); - } - - public static int getNodeIndex(ParseTree node) { - if (node instanceof TerminalNode) { - return ((TerminalNode) node).getSymbol().getTokenIndex(); + public static Integer computeTokenIndex(DRLParser parser, int row, int col) { + for (int i = 0; i < parser.getInputStream().size(); i++) { + Token token = parser.getInputStream().get(i); + int start = token.getCharPositionInLine(); + int stop = token.getCharPositionInLine() + token.getText().length(); + if (token.getLine() > row) + return token.getTokenIndex() - 1; + else if (token.getLine() == row && start >= col) + return token.getTokenIndex() == 0 ? 0 : token.getTokenIndex() - 1; + else if (token.getLine() == row && start < col && stop >= col) + return token.getTokenIndex(); } - return node.getChildCount() == 0 ? 0: getNodeIndex(node.getChild(0)); + return null; } } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 9aa2fbce870..459fcf291dc 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -1,23 +1,16 @@ package org.drools.parser; -import org.drools.drl.ast.descr.AnnotationDescr; -import org.drools.drl.ast.descr.AttributeDescr; -import org.drools.drl.ast.descr.GlobalDescr; -import org.drools.drl.ast.descr.ImportDescr; -import org.drools.drl.ast.descr.PackageDescr; -import org.drools.drl.ast.descr.PatternDescr; -import org.drools.drl.ast.descr.RuleDescr; -import org.drools.drl.ast.descr.UnitDescr; +import org.drools.drl.ast.descr.*; -public class DRLVisitorImpl extends DRLBaseVisitor { +public class DRLVisitorImpl extends DRLParserBaseVisitor { private final PackageDescr packageDescr = new PackageDescr(); private RuleDescr ruleDescr; @Override - public Object visitCompilationunit(DRLParser.CompilationunitContext ctx) { - return super.visitCompilationunit(ctx); + public Object visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { + return super.visitCompilationUnit(ctx); } @Override @@ -34,13 +27,13 @@ public Object visitUnitdef(DRLParser.UnitdefContext ctx) { @Override public Object visitGlobaldef(DRLParser.GlobaldefContext ctx) { - packageDescr.addGlobal(new GlobalDescr(ctx.ID().getText(), ctx.type().getText())); + packageDescr.addGlobal(new GlobalDescr(ctx.IDENTIFIER().getText(), ctx.type().getText())); return super.visitGlobaldef(ctx); } @Override public Object visitImportdef(DRLParser.ImportdefContext ctx) { - String imp = ctx.qualifiedIdentifier().getText() + (ctx.STAR() != null ? ".*" : ""); + String imp = ctx.qualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); packageDescr.addImport(new ImportDescr(imp)); return super.visitImportdef(ctx); } @@ -58,10 +51,10 @@ public Object visitRuledef(DRLParser.RuledefContext ctx) { @Override public Object visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { - if ( ctx.lhsPattern().size() == 1 ) { + if (ctx.lhsPattern().size() == 1) { PatternDescr patternDescr = new PatternDescr(ctx.lhsPattern(0).objectType.getText()); if (ctx.label() != null) { - patternDescr.setIdentifier(ctx.label().ID().getText()); + patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); } ruleDescr.getLhs().addDescr(patternDescr); } @@ -69,18 +62,18 @@ public Object visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { } @Override - public Object visitAnnotation(DRLParser.AnnotationContext ctx) { + public Object visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); - annotationDescr.setValue(ctx.arguments().argument(0).getText()); + annotationDescr.setValue(ctx.drlArguments().drlArgument(0).getText()); ruleDescr.addAnnotation(annotationDescr); - return super.visitAnnotation(ctx); + return super.visitDrlAnnotation(ctx); } @Override public Object visitAttribute(DRLParser.AttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr( ctx.getChild(0).getText() ); + AttributeDescr attributeDescr = new AttributeDescr(ctx.getChild(0).getText()); if (ctx.getChildCount() > 1) { - attributeDescr.setValue( ctx.getChild(1).getText() ); + attributeDescr.setValue(ctx.getChild(1).getText()); } ruleDescr.addAttribute(attributeDescr); return super.visitAttribute(ctx); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java index 5d8bd5b42dd..f51710e1b87 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java @@ -1,24 +1,11 @@ package org.drools.parser; -import org.antlr.v4.runtime.RuleContext; -import org.antlr.v4.runtime.tree.ParseTree; -import org.drools.drl.ast.descr.AnnotationDescr; -import org.drools.drl.ast.descr.AttributeDescr; -import org.drools.drl.ast.descr.BaseDescr; -import org.drools.drl.ast.descr.GlobalDescr; -import org.drools.drl.ast.descr.PackageDescr; -import org.drools.drl.ast.descr.PatternDescr; -import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.*; import org.junit.Test; -import static org.drools.parser.DRLParserHelper.createParseTree; -import static org.drools.parser.DRLParserHelper.findNodeAtPosition; -import static org.drools.parser.DRLParserHelper.findParentOfType; -import static org.drools.parser.DRLParserHelper.isAfterSymbol; -import static org.drools.parser.DRLParserHelper.parse; +import static org.drools.parser.DRLParserHelper.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; public class DRLParserTest { @@ -29,6 +16,7 @@ public class DRLParserTest { "rule TestRule @Test(true) no-loop salience 15 when \n" + " $p:Person()\n" + "then\n" + + " int a = 4;\n" + " System.out.println($p.getName());\n" + "end\n"; @@ -52,37 +40,46 @@ public void testParse() { assertNotNull(annotationDescr); assertEquals("true", annotationDescr.getValue()); - assertEquals( 2, ruleDescr.getAttributes().size() ); - assertNotNull( ruleDescr.getAttributes().get("no-loop") ); + assertEquals(2, ruleDescr.getAttributes().size()); + assertNotNull(ruleDescr.getAttributes().get("no-loop")); AttributeDescr salience = ruleDescr.getAttributes().get("salience"); - assertNotNull( salience ); - assertEquals( "15", salience.getValue() ); + assertNotNull(salience); + assertEquals("15", salience.getValue()); assertEquals("TestRule", ruleDescr.getName()); - assertEquals( 1, ruleDescr.getLhs().getDescrs().size() ); + assertEquals(1, ruleDescr.getLhs().getDescrs().size()); PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); assertEquals("$p", patternDescr.getIdentifier()); assertEquals("Person", patternDescr.getObjectType()); - assertEquals("System.out.println($p.getName());", ruleDescr.getConsequence()); + assertEquals("inta=4;System.out.println($p.getName());", ruleDescr.getConsequence()); } @Test - public void testCursorPosition() { - ParseTree parseTree = createParseTree(drl); - ParseTree node = findNodeAtPosition(parseTree, 5, 7); - assertEquals("Person", node.getText()); - ParseTree lhs = findParentOfType(node, DRLParser.RULE_lhs); - assertEquals(DRLParser.RULE_lhs, ((RuleContext) lhs).getRuleIndex()); - assertEquals("$p:Person()", lhs.getText()); - } + public void testComputeTokenIndex() { + DRLParser parser = createDrlParser(drl); + parser.compilationUnit(); - @Test - public void testCursorPosition2() { - ParseTree parseTree = createParseTree(drl); - ParseTree node = findNodeAtPosition(parseTree, 4, 51); - assertEquals("when", node.getText()); - assertTrue(isAfterSymbol(node, DRLParser.WHEN, 4, 51)); + assertEquals(0, (int) computeTokenIndex(parser, 1, 0)); + assertEquals(0, (int) computeTokenIndex(parser, 1, 1)); + assertEquals(0, (int) computeTokenIndex(parser, 1, 7)); + assertEquals(1, (int) computeTokenIndex(parser, 1, 8)); + assertEquals(2, (int) computeTokenIndex(parser, 1, 9)); + assertEquals(2, (int) computeTokenIndex(parser, 1, 9)); + assertEquals(3, (int) computeTokenIndex(parser, 1, 12)); + assertEquals(4, (int) computeTokenIndex(parser, 1, 13)); + assertEquals(5, (int) computeTokenIndex(parser, 1, 17)); + assertEquals(6, (int) computeTokenIndex(parser, 1, 18)); + assertEquals(6, (int) computeTokenIndex(parser, 2, 0)); + assertEquals(7, (int) computeTokenIndex(parser, 2, 1)); + assertEquals(7, (int) computeTokenIndex(parser, 2, 6)); + assertEquals(8, (int) computeTokenIndex(parser, 2, 7)); + assertEquals(73, (int) computeTokenIndex(parser, 9, 0)); + assertEquals(74, (int) computeTokenIndex(parser, 9, 1)); + assertEquals(75, (int) computeTokenIndex(parser, 9, 4)); + assertEquals(75, (int) computeTokenIndex(parser, 9, 5)); + assertEquals(75, (int) computeTokenIndex(parser, 10, 0)); // EOF } + } From 7556debab77034827de8334a5736c3889267dc00 Mon Sep 17 00:00:00 2001 From: mariofusco Date: Fri, 22 Apr 2022 16:45:42 +0200 Subject: [PATCH 014/141] add constraints parsing --- .../org/drools/parser/DRLVisitorImpl.java | 67 ++++++++++++++++--- .../java/org/drools/parser/DRLParserTest.java | 19 ++++-- 2 files changed, 69 insertions(+), 17 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 459fcf291dc..4c816406889 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -1,12 +1,18 @@ package org.drools.parser; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.*; public class DRLVisitorImpl extends DRLParserBaseVisitor { private final PackageDescr packageDescr = new PackageDescr(); - private RuleDescr ruleDescr; + private RuleDescr currentRule; + private PatternDescr currentPattern; @Override public Object visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { @@ -40,32 +46,71 @@ public Object visitImportdef(DRLParser.ImportdefContext ctx) { @Override public Object visitRuledef(DRLParser.RuledefContext ctx) { - ruleDescr = new RuleDescr(ctx.name.getText()); - ruleDescr.setConsequence(ctx.rhs().getText()); - packageDescr.addRule(ruleDescr); + currentRule = new RuleDescr(ctx.name.getText()); + currentRule.setConsequence(ctx.rhs().getText()); + packageDescr.addRule(currentRule); Object result = super.visitRuledef(ctx); - ruleDescr = null; + currentRule = null; return result; } @Override public Object visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { if (ctx.lhsPattern().size() == 1) { - PatternDescr patternDescr = new PatternDescr(ctx.lhsPattern(0).objectType.getText()); + currentPattern = new PatternDescr(ctx.lhsPattern(0).objectType.getText()); if (ctx.label() != null) { - patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); + currentPattern.setIdentifier(ctx.label().IDENTIFIER().getText()); + } + currentRule.getLhs().addDescr(currentPattern); + } + Object result = super.visitLhsPatternBind(ctx); + currentPattern = null; + return result; + } + + @Override + public Object visitConstraint(DRLParser.ConstraintContext ctx) { + Object constraint = super.visitConstraint(ctx); + ExprConstraintDescr constr = new ExprConstraintDescr( constraint.toString() ); + constr.setType( ExprConstraintDescr.Type.NAMED ); + currentPattern.addConstraint( constr ); + return null; + } + + @Override + public Object visitExpression(DRLParser.ExpressionContext ctx) { + return ctx.children.stream() + .map(c -> c instanceof TerminalNode ? c : c.accept(this)) + .filter(Objects::nonNull) + .map(Object::toString) + .collect(Collectors.joining(" ")); + } + + @Override + public Object visitIdentifier(DRLParser.IdentifierContext ctx) { + return ctx.IDENTIFIER().getText(); + } + + @Override + public Object visitLiteral(DRLParser.LiteralContext ctx) { + ParseTree node = ctx; + while (true) { + if (node instanceof TerminalNode) { + return node.toString(); + } + if (node.getChildCount() != 1) { + return super.visitLiteral(ctx); } - ruleDescr.getLhs().addDescr(patternDescr); + node = node.getChild(0); } - return super.visitLhsPatternBind(ctx); } @Override public Object visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); annotationDescr.setValue(ctx.drlArguments().drlArgument(0).getText()); - ruleDescr.addAnnotation(annotationDescr); + currentRule.addAnnotation(annotationDescr); return super.visitDrlAnnotation(ctx); } @@ -75,7 +120,7 @@ public Object visitAttribute(DRLParser.AttributeContext ctx) { if (ctx.getChildCount() > 1) { attributeDescr.setValue(ctx.getChild(1).getText()); } - ruleDescr.addAttribute(attributeDescr); + currentRule.addAttribute(attributeDescr); return super.visitAttribute(ctx); } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java index f51710e1b87..4e8abc50b0c 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java @@ -1,5 +1,7 @@ package org.drools.parser; +import java.util.List; + import org.drools.drl.ast.descr.*; import org.junit.Test; @@ -14,7 +16,7 @@ public class DRLParserTest { "import org.test.model.Person;\n" + "global String result;\n" + "rule TestRule @Test(true) no-loop salience 15 when \n" + - " $p:Person()\n" + + " $p:Person( age >= 18 )\n" + "then\n" + " int a = 4;\n" + " System.out.println($p.getName());\n" + @@ -53,6 +55,11 @@ public void testParse() { assertEquals("$p", patternDescr.getIdentifier()); assertEquals("Person", patternDescr.getObjectType()); + List constraints = patternDescr.getConstraint().getDescrs(); + assertEquals(1, constraints.size()); + ExprConstraintDescr expr = (ExprConstraintDescr) constraints.get(0); + assertEquals("age >= 18", expr.getExpression()); + assertEquals("inta=4;System.out.println($p.getName());", ruleDescr.getConsequence()); } @@ -75,11 +82,11 @@ public void testComputeTokenIndex() { assertEquals(7, (int) computeTokenIndex(parser, 2, 1)); assertEquals(7, (int) computeTokenIndex(parser, 2, 6)); assertEquals(8, (int) computeTokenIndex(parser, 2, 7)); - assertEquals(73, (int) computeTokenIndex(parser, 9, 0)); - assertEquals(74, (int) computeTokenIndex(parser, 9, 1)); - assertEquals(75, (int) computeTokenIndex(parser, 9, 4)); - assertEquals(75, (int) computeTokenIndex(parser, 9, 5)); - assertEquals(75, (int) computeTokenIndex(parser, 10, 0)); // EOF + assertEquals(80, (int) computeTokenIndex(parser, 9, 0)); + assertEquals(81, (int) computeTokenIndex(parser, 9, 1)); + assertEquals(82, (int) computeTokenIndex(parser, 9, 4)); + assertEquals(82, (int) computeTokenIndex(parser, 9, 5)); + assertEquals(82, (int) computeTokenIndex(parser, 10, 0)); // EOF } } From 919cb1ae69c8511449be3afe24a2085d8ec4f425 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 27 Apr 2022 16:40:16 +0900 Subject: [PATCH 015/141] - Added DRLParserWrapper to store errors using DRLErrorListener (#5) - Added MiscDRLParserTest which is being ported from RuleParserTest to enhance coverage. --- drools-drl/drools-drl10-parser/pom.xml | 6 +++ .../org/drools/parser/DRLErrorListener.java | 28 ++++++++++ .../org/drools/parser/DRLParserError.java | 54 +++++++++++++++++++ .../org/drools/parser/DRLParserWrapper.java | 45 ++++++++++++++++ .../org/drools/parser/MiscDRLParserTest.java | 51 ++++++++++++++++++ .../src/test/resources/logback-test.xml | 16 ++++++ 6 files changed, 200 insertions(+) create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java create mode 100644 drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/logback-test.xml diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml index 2b88baa153b..599ec8ab07f 100644 --- a/drools-drl/drools-drl10-parser/pom.xml +++ b/drools-drl/drools-drl10-parser/pom.xml @@ -47,6 +47,12 @@ ${version.junit} test + + ch.qos.logback + logback-classic + ${version.ch.qos.logback} + test + diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java new file mode 100644 index 00000000000..a15d12adddb --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java @@ -0,0 +1,28 @@ +package org.drools.parser; + +import java.util.ArrayList; +import java.util.List; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; + +public class DRLErrorListener extends BaseErrorListener { + + private final List errors = new ArrayList<>(); + + public List getErrors() { + return errors; + } + + @Override + public void syntaxError(Recognizer recognizer, + Object offendingSymbol, + int line, + int charPositionInLine, + String msg, + RecognitionException e) { + + errors.add(new DRLParserError(line, charPositionInLine, msg)); + } +} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java new file mode 100644 index 00000000000..6b9fe116943 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java @@ -0,0 +1,54 @@ +package org.drools.parser; + +public class DRLParserError { + + private int lineNumber; + private int column; + private String message; + + private Exception exception; + + public DRLParserError(int lineNumber, int column, String message) { + this.lineNumber = lineNumber; + this.column = column; + this.message = message; + } + + public DRLParserError(Exception exception) { + this.exception = exception; + } + + public int getLineNumber() { + return lineNumber; + } + + public void setLineNumber(int lineNumber) { + this.lineNumber = lineNumber; + } + + public int getColumn() { + return column; + } + + public void setColumn(int column) { + this.column = column; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return "DRLParserError{" + + "lineNumber=" + lineNumber + + ", column=" + column + + ", message='" + message + '\'' + + ", exception=" + exception + + '}'; + } +} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java new file mode 100644 index 00000000000..4b948cffca5 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java @@ -0,0 +1,45 @@ +package org.drools.parser; + +import java.util.ArrayList; +import java.util.List; + +import org.antlr.v4.runtime.tree.ParseTree; +import org.drools.drl.ast.descr.PackageDescr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DRLParserWrapper { + + private static final Logger LOGGER = LoggerFactory.getLogger(DRLParserWrapper.class); + + private final List errors = new ArrayList<>(); + + public DRLParserWrapper() { + } + + public PackageDescr parse(String drl) { + DRLParser drlParser = DRLParserHelper.createDrlParser(drl); + DRLErrorListener errorListener = new DRLErrorListener(); + drlParser.addErrorListener(errorListener); + + ParseTree parseTree = drlParser.compilationUnit(); + + errors.addAll(errorListener.getErrors()); + + try { + return DRLParserHelper.parseTree2PackageDescr(parseTree); + } catch (Exception e) { + LOGGER.error("Exception while creating PackageDescr", e); + errors.add(new DRLParserError(e)); + return null; + } + } + + public List getErrors() { + return errors; + } + + public boolean hasErrors() { + return !errors.isEmpty(); + } +} diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java new file mode 100644 index 00000000000..9a6b31f2b7f --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -0,0 +1,51 @@ +package org.drools.parser; + +import junit.framework.TestCase; +import org.drools.drl.ast.descr.PackageDescr; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/* + * This test class is being ported from org.drools.mvel.compiler.lang.RuleParserTest + */ +public class MiscDRLParserTest extends TestCase { + + private DRLParserWrapper parser; + + @Before + protected void setUp() throws Exception { + super.setUp(); + parser = new DRLParserWrapper(); + } + + @After + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testPackage() throws Exception { + final String source = "package foo.bar.baz"; + final PackageDescr pkg = parser.parse(source); + assertEquals("foo.bar.baz", pkg.getName()); + } + + @Test + public void testPackageWithErrorNode() throws Exception { + final String source = "package 12 foo.bar.baz"; + final PackageDescr pkg = parser.parse(source); + assertTrue(parser.hasErrors()); + // getText() combines an ErrorNode "12" so the result is different from DRL6Parser. + assertEquals("12foo.bar.baz", pkg.getName()); + } + + @Test + public void testPackageWithAllErrorNode() throws Exception { + final String source = "package 12 12312 231"; + final PackageDescr pkg = parser.parse(source); + assertTrue(parser.hasErrors()); + // NPE inside DRLVisitorImpl.visitIdentifier(). So pkg is null. Different from DRL6Parser. + assertNull(pkg); + } +} diff --git a/drools-drl/drools-drl10-parser/src/test/resources/logback-test.xml b/drools-drl/drools-drl10-parser/src/test/resources/logback-test.xml new file mode 100644 index 00000000000..7740901e7d3 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/logback-test.xml @@ -0,0 +1,16 @@ + + + + + + %date{HH:mm:ss.SSS} [%thread] %-5level %class{36}.%method:%line - %msg%n + + + + + + + + + + \ No newline at end of file From a6cc3aadf958fa3ca8a192cdcc6d490b9474e624 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 11 May 2022 00:41:17 +0900 Subject: [PATCH 016/141] Enhance test/grammar coverage. function import, global, exists, not (#6) --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 2 + .../antlr4/org/drools/parser/DRLParser.g4 | 38 ++- .../org/drools/parser/DRLParserHelper.java | 26 ++ .../org/drools/parser/DRLParserWrapper.java | 5 + .../org/drools/parser/DRLVisitorImpl.java | 97 ++++++- .../java/org/drools/parser/StringUtils.java | 20 ++ .../org/drools/parser/MiscDRLParserTest.java | 237 +++++++++++++++++- .../resources/org/drools/parser/globals.drl | 28 +++ .../org/drools/parser/test_FunctionImport.drl | 27 ++ 9 files changed, 462 insertions(+), 18 deletions(-) create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/StringUtils.java create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/globals.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_FunctionImport.drl diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 732a0d3bcc9..0f4ee3cc48f 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -32,8 +32,10 @@ WHEN : 'when'; THEN : 'then'; END : 'end'; +EXISTS : 'exists'; NOT : 'not'; IN : 'in'; +FROM : 'from'; SALIENCE : 'salience'; ENABLED : 'enabled'; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 31bf8c80eed..2818590bd59 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -33,7 +33,11 @@ lhsUnary : ( lhsExists namedConsequence? ) SEMI? ; */ -lhsUnary : lhsPatternBind ; +lhsUnary : ( + lhsExists + | lhsNot + | lhsPatternBind + ) ; lhsPatternBind : label? ( LPAREN lhsPattern (OR lhsPattern)* RPAREN | lhsPattern ) ; /* @@ -41,7 +45,7 @@ lhsPattern : xpathPrimary (OVER patternFilter)? | ( QUESTION? qualifiedIdentifier LPAREN positionalConstraints? constraints? RPAREN (OVER patternFilter)? (FROM patternSource)? ) ; */ -lhsPattern : QUESTION? objectType=qualifiedName LPAREN positionalConstraints? constraints? RPAREN ; +lhsPattern : QUESTION? objectType=qualifiedName LPAREN (positionalConstraints? constraints? ) RPAREN (FROM patternSource)? ; positionalConstraints : constraint (COMMA constraint)* SEMI ; constraints : constraint (COMMA constraint)* ; constraint : label? ( nestedConstraint | conditionalOrExpression ) ; @@ -60,6 +64,34 @@ drlExpression : conditionalExpression ( op=assignmentOperator right=drlExpressio conditionalExpression : left=conditionalOrExpression ternaryExpression? ; ternaryExpression : QUESTION ts=drlExpression COLON fs=drlExpression ; +/* + patternSource := FROM + ( fromAccumulate + | fromCollect + | fromEntryPoint + | fromWindow + | fromExpression ) +*/ +patternSource : fromExpression ; +fromExpression : conditionalOrExpression ; + +/* + lhsExists := EXISTS + ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or + | LEFT_PAREN lhsOr RIGHT_PAREN + | lhsPatternBind + ) +*/ +lhsExists : EXISTS lhsPatternBind ; +/* + lhsNot := NOT + ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or + | LEFT_PAREN lhsOr RIGHT_PAREN + | lhsPatternBind + ) +*/ +lhsNot : NOT lhsPatternBind ; + rhs : blockStatement+ ; stringId : ( IDENTIFIER | STRING_LITERAL ) ; @@ -76,7 +108,7 @@ drlAnnotation : AT name=qualifiedName drlArguments? ; attributes : attribute ( COMMA? attribute )* ; attribute : ( 'salience' DECIMAL_LITERAL ) - | ( 'enabled' | 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOLEAN? + | ( 'enabled' | 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOL_LITERAL? | ( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) STRING_LITERAL | 'calendars' STRING_LITERAL ( COMMA STRING_LITERAL )* | 'timer' ( DECIMAL_LITERAL | TEXT ) diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index 6c39a733235..feabbe39207 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -3,8 +3,11 @@ import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.PackageDescr; public class DRLParserHelper { @@ -46,4 +49,27 @@ else if (token.getLine() == row && start < col && stop >= col) } return null; } + + /** + * RuleContext.getText() connects all nodes including ErrorNode. This method appends texts only from valid nodes + */ + public static String getTextWithoutErrorNode(ParseTree tree) { + if (tree.getChildCount() == 0) { + return ""; + } + + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < tree.getChildCount(); i++) { + ParseTree child = tree.getChild(i); + if (!(child instanceof ErrorNode)) { + if (child instanceof TerminalNode) { + builder.append(child.getText()); + } else { + builder.append(getTextWithoutErrorNode(child)); + } + } + } + + return builder.toString(); + } } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java index 4b948cffca5..251c918190a 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; import org.antlr.v4.runtime.tree.ParseTree; import org.drools.drl.ast.descr.PackageDescr; @@ -39,6 +40,10 @@ public List getErrors() { return errors; } + public List getErrorMessages() { + return errors.stream().map(DRLParserError::getMessage).collect(Collectors.toList()); + } + public boolean hasErrors() { return !errors.isEmpty(); } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 4c816406889..d93c707abe7 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -1,18 +1,25 @@ package org.drools.parser; +import java.util.ArrayDeque; +import java.util.Deque; import java.util.Objects; import java.util.stream.Collectors; +import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.*; +import static org.drools.parser.DRLParserHelper.getTextWithoutErrorNode; +import static org.drools.parser.StringUtils.safeStripStringDelimiters; + public class DRLVisitorImpl extends DRLParserBaseVisitor { private final PackageDescr packageDescr = new PackageDescr(); private RuleDescr currentRule; private PatternDescr currentPattern; + private Deque currentConstructStack = new ArrayDeque<>(); // e.g. whole LHS, not, exist @Override public Object visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { @@ -21,7 +28,7 @@ public Object visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { @Override public Object visitPackagedef(DRLParser.PackagedefContext ctx) { - packageDescr.setName(ctx.name.getText()); + packageDescr.setName(getTextWithoutErrorNode(ctx.name)); return super.visitPackagedef(ctx); } @@ -33,20 +40,32 @@ public Object visitUnitdef(DRLParser.UnitdefContext ctx) { @Override public Object visitGlobaldef(DRLParser.GlobaldefContext ctx) { - packageDescr.addGlobal(new GlobalDescr(ctx.IDENTIFIER().getText(), ctx.type().getText())); + GlobalDescr globalDescr = new GlobalDescr(ctx.IDENTIFIER().getText(), ctx.type().getText()); + populateStartEnd(globalDescr, ctx); + packageDescr.addGlobal(globalDescr); return super.visitGlobaldef(ctx); } @Override public Object visitImportdef(DRLParser.ImportdefContext ctx) { - String imp = ctx.qualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); - packageDescr.addImport(new ImportDescr(imp)); + String target = ctx.qualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); + if (ctx.FUNCTION() != null || ctx.STATIC() != null) { + FunctionImportDescr functionImportDescr = new FunctionImportDescr(); + functionImportDescr.setTarget(target); + populateStartEnd(functionImportDescr, ctx); + packageDescr.addFunctionImport(functionImportDescr); + } else { + ImportDescr importDescr = new ImportDescr(); + importDescr.setTarget(target); + populateStartEnd(importDescr, ctx); + packageDescr.addImport(importDescr); + } return super.visitImportdef(ctx); } @Override public Object visitRuledef(DRLParser.RuledefContext ctx) { - currentRule = new RuleDescr(ctx.name.getText()); + currentRule = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); currentRule.setConsequence(ctx.rhs().getText()); packageDescr.addRule(currentRule); @@ -55,14 +74,33 @@ public Object visitRuledef(DRLParser.RuledefContext ctx) { return result; } + @Override + public Object visitLhs(DRLParser.LhsContext ctx) { + currentConstructStack.push(currentRule.getLhs()); + try { + return super.visitLhs(ctx); + } finally { + currentConstructStack.pop(); + } + } + @Override public Object visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { + // TODO: this logic will likely be split to visitLhsPattern if (ctx.lhsPattern().size() == 1) { - currentPattern = new PatternDescr(ctx.lhsPattern(0).objectType.getText()); + DRLParser.LhsPatternContext lhsPatternCtx = ctx.lhsPattern(0); + currentPattern = new PatternDescr(lhsPatternCtx.objectType.getText()); if (ctx.label() != null) { currentPattern.setIdentifier(ctx.label().IDENTIFIER().getText()); } - currentRule.getLhs().addDescr(currentPattern); + if (lhsPatternCtx.patternSource() != null) { + String expression = lhsPatternCtx.patternSource().getText(); + FromDescr from = new FromDescr(); + from.setDataSource(new MVELExprDescr(expression)); + from.setResource(currentPattern.getResource()); + currentPattern.setSource(from); + } + currentConstructStack.peek().addDescr(currentPattern); } Object result = super.visitLhsPatternBind(ctx); currentPattern = null; @@ -72,9 +110,11 @@ public Object visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { @Override public Object visitConstraint(DRLParser.ConstraintContext ctx) { Object constraint = super.visitConstraint(ctx); - ExprConstraintDescr constr = new ExprConstraintDescr( constraint.toString() ); - constr.setType( ExprConstraintDescr.Type.NAMED ); - currentPattern.addConstraint( constr ); + if (constraint != null) { + ExprConstraintDescr constr = new ExprConstraintDescr(constraint.toString()); + constr.setType(ExprConstraintDescr.Type.NAMED); + currentPattern.addConstraint(constr); + } return null; } @@ -89,7 +129,11 @@ public Object visitExpression(DRLParser.ExpressionContext ctx) { @Override public Object visitIdentifier(DRLParser.IdentifierContext ctx) { - return ctx.IDENTIFIER().getText(); + if (ctx.IDENTIFIER() == null) { + return ""; + } else { + return ctx.IDENTIFIER().getText(); + } } @Override @@ -124,7 +168,38 @@ public Object visitAttribute(DRLParser.AttributeContext ctx) { return super.visitAttribute(ctx); } + @Override + public Object visitLhsExists(DRLParser.LhsExistsContext ctx) { + ExistsDescr existsDescr = new ExistsDescr(); + currentConstructStack.peek().addDescr(existsDescr); + currentConstructStack.push(existsDescr); + try { + return super.visitLhsExists(ctx); + } finally { + currentConstructStack.pop(); + } + } + + @Override + public Object visitLhsNot(DRLParser.LhsNotContext ctx) { + NotDescr notDescr = new NotDescr(); + currentConstructStack.peek().addDescr(notDescr); + currentConstructStack.push(notDescr); + try { + return super.visitLhsNot(ctx); + } finally { + currentConstructStack.pop(); + } + } + public PackageDescr getPackageDescr() { return packageDescr; } + + private void populateStartEnd(BaseDescr descr, ParserRuleContext ctx) { + descr.setStartCharacter(ctx.getStart().getStartIndex()); + // TODO: Current DRL6Parser adds +1 for EndCharacter but it doesn't look reasonable. At the moment, I don't add. Instead, I fix unit tests. + // I will revisit if this is the right approach. + descr.setEndCharacter(ctx.getStop().getStopIndex()); + } } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/StringUtils.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/StringUtils.java new file mode 100644 index 00000000000..22f8adf4c8a --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/StringUtils.java @@ -0,0 +1,20 @@ +package org.drools.parser; + +/** + * will be merged in drools-util + */ +public class StringUtils { + + private StringUtils() { + } + + public static String safeStripStringDelimiters(String value) { + if (value != null) { + value = value.trim(); + if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { + value = value.substring(1, value.length() - 1); + } + } + return value; + } +} diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 9a6b31f2b7f..caabed15927 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -1,7 +1,23 @@ package org.drools.parser; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + import junit.framework.TestCase; +import org.drools.drl.ast.descr.FromDescr; +import org.drools.drl.ast.descr.FunctionImportDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.ImportDescr; +import org.drools.drl.ast.descr.NotDescr; import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.RuleDescr; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -24,6 +40,19 @@ protected void tearDown() throws Exception { super.tearDown(); } + private PackageDescr parseResource(final String filename) throws Exception { + Path path = Paths.get(getClass().getResource(filename).toURI()); + final StringBuilder sb = new StringBuilder(); + try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { + for (String line; (line = br.readLine()) != null; ) { + sb.append(line + "\n"); + } + } catch (IOException e) { + e.printStackTrace(); + } + return parser.parse(sb.toString()); + } + @Test public void testPackage() throws Exception { final String source = "package foo.bar.baz"; @@ -36,8 +65,7 @@ public void testPackageWithErrorNode() throws Exception { final String source = "package 12 foo.bar.baz"; final PackageDescr pkg = parser.parse(source); assertTrue(parser.hasErrors()); - // getText() combines an ErrorNode "12" so the result is different from DRL6Parser. - assertEquals("12foo.bar.baz", pkg.getName()); + assertEquals("foo.bar.baz", pkg.getName()); } @Test @@ -45,7 +73,208 @@ public void testPackageWithAllErrorNode() throws Exception { final String source = "package 12 12312 231"; final PackageDescr pkg = parser.parse(source); assertTrue(parser.hasErrors()); - // NPE inside DRLVisitorImpl.visitIdentifier(). So pkg is null. Different from DRL6Parser. - assertNull(pkg); + assertEquals("", pkg.getName()); + } + + @Test + public void testCompilationUnit() throws Exception { + final String source = "package foo; import com.foo.Bar; import com.foo.Baz;"; + PackageDescr pkg = parser.parse(source); + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + assertEquals("foo", + pkg.getName()); + assertEquals(2, + pkg.getImports().size()); + ImportDescr impdescr = pkg.getImports().get(0); + assertEquals("com.foo.Bar", + impdescr.getTarget()); + assertEquals(source.indexOf("import " + impdescr.getTarget()), + impdescr.getStartCharacter()); + assertEquals(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length(), + impdescr.getEndCharacter()); + + impdescr = pkg.getImports().get(1); + assertEquals("com.foo.Baz", + impdescr.getTarget()); + assertEquals(source.indexOf("import " + impdescr.getTarget()), + impdescr.getStartCharacter()); + assertEquals(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length(), + impdescr.getEndCharacter()); + } + + @Test + public void testFunctionImport() throws Exception { + final String source = "package foo\n" + + "import function java.lang.Math.max\n" + + "import function java.lang.Math.min;\n" + + "import foo.bar.*\n" + + "import baz.Baz"; + PackageDescr pkg = parser.parse(source); + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + assertEquals("foo", + pkg.getName()); + assertEquals(2, + pkg.getImports().size()); + ImportDescr impdescr = pkg.getImports().get(0); + assertEquals("foo.bar.*", + impdescr.getTarget()); + assertEquals(source.indexOf("import " + impdescr.getTarget()), + impdescr.getStartCharacter()); + + assertEquals(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1, + impdescr.getEndCharacter()); + + impdescr = pkg.getImports().get(1); + assertEquals("baz.Baz", + impdescr.getTarget()); + assertEquals(source.indexOf("import " + impdescr.getTarget()), + impdescr.getStartCharacter()); + assertEquals(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1, + impdescr.getEndCharacter()); + + assertEquals(2, + pkg.getFunctionImports().size()); + impdescr = pkg.getFunctionImports().get(0); + assertEquals("java.lang.Math.max", + impdescr.getTarget()); + assertEquals(source.indexOf("import function " + impdescr.getTarget()), + impdescr.getStartCharacter()); + assertEquals(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length() - 1, + impdescr.getEndCharacter()); + + impdescr = pkg.getFunctionImports().get(1); + assertEquals("java.lang.Math.min", + impdescr.getTarget()); + assertEquals(source.indexOf("import function " + impdescr.getTarget()), + impdescr.getStartCharacter()); + assertEquals(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length(), + impdescr.getEndCharacter()); + } + + @Test + public void testGlobalWithComplexType() throws Exception { + final String source = "package foo.bar.baz\n" + + "import com.foo.Bar\n" + + "global java.util.List> aList;\n" + + "global Integer aNumber"; + PackageDescr pkg = parser.parse(source); + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + assertEquals("foo.bar.baz", + pkg.getName()); + assertEquals(1, + pkg.getImports().size()); + + ImportDescr impdescr = pkg.getImports().get(0); + assertEquals("com.foo.Bar", + impdescr.getTarget()); + assertEquals(source.indexOf("import " + impdescr.getTarget()), + impdescr.getStartCharacter()); + assertEquals(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1, + impdescr.getEndCharacter()); + + assertEquals(2, + pkg.getGlobals().size()); + + GlobalDescr global = pkg.getGlobals().get(0); + assertEquals("java.util.List>", + global.getType()); + assertEquals("aList", + global.getIdentifier()); + assertEquals(source.indexOf("global " + global.getType()), + global.getStartCharacter()); + assertEquals(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + + ("global " + global.getType() + " " + global.getIdentifier()).length(), + global.getEndCharacter()); + + global = pkg.getGlobals().get(1); + assertEquals("Integer", + global.getType()); + assertEquals("aNumber", + global.getIdentifier()); + assertEquals(source.indexOf("global " + global.getType()), + global.getStartCharacter()); + assertEquals(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + + ("global " + global.getType() + " " + global.getIdentifier()).length() - 1, + global.getEndCharacter()); + } + + @Test + public void testGlobalWithOrWithoutSemi() throws Exception { + PackageDescr pack = parseResource("globals.drl"); + + assertEquals(1, + pack.getRules().size()); + + final RuleDescr rule = (RuleDescr) pack.getRules().get(0); + assertEquals(1, + rule.getLhs().getDescrs().size()); + + assertEquals(1, + pack.getImports().size()); + assertEquals(2, + pack.getGlobals().size()); + + final GlobalDescr foo = (GlobalDescr) pack.getGlobals().get(0); + assertEquals("java.lang.String", + foo.getType()); + assertEquals("foo", + foo.getIdentifier()); + final GlobalDescr bar = (GlobalDescr) pack.getGlobals().get(1); + assertEquals("java.lang.Integer", + bar.getType()); + assertEquals("bar", + bar.getIdentifier()); + } + + @Test + public void testFunctionImportWithNotExist() throws Exception { + PackageDescr pkg = (PackageDescr) parseResource("test_FunctionImport.drl"); + + assertEquals(2, + pkg.getFunctionImports().size()); + + assertEquals("abd.def.x", + ((FunctionImportDescr) pkg.getFunctionImports().get(0)).getTarget()); + assertFalse(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getStartCharacter() == -1); + assertFalse(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getEndCharacter() == -1); + assertEquals("qed.wah.*", + ((FunctionImportDescr) pkg.getFunctionImports().get(1)).getTarget()); + assertFalse(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getStartCharacter() == -1); + assertFalse(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getEndCharacter() == -1); + } + + @Test + public void testFromComplexAcessor() throws Exception { + String source = "rule \"Invalid customer id\" ruleflow-group \"validate\" lock-on-active true \n" + + " when \n" + + " o: Order( ) \n" + + " not( Customer( ) from customerService.getCustomer(o.getCustomerId()) ) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); " + + "\n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parser.parse(source); + + assertFalse(parser.getErrorMessages().toString(), + parser.hasErrors()); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertEquals("Invalid customer id", + rule.getName()); + + assertEquals(2, + rule.getLhs().getDescrs().size()); + + NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(1); + PatternDescr customer = (PatternDescr) not.getDescrs().get(0); + + assertEquals("Customer", + customer.getObjectType()); + assertEquals("customerService.getCustomer(o.getCustomerId())", + ((FromDescr) customer.getSource()).getDataSource().getText()); } } diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/globals.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/globals.drl new file mode 100644 index 00000000000..bc352c77f4b --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/globals.drl @@ -0,0 +1,28 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +global java.lang.String foo +global java.lang.Integer bar; + +rule baz + when + Cheese( ) + then + +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_FunctionImport.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_FunctionImport.drl new file mode 100644 index 00000000000..a548a7b4c2c --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_FunctionImport.drl @@ -0,0 +1,27 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package HR1 + +import function abd.def.x +import function qed.wah.* + +rule simple_rule + when + not ( Cheese(type == "stilton") ) + exists ( Foo() ) + then + funky(); +end From a30d77165da1787e3b0a383a33f5aa8a92976df2 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Sun, 29 May 2022 16:34:48 +0900 Subject: [PATCH 017/141] Enhance test/grammar coverage. and, or, listExpression (#7) --- drools-drl/drools-drl10-parser/pom.xml | 6 + .../main/antlr4/org/drools/parser/DRLLexer.g4 | 3 + .../antlr4/org/drools/parser/DRLParser.g4 | 28 +++- .../org/drools/parser/DRLVisitorImpl.java | 52 ++++++-- .../org/drools/parser/MiscDRLParserTest.java | 120 ++++++++++++++++++ 5 files changed, 192 insertions(+), 17 deletions(-) diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml index 599ec8ab07f..93eefbc5d0d 100644 --- a/drools-drl/drools-drl10-parser/pom.xml +++ b/drools-drl/drools-drl10-parser/pom.xml @@ -47,6 +47,12 @@ ${version.junit} test + + org.assertj + assertj-core + ${version.org.assertj} + test + ch.qos.logback logback-classic diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 0f4ee3cc48f..8ba1364c40d 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -32,6 +32,9 @@ WHEN : 'when'; THEN : 'then'; END : 'end'; +KWD_AND : 'and'; +KWD_OR : 'or'; + EXISTS : 'exists'; NOT : 'not'; IN : 'in'; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 2818590bd59..c9db7951aa7 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -19,8 +19,8 @@ ruledef : RULE name=stringId (EXTENDS stringId)? drlAnnotation* attributes? WHEN lhs : lhsExpression ; lhsExpression : lhsOr* ; -lhsOr : LPAREN OR lhsAnd+ RPAREN | lhsAnd (OR lhsAnd)* ; -lhsAnd : LPAREN AND lhsUnary+ RPAREN | lhsUnary (AND lhsUnary)* ; +lhsOr : LPAREN KWD_OR lhsAnd+ RPAREN | lhsAnd (KWD_OR lhsAnd)* ; +lhsAnd : LPAREN KWD_AND lhsUnary+ RPAREN | lhsUnary (KWD_AND lhsUnary)* ; /* lhsUnary : ( lhsExists namedConsequence? @@ -38,7 +38,7 @@ lhsUnary : ( | lhsNot | lhsPatternBind ) ; -lhsPatternBind : label? ( LPAREN lhsPattern (OR lhsPattern)* RPAREN | lhsPattern ) ; +lhsPatternBind : label? ( LPAREN lhsPattern (KWD_OR lhsPattern)* RPAREN | lhsPattern ) ; /* lhsPattern : xpathPrimary (OVER patternFilter)? | @@ -58,7 +58,27 @@ andExpression : left=equalityExpression (BITAND right=equalityExpression)* ; equalityExpression : left=instanceOfExpression ( ( op=EQUAL | op=NOTEQUAL ) right=instanceOfExpression )* ; instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; inExpression : left=relationalExpression ( 'not'? 'in' LPAREN drlExpression (COMMA drlExpression)* RPAREN )? ; -relationalExpression : expression? ; // TODO +relationalExpression : expression? ; // TODO : shiftExpression, additiveExpression, multiplicativeExpression, unaryExpression, unaryExpressionNotPlusMinus, ..., primary + +/* extending JavaParser */ +primary + : LPAREN expression RPAREN + | THIS + | SUPER + | literal + | identifier + | typeTypeOrVoid DOT CLASS + | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) + | inlineListExpression + ; + +inlineListExpression + : LBRACK expressionList? RBRACK + ; + +expressionList + : expression (COMMA expression)* + ; drlExpression : conditionalExpression ( op=assignmentOperator right=drlExpression )? ; conditionalExpression : left=conditionalOrExpression ternaryExpression? ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index d93c707abe7..98f6388b49e 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -2,6 +2,7 @@ import java.util.ArrayDeque; import java.util.Deque; +import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @@ -19,7 +20,8 @@ public class DRLVisitorImpl extends DRLParserBaseVisitor { private RuleDescr currentRule; private PatternDescr currentPattern; - private Deque currentConstructStack = new ArrayDeque<>(); // e.g. whole LHS, not, exist + + private final Deque currentConstructStack = new ArrayDeque<>(); // e.g. whole LHS (= AndDescr), NotDescr, ExistsDescr @Override public Object visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { @@ -86,23 +88,47 @@ public Object visitLhs(DRLParser.LhsContext ctx) { @Override public Object visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { - // TODO: this logic will likely be split to visitLhsPattern if (ctx.lhsPattern().size() == 1) { - DRLParser.LhsPatternContext lhsPatternCtx = ctx.lhsPattern(0); - currentPattern = new PatternDescr(lhsPatternCtx.objectType.getText()); + Object result = super.visitLhsPatternBind(ctx); + PatternDescr patternDescr = (PatternDescr) currentConstructStack.peek().getDescrs().get(0); if (ctx.label() != null) { - currentPattern.setIdentifier(ctx.label().IDENTIFIER().getText()); + patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); } - if (lhsPatternCtx.patternSource() != null) { - String expression = lhsPatternCtx.patternSource().getText(); - FromDescr from = new FromDescr(); - from.setDataSource(new MVELExprDescr(expression)); - from.setResource(currentPattern.getResource()); - currentPattern.setSource(from); + return result; + } else if (ctx.lhsPattern().size() > 1) { + OrDescr orDescr = new OrDescr(); + currentConstructStack.peek().addDescr(orDescr); + currentConstructStack.push(orDescr); + try { + Object result = super.visitLhsPatternBind(ctx); + List descrs = orDescr.getDescrs(); + for (BaseDescr descr : descrs) { + PatternDescr patternDescr = (PatternDescr) descr; + if (ctx.label() != null) { + patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); + } + } + return result; + } finally { + currentConstructStack.pop(); } - currentConstructStack.peek().addDescr(currentPattern); + } else { + throw new IllegalStateException("ctx.lhsPattern().size() == 0 : " + ctx.getText()); + } + } + + @Override + public Object visitLhsPattern(DRLParser.LhsPatternContext ctx) { + currentPattern = new PatternDescr(ctx.objectType.getText()); + if (ctx.patternSource() != null) { + String expression = ctx.patternSource().getText(); + FromDescr from = new FromDescr(); + from.setDataSource(new MVELExprDescr(expression)); + from.setResource(currentPattern.getResource()); + currentPattern.setSource(from); } - Object result = super.visitLhsPatternBind(ctx); + Object result = super.visitLhsPattern(ctx); + currentConstructStack.peek().addDescr(currentPattern); currentPattern = null; return result; } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index caabed15927..07746c02991 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -10,11 +10,15 @@ import java.nio.file.Paths; import junit.framework.TestCase; +import org.assertj.core.api.Assertions; +import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.FromDescr; import org.drools.drl.ast.descr.FunctionImportDescr; import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.ImportDescr; import org.drools.drl.ast.descr.NotDescr; +import org.drools.drl.ast.descr.OrDescr; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.ast.descr.PatternDescr; import org.drools.drl.ast.descr.RuleDescr; @@ -22,6 +26,8 @@ import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + /* * This test class is being ported from org.drools.mvel.compiler.lang.RuleParserTest */ @@ -277,4 +283,118 @@ public void testFromComplexAcessor() throws Exception { assertEquals("customerService.getCustomer(o.getCustomerId())", ((FromDescr) customer.getSource()).getDataSource().getText()); } + + @Test + public void testFromWithInlineList() throws Exception { + String source = "rule XYZ \n" + + " when \n" + + " o: Order( ) \n" + + " not( Number( ) from [1, 2, 3] ) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parser.parse(source); + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertEquals("XYZ", + rule.getName()); + + PatternDescr number = (PatternDescr) ((NotDescr) rule.getLhs().getDescrs().get(1)).getDescrs().get(0); + assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3]"); + } + + @Test + public void testFromWithInlineListMethod() throws Exception { + String source = "rule XYZ \n" + + " when \n" + + " o: Order( ) \n" + + " Number( ) from [1, 2, 3].sublist(1, 2) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parser.parse(source); + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertEquals("XYZ", + rule.getName()); + + assertFalse(parser.hasErrors()); + PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); + + assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3].sublist(1, 2)"); + } + + @Test + public void testFromWithInlineListIndex() throws Exception { + String source = "rule XYZ \n" + + " when \n" + + " o: Order( ) \n" + + " Number( ) from [1, 2, 3][1] \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parser.parse(source); + + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertEquals("XYZ", + rule.getName()); + + assertFalse(parser.hasErrors()); + PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3][1]"); + } + + @Test + public void testRuleWithoutEnd() throws Exception { + String source = "rule \"Invalid customer id\" \n" + + " when \n" + + " o: Order( ) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n"; + parser.parse(source); + assertTrue(parser.hasErrors()); + } + + @Test + public void testOrWithSpecialBind() throws Exception { + String source = "rule \"A and (B or C or D)\" \n" + + " when \n" + + " pdo1 : ParametricDataObject( paramID == 101, stringValue == \"1000\" ) and \n" + + " pdo2 :(ParametricDataObject( paramID == 101, stringValue == \"1001\" ) or \n" + + " ParametricDataObject( paramID == 101, stringValue == \"1002\" ) or \n" + + " ParametricDataObject( paramID == 101, stringValue == \"1003\" )) \n" + + " then \n" + + " System.out.println( \"Rule: A and (B or C or D) Fired. pdo1: \" + pdo1 + \" pdo2: \"+ pdo2); \n" + + "end\n"; + PackageDescr pkg = parser.parse(source); + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + + RuleDescr rule = pkg.getRules().get(0); + AndDescr lhs = rule.getLhs(); + assertEquals(2, + lhs.getDescrs().size()); + + PatternDescr pdo1 = (PatternDescr) lhs.getDescrs().get(0); + assertEquals("pdo1", + pdo1.getIdentifier()); + + OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(1); + assertEquals(3, + or.getDescrs().size()); + for (BaseDescr pdo2 : or.getDescrs()) { + assertEquals("pdo2", + ((PatternDescr) pdo2).getIdentifier()); + } + } } From 65e22578258965fec6b819720a1fb1b8a8f1ac29 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 27 Jun 2022 15:42:21 +0900 Subject: [PATCH 018/141] Enhance test/grammar coverage. matches, single quoted string, escape (#9) - Introduced drlExpression, drlPrimary, drlLiteral, DRL_STRING_LITERAL --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 30 +++++++ .../antlr4/org/drools/parser/DRLParser.g4 | 79 +++++++++++++++---- .../org/drools/parser/DRLVisitorImpl.java | 15 +++- .../org/drools/parser/MiscDRLParserTest.java | 61 ++++++++++++++ 4 files changed, 168 insertions(+), 17 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 8ba1364c40d..ed2416b6acd 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -39,6 +39,7 @@ EXISTS : 'exists'; NOT : 'not'; IN : 'in'; FROM : 'from'; +MATCHES : 'matches'; SALIENCE : 'salience'; ENABLED : 'enabled'; @@ -69,6 +70,10 @@ TIME_INTERVAL | (('0'..'9')+ 'ms') ; +DRL_STRING_LITERAL + : ('"' ( DrlEscapeSequence | ~('\\'|'"') )* '"') + | ('\'' ( DrlEscapeSequence | ~('\\'|'\'') )* '\'') { setText( normalizeString( getText() ) ); } + ; ///////////////// // SYMBOLS @@ -80,3 +85,28 @@ NULL_SAFE_DOT : '!.' ; QUESTION_DIV : '?/' ; MISC : '\'' | '\\' | '$' ; + +///////////////// +// Fragment +///////////////// +fragment +DrlEscapeSequence + : '\\' ('b'|'B'|'t'|'n'|'f'|'r'|'"'|'\''|'\\'|'.'|'o'| + 'x'|'a'|'e'|'c'|'d'|'D'|'s'|'S'|'w'|'W'|'p'|'A'| + 'G'|'Z'|'z'|'Q'|'E'|'*'|'['|']'|'('|')'|'$'|'^'| + '{'|'}'|'?'|'+'|'-'|'&'|'|') + | DrlUnicodeEscape + | DrlOctalEscape + ; + +fragment +DrlOctalEscape + : '\\' ('0'..'3') ('0'..'7') ('0'..'7') + | '\\' ('0'..'7') ('0'..'7') + | '\\' ('0'..'7') + ; + +fragment +DrlUnicodeEscape + : '\\' 'u' HexDigit HexDigit HexDigit HexDigit + ; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index c9db7951aa7..b68437835f6 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -58,32 +58,83 @@ andExpression : left=equalityExpression (BITAND right=equalityExpression)* ; equalityExpression : left=instanceOfExpression ( ( op=EQUAL | op=NOTEQUAL ) right=instanceOfExpression )* ; instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; inExpression : left=relationalExpression ( 'not'? 'in' LPAREN drlExpression (COMMA drlExpression)* RPAREN )? ; -relationalExpression : expression? ; // TODO : shiftExpression, additiveExpression, multiplicativeExpression, unaryExpression, unaryExpressionNotPlusMinus, ..., primary +relationalExpression : drlExpression? ; + +/* extending JavaParser expression */ +drlExpression + : drlPrimary + | drlExpression bop=DOT + ( + identifier + | methodCall + | THIS + | NEW nonWildcardTypeArguments? innerCreator + | SUPER superSuffix + | explicitGenericInvocation + ) + | drlExpression LBRACK drlExpression RBRACK + | methodCall + | NEW creator + | LPAREN annotation* typeType (BITAND typeType)* RPAREN drlExpression + | drlExpression postfix=(INC | DEC) + | prefix=(ADD|SUB|INC|DEC) drlExpression + | prefix=(TILDE|BANG) drlExpression + | drlExpression bop=(MUL|DIV|MOD) drlExpression + | drlExpression bop=(ADD|SUB) drlExpression + | drlExpression (LT LT | GT GT GT | GT GT) drlExpression + | drlExpression bop=(LE | GE | GT | LT) drlExpression + | drlExpression bop=INSTANCEOF (typeType | pattern) + | drlExpression bop=MATCHES drlExpression + | drlExpression bop=(EQUAL | NOTEQUAL) drlExpression + | drlExpression bop=BITAND drlExpression + | drlExpression bop=CARET drlExpression + | drlExpression bop=BITOR drlExpression + | drlExpression bop=AND drlExpression + | drlExpression bop=OR drlExpression + | drlExpression bop=QUESTION drlExpression COLON drlExpression + | drlExpression + bop=(ASSIGN | ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | RSHIFT_ASSIGN | URSHIFT_ASSIGN | LSHIFT_ASSIGN | MOD_ASSIGN) + drlExpression + | lambdaExpression // Java8 + | switchExpression // Java17 + + // Java 8 methodReference + | drlExpression COLONCOLON typeArguments? identifier + | typeType COLONCOLON (typeArguments? identifier | NEW) + | classType COLONCOLON typeArguments? NEW + ; -/* extending JavaParser */ -primary - : LPAREN expression RPAREN +/* extending JavaParser primary */ +drlPrimary + : LPAREN drlExpression RPAREN | THIS | SUPER - | literal + | drlLiteral | identifier | typeTypeOrVoid DOT CLASS | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) | inlineListExpression ; +/* extending JavaParser literal */ +drlLiteral + : integerLiteral + | floatLiteral + | CHAR_LITERAL + | DRL_STRING_LITERAL + | BOOL_LITERAL + | NULL_LITERAL + | TEXT_BLOCK // Java17 + ; + inlineListExpression : LBRACK expressionList? RBRACK ; expressionList - : expression (COMMA expression)* + : drlExpression (COMMA drlExpression)* ; -drlExpression : conditionalExpression ( op=assignmentOperator right=drlExpression )? ; -conditionalExpression : left=conditionalOrExpression ternaryExpression? ; -ternaryExpression : QUESTION ts=drlExpression COLON fs=drlExpression ; - /* patternSource := FROM ( fromAccumulate @@ -112,9 +163,9 @@ lhsExists : EXISTS lhsPatternBind ; */ lhsNot : NOT lhsPatternBind ; -rhs : blockStatement+ ; +rhs : blockStatement* ; -stringId : ( IDENTIFIER | STRING_LITERAL ) ; +stringId : ( IDENTIFIER | DRL_STRING_LITERAL ) ; type : IDENTIFIER typeArguments? ( DOT IDENTIFIER typeArguments? )* (LBRACK RBRACK)* ; @@ -129,8 +180,8 @@ drlAnnotation : AT name=qualifiedName drlArguments? ; attributes : attribute ( COMMA? attribute )* ; attribute : ( 'salience' DECIMAL_LITERAL ) | ( 'enabled' | 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOL_LITERAL? - | ( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) STRING_LITERAL - | 'calendars' STRING_LITERAL ( COMMA STRING_LITERAL )* + | ( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) DRL_STRING_LITERAL + | 'calendars' DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* | 'timer' ( DECIMAL_LITERAL | TEXT ) | 'duration' ( DECIMAL_LITERAL | TEXT ) ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 98f6388b49e..5706ddd9db3 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -145,7 +145,16 @@ public Object visitConstraint(DRLParser.ConstraintContext ctx) { } @Override - public Object visitExpression(DRLParser.ExpressionContext ctx) { + public Object visitDrlExpression(DRLParser.DrlExpressionContext ctx) { + return ctx.children.stream() + .map(c -> c instanceof TerminalNode ? c : c.accept(this)) + .filter(Objects::nonNull) + .map(Object::toString) + .collect(Collectors.joining(" ")); + } + + @Override + public Object visitDrlPrimary(DRLParser.DrlPrimaryContext ctx) { return ctx.children.stream() .map(c -> c instanceof TerminalNode ? c : c.accept(this)) .filter(Objects::nonNull) @@ -163,14 +172,14 @@ public Object visitIdentifier(DRLParser.IdentifierContext ctx) { } @Override - public Object visitLiteral(DRLParser.LiteralContext ctx) { + public Object visitDrlLiteral(DRLParser.DrlLiteralContext ctx) { ParseTree node = ctx; while (true) { if (node instanceof TerminalNode) { return node.toString(); } if (node.getChildCount() != 1) { - return super.visitLiteral(ctx); + return super.visitDrlLiteral(ctx); } node = node.getChild(0); } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 07746c02991..c105a4a29fd 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -13,6 +13,7 @@ import org.assertj.core.api.Assertions; import org.drools.drl.ast.descr.AndDescr; import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; import org.drools.drl.ast.descr.FromDescr; import org.drools.drl.ast.descr.FunctionImportDescr; import org.drools.drl.ast.descr.GlobalDescr; @@ -397,4 +398,64 @@ public void testOrWithSpecialBind() throws Exception { ((PatternDescr) pdo2).getIdentifier()); } } + + @Test + public void testCompatibleRestriction() throws Exception { + String source = "package com.sample rule test when Test( ( text == null || text2 matches \"\" ) ) then end"; + PackageDescr pkg = parser.parse(source); + + assertEquals( "com.sample", + pkg.getName() ); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertEquals( "test", + rule.getName() ); + ExprConstraintDescr expr = (ExprConstraintDescr) ((PatternDescr) rule.getLhs().getDescrs().get(0 )).getDescrs().get(0 ); + assertEquals( "( text == null || text2 matches \"\" )", + expr.getText() ); + } + + @Test + public void testSimpleConstraint() throws Exception { + String source = "package com.sample rule test when Cheese( type == 'stilton', price > 10 ) then end"; + PackageDescr pkg = parser.parse(source); + + assertEquals( "com.sample", + pkg.getName() ); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertEquals( "test", + rule.getName() ); + + assertEquals( 1, + rule.getLhs().getDescrs().size() ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + AndDescr constraint = (AndDescr) pattern.getConstraint(); + assertEquals( 2, + constraint.getDescrs().size() ); + assertEquals( "type == \"stilton\"", + constraint.getDescrs().get( 0 ).toString() ); + assertEquals( "price > 10", + constraint.getDescrs().get( 1 ).toString() ); + } + + @Test + public void testStringEscapes() throws Exception { + String source = "package com.sample rule test when Cheese( type matches \"\\..*\\\\.\" ) then end"; + PackageDescr pkg = parser.parse(source); + assertEquals( "com.sample", + pkg.getName() ); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertEquals( "test", + rule.getName() ); + + assertEquals( 1, + rule.getLhs().getDescrs().size() ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + AndDescr constraint = (AndDescr) pattern.getConstraint(); + assertEquals( 1, + constraint.getDescrs().size() ); + assertEquals( "type matches \"\\..*\\\\.\"", + constraint.getDescrs().get( 0 ).toString() ); + } } From 4632ed2cce54d41f5beabc9da69b0b2fac10dcf5 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 15 Aug 2022 16:51:01 +0900 Subject: [PATCH 019/141] Enhance test/grammar coverage. dialect, invalid lhs (#10) --- drools-drl/drools-drl10-parser/pom.xml | 5 ++ .../antlr4/org/drools/parser/DRLParser.g4 | 2 +- .../org/drools/parser/DRLVisitorImpl.java | 31 ++++++++-- ...tringUtils.java => ParserStringUtils.java} | 4 +- .../org/drools/parser/MiscDRLParserTest.java | 56 +++++++++++++++---- .../org/drools/parser/empty_rule.drl | 21 +++++++ 6 files changed, 102 insertions(+), 17 deletions(-) rename drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/{StringUtils.java => ParserStringUtils.java} (86%) create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/empty_rule.drl diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml index 93eefbc5d0d..31e015289c6 100644 --- a/drools-drl/drools-drl10-parser/pom.xml +++ b/drools-drl/drools-drl10-parser/pom.xml @@ -20,6 +20,11 @@ drools-drl-ast ${version.drools-drl-ast} + + org.drools + drools-util + ${version.drools-drl-ast} + diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index b68437835f6..2551a835932 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -5,7 +5,7 @@ options { tokenVocab=DRLLexer; } import JavaParser; -compilationUnit : packagedef? unitdef? importdef* globaldef* ruledef* ; +compilationUnit : packagedef? unitdef? importdef* attributes* globaldef* ruledef* ; packagedef : PACKAGE name=qualifiedName SEMI? ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 5706ddd9db3..8caa78a977d 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -9,10 +9,27 @@ import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; -import org.drools.drl.ast.descr.*; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ConditionalElementDescr; +import org.drools.drl.ast.descr.ExistsDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.FromDescr; +import org.drools.drl.ast.descr.FunctionImportDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.ImportDescr; +import org.drools.drl.ast.descr.MVELExprDescr; +import org.drools.drl.ast.descr.NotDescr; +import org.drools.drl.ast.descr.OrDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.UnitDescr; import static org.drools.parser.DRLParserHelper.getTextWithoutErrorNode; -import static org.drools.parser.StringUtils.safeStripStringDelimiters; +import static org.drools.parser.ParserStringUtils.safeStripStringDelimiters; +import static org.drools.util.StringUtils.unescapeJava; public class DRLVisitorImpl extends DRLParserBaseVisitor { @@ -197,9 +214,15 @@ public Object visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { public Object visitAttribute(DRLParser.AttributeContext ctx) { AttributeDescr attributeDescr = new AttributeDescr(ctx.getChild(0).getText()); if (ctx.getChildCount() > 1) { - attributeDescr.setValue(ctx.getChild(1).getText()); + // TODO : will likely split visitAttribute methods using labels (e.g. #stringAttribute) + String value = unescapeJava(safeStripStringDelimiters(ctx.getChild(1).getText())); + attributeDescr.setValue(value); + } + if (currentRule != null) { + currentRule.addAttribute(attributeDescr); + } else { + packageDescr.addAttribute(attributeDescr); } - currentRule.addAttribute(attributeDescr); return super.visitAttribute(ctx); } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/StringUtils.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java similarity index 86% rename from drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/StringUtils.java rename to drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java index 22f8adf4c8a..966a68b90c7 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/StringUtils.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java @@ -3,9 +3,9 @@ /** * will be merged in drools-util */ -public class StringUtils { +public class ParserStringUtils { - private StringUtils() { + private ParserStringUtils() { } public static String safeStripStringDelimiters(String value) { diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index c105a4a29fd..baaaa5a5e4d 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -12,6 +12,7 @@ import junit.framework.TestCase; import org.assertj.core.api.Assertions; import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; import org.drools.drl.ast.descr.FromDescr; @@ -47,7 +48,7 @@ protected void tearDown() throws Exception { super.tearDown(); } - private PackageDescr parseResource(final String filename) throws Exception { + private String readResource(final String filename) throws Exception { Path path = Paths.get(getClass().getResource(filename).toURI()); final StringBuilder sb = new StringBuilder(); try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { @@ -57,7 +58,7 @@ private PackageDescr parseResource(final String filename) throws Exception { } catch (IOException e) { e.printStackTrace(); } - return parser.parse(sb.toString()); + return sb.toString(); } @Test @@ -210,26 +211,27 @@ public void testGlobalWithComplexType() throws Exception { @Test public void testGlobalWithOrWithoutSemi() throws Exception { - PackageDescr pack = parseResource("globals.drl"); + String source = readResource("globals.drl"); + PackageDescr pkg = parser.parse(source); assertEquals(1, - pack.getRules().size()); + pkg.getRules().size()); - final RuleDescr rule = (RuleDescr) pack.getRules().get(0); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertEquals(1, rule.getLhs().getDescrs().size()); assertEquals(1, - pack.getImports().size()); + pkg.getImports().size()); assertEquals(2, - pack.getGlobals().size()); + pkg.getGlobals().size()); - final GlobalDescr foo = (GlobalDescr) pack.getGlobals().get(0); + final GlobalDescr foo = (GlobalDescr) pkg.getGlobals().get(0); assertEquals("java.lang.String", foo.getType()); assertEquals("foo", foo.getIdentifier()); - final GlobalDescr bar = (GlobalDescr) pack.getGlobals().get(1); + final GlobalDescr bar = (GlobalDescr) pkg.getGlobals().get(1); assertEquals("java.lang.Integer", bar.getType()); assertEquals("bar", @@ -238,7 +240,8 @@ public void testGlobalWithOrWithoutSemi() throws Exception { @Test public void testFunctionImportWithNotExist() throws Exception { - PackageDescr pkg = (PackageDescr) parseResource("test_FunctionImport.drl"); + String source = readResource("test_FunctionImport.drl"); + PackageDescr pkg = parser.parse(source); assertEquals(2, pkg.getFunctionImports().size()); @@ -458,4 +461,37 @@ public void testStringEscapes() throws Exception { assertEquals( "type matches \"\\..*\\\\.\"", constraint.getDescrs().get( 0 ).toString() ); } + + @Test + public void testDialect() throws Exception { + final String source = "dialect 'mvel'"; + PackageDescr pkg = parser.parse(source); + AttributeDescr attr = (AttributeDescr) pkg.getAttributes().get(0); + assertEquals("dialect", + attr.getName()); + assertEquals("mvel", + attr.getValue()); + } + + @Test + public void testDialect2() throws Exception { + final String source = "dialect \"mvel\""; + PackageDescr pkg = parser.parse(source); + AttributeDescr attr = pkg.getAttributes().get(0); + assertEquals("dialect", + attr.getName()); + assertEquals("mvel", + attr.getValue()); + } + + @Test + public void testEmptyRuleWithoutWhen() throws Exception { + String source = readResource("empty_rule.drl"); // without WHEN + PackageDescr pkg = parser.parse(source); + + assertTrue(parser.getErrors().toString(), + parser.hasErrors()); + + // Note : RuleParserTest.testEmptyRule allows this DRL, but I think is doesn't make sense to pass this DRL + } } diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/empty_rule.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/empty_rule.drl new file mode 100644 index 00000000000..406037fbbd2 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/empty_rule.drl @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule empty + +then + +end \ No newline at end of file From acbe6c837062548f76aa460e2e71fab007026dcd Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 22 Sep 2022 19:32:46 +0900 Subject: [PATCH 020/141] Enhance test/grammar coverage. keyword collision (#11) - Add "DRL_" prefix for DRL keywords for clarification --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 78 +++---- .../antlr4/org/drools/parser/DRLParser.g4 | 197 ++++++++++++++++-- .../org/drools/parser/DRLVisitorImpl.java | 15 +- .../org/drools/parser/MiscDRLParserTest.java | 12 ++ .../org/drools/parser/eol_funny_business.drl | 35 ++++ 5 files changed, 272 insertions(+), 65 deletions(-) create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eol_funny_business.drl diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index ed2416b6acd..f92c120d0a6 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -18,45 +18,45 @@ import JavaLexer; // KEYWORDS ///////////////// -PACKAGE : 'package'; -UNIT : 'unit'; -IMPORT : 'import'; -FUNCTION : 'function'; -STATIC : 'static'; -GLOBAL : 'global'; -RULE : 'rule'; -QUERY : 'query'; -EXTENDS : 'extends'; -SUPER : 'super'; -WHEN : 'when'; -THEN : 'then'; -END : 'end'; - -KWD_AND : 'and'; -KWD_OR : 'or'; - -EXISTS : 'exists'; -NOT : 'not'; -IN : 'in'; -FROM : 'from'; -MATCHES : 'matches'; - -SALIENCE : 'salience'; -ENABLED : 'enabled'; -NO_LOOP : 'no-loop'; -AUTO_FOCUS : 'auto-focus'; -LOCK_ON_ACTIVE : 'lock-on-active'; -REFRACT : 'refract'; -DIRECT : 'direct'; -AGENDA_GROUP : 'agenda-group'; -ACTIVATION_GROUP : 'activation-group'; -RULEFLOW_GROUP : 'ruleflow-group'; -DATE_EFFECTIVE : 'date-effective'; -DATE_EXPIRES : 'date-expires'; -DIALECT : 'dialect'; -CALENDARS : 'calendars'; -TIMER : 'timer'; -DURATION : 'duration'; +DRL_PACKAGE : 'package'; +DRL_UNIT : 'unit'; +DRL_IMPORT : 'import'; +DRL_FUNCTION : 'function'; +DRL_STATIC : 'static'; +DRL_GLOBAL : 'global'; +DRL_RULE : 'rule'; +DRL_QUERY : 'query'; +DRL_EXTENDS : 'extends'; +DRL_SUPER : 'super'; +DRL_WHEN : 'when'; +DRL_THEN : 'then'; +DRL_END : 'end'; + +DRL_AND : 'and'; +DRL_OR : 'or'; + +DRL_EXISTS : 'exists'; +DRL_NOT : 'not'; +DRL_IN : 'in'; +DRL_FROM : 'from'; +DRL_MATCHES : 'matches'; + +DRL_SALIENCE : 'salience'; +DRL_ENABLED : 'enabled'; +DRL_NO_LOOP : 'no-loop'; +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'; +DRL_DATE_EXPIRES : 'date-expires'; +DRL_DIALECT : 'dialect'; +DRL_CALENDARS : 'calendars'; +DRL_TIMER : 'timer'; +DRL_DURATION : 'duration'; ///////////////// // LEXER diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 2551a835932..690828a176e 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -4,23 +4,42 @@ options { tokenVocab=DRLLexer; } import JavaParser; + /* + * statement := importStatement + * | globalStatement + * | declare + * | rule + * | ruleAttribute + * | function + * | query + * ; + */ +compilationUnit : packagedef? unitdef? drlStatementdef* ; -compilationUnit : packagedef? unitdef? importdef* attributes* globaldef* ruledef* ; +drlStatementdef + : importdef + | globaldef + | functiondef + | attributes + | ruledef + ; + +packagedef : DRL_PACKAGE name=drlQualifiedName SEMI? ; -packagedef : PACKAGE name=qualifiedName SEMI? ; +unitdef : DRL_UNIT name=drlQualifiedName SEMI? ; -unitdef : UNIT name=qualifiedName SEMI? ; +importdef : DRL_IMPORT (DRL_FUNCTION|DRL_STATIC)? drlQualifiedName (DOT MUL)? SEMI? ; -importdef : IMPORT (FUNCTION|STATIC)? qualifiedName (DOT MUL)? SEMI? ; +globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; -globaldef : GLOBAL type IDENTIFIER SEMI? ; +// rule := RULE stringId (EXTENDS stringId)? annotation* attributes? lhs? rhs END -ruledef : RULE name=stringId (EXTENDS stringId)? drlAnnotation* attributes? WHEN lhs THEN rhs END ; +ruledef : DRL_RULE name=stringId (DRL_EXTENDS stringId)? drlAnnotation* attributes? DRL_WHEN lhs DRL_THEN rhs DRL_END ; -lhs : lhsExpression ; +lhs : lhsExpression? ; lhsExpression : lhsOr* ; -lhsOr : LPAREN KWD_OR lhsAnd+ RPAREN | lhsAnd (KWD_OR lhsAnd)* ; -lhsAnd : LPAREN KWD_AND lhsUnary+ RPAREN | lhsUnary (KWD_AND lhsUnary)* ; +lhsOr : LPAREN DRL_OR lhsAnd+ RPAREN | lhsAnd (DRL_OR lhsAnd)* ; +lhsAnd : LPAREN DRL_AND lhsUnary+ RPAREN | lhsUnary (DRL_AND lhsUnary)* ; /* lhsUnary : ( lhsExists namedConsequence? @@ -38,14 +57,14 @@ lhsUnary : ( | lhsNot | lhsPatternBind ) ; -lhsPatternBind : label? ( LPAREN lhsPattern (KWD_OR lhsPattern)* RPAREN | lhsPattern ) ; +lhsPatternBind : label? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; /* lhsPattern : xpathPrimary (OVER patternFilter)? | ( QUESTION? qualifiedIdentifier LPAREN positionalConstraints? constraints? RPAREN (OVER patternFilter)? (FROM patternSource)? ) ; */ -lhsPattern : QUESTION? objectType=qualifiedName LPAREN (positionalConstraints? constraints? ) RPAREN (FROM patternSource)? ; +lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN (positionalConstraints? constraints? ) RPAREN (DRL_FROM patternSource)? ; positionalConstraints : constraint (COMMA constraint)* SEMI ; constraints : constraint (COMMA constraint)* ; constraint : label? ( nestedConstraint | conditionalOrExpression ) ; @@ -60,6 +79,76 @@ instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; inExpression : left=relationalExpression ( 'not'? 'in' LPAREN drlExpression (COMMA drlExpression)* RPAREN )? ; relationalExpression : drlExpression? ; + +/* function := FUNCTION type? ID parameters(typed) chunk_{_} */ +functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters block ; + + +/* extending JavaParser qualifiedName */ +drlQualifiedName + : drlIdentifier (DOT drlIdentifier)* + ; + +/* extending JavaParser identifier */ +drlIdentifier + : drlKeywords + | IDENTIFIER + | MODULE + | OPEN + | REQUIRES + | EXPORTS + | OPENS + | TO + | USES + | PROVIDES + | WITH + | TRANSITIVE + | YIELD + | SEALED + | PERMITS + | RECORD + | VAR + ; + +drlKeywords + : DRL_PACKAGE + | DRL_UNIT + | DRL_IMPORT + | DRL_FUNCTION + | DRL_STATIC + | DRL_GLOBAL + | DRL_RULE + | DRL_QUERY + | DRL_EXTENDS + | DRL_SUPER + | DRL_WHEN + | DRL_THEN + | DRL_END + | DRL_AND + | DRL_OR + | DRL_EXISTS + | DRL_NOT + | DRL_IN + | DRL_FROM + | DRL_MATCHES + | DRL_SALIENCE + | DRL_ENABLED + | DRL_NO_LOOP + | DRL_AUTO_FOCUS + | DRL_LOCK_ON_ACTIVE + | DRL_REFRACT + | DRL_DIRECT + | DRL_AGENDA_GROUP + | DRL_ACTIVATION_GROUP + | DRL_RULEFLOW_GROUP + | DRL_DATE_EFFECTIVE + | DRL_DATE_EXPIRES + | DRL_DIALECT + | DRL_CALENDARS + | DRL_TIMER + | DRL_DURATION + ; + /* extending JavaParser expression */ drlExpression : drlPrimary @@ -84,7 +173,7 @@ drlExpression | drlExpression (LT LT | GT GT GT | GT GT) drlExpression | drlExpression bop=(LE | GE | GT | LT) drlExpression | drlExpression bop=INSTANCEOF (typeType | pattern) - | drlExpression bop=MATCHES drlExpression + | drlExpression bop=DRL_MATCHES drlExpression | drlExpression bop=(EQUAL | NOTEQUAL) drlExpression | drlExpression bop=BITAND drlExpression | drlExpression bop=CARET drlExpression @@ -110,7 +199,7 @@ drlPrimary | THIS | SUPER | drlLiteral - | identifier + | drlIdentifier | typeTypeOrVoid DOT CLASS | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) | inlineListExpression @@ -153,7 +242,7 @@ fromExpression : conditionalOrExpression ; | lhsPatternBind ) */ -lhsExists : EXISTS lhsPatternBind ; +lhsExists : DRL_EXISTS lhsPatternBind ; /* lhsNot := NOT ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or @@ -161,9 +250,9 @@ lhsExists : EXISTS lhsPatternBind ; | lhsPatternBind ) */ -lhsNot : NOT lhsPatternBind ; +lhsNot : DRL_NOT lhsPatternBind ; -rhs : blockStatement* ; +rhs : drlRhsBlockStatement* ; stringId : ( IDENTIFIER | DRL_STRING_LITERAL ) ; @@ -175,7 +264,7 @@ type : IDENTIFIER typeArguments? ( DOT IDENTIFIER typeArguments? )* (LBRACK RBRA drlArguments : LPAREN drlArgument (COMMA drlArgument)* RPAREN ; drlArgument : ( stringId | floatLiteral | BOOL_LITERAL | NULL_LITERAL ) ; -drlAnnotation : AT name=qualifiedName drlArguments? ; +drlAnnotation : AT name=drlQualifiedName drlArguments? ; attributes : attribute ( COMMA? attribute )* ; attribute : ( 'salience' DECIMAL_LITERAL ) @@ -198,3 +287,77 @@ assignmentOperator : ASSIGN label : IDENTIFIER COLON ; unif : IDENTIFIER UNIFY ; + +/* extending JavaParser blockStatement */ +drlRhsBlockStatement + : localVariableDeclaration SEMI + | drlRhsStatement + | localTypeDeclaration + ; + +/* extending JavaParser statement */ +drlRhsStatement + : blockLabel=block + | ASSERT drlRhsExpression (COLON drlRhsExpression)? SEMI + | IF parExpression drlRhsStatement (ELSE drlRhsStatement)? + | FOR LPAREN forControl RPAREN drlRhsStatement + | WHILE parExpression drlRhsStatement + | DO drlRhsStatement WHILE parExpression SEMI + | TRY block (catchClause+ finallyBlock? | finallyBlock) + | TRY resourceSpecification block catchClause* finallyBlock? + | SWITCH parExpression LBRACE switchBlockStatementGroup* switchLabel* RBRACE + | SYNCHRONIZED parExpression block + | RETURN drlRhsExpression? SEMI + | THROW drlRhsExpression SEMI + | BREAK identifier? SEMI + | CONTINUE identifier? SEMI + | YIELD drlRhsExpression SEMI // Java17 + | SEMI + | statementExpression=drlRhsExpression SEMI + | switchExpression SEMI? // Java17 + | identifierLabel=identifier COLON drlRhsStatement + ; + +/* extending JavaParser expression */ +drlRhsExpression + : drlPrimary + | drlRhsExpression bop=DOT + ( + identifier + | methodCall + | THIS + | NEW nonWildcardTypeArguments? innerCreator + | SUPER superSuffix + | explicitGenericInvocation + ) + | drlRhsExpression LBRACK drlRhsExpression RBRACK + | methodCall + | NEW creator + | LPAREN annotation* typeType (BITAND typeType)* RPAREN drlRhsExpression + | drlRhsExpression postfix=(INC | DEC) + | prefix=(ADD|SUB|INC|DEC) drlRhsExpression + | prefix=(TILDE|BANG) drlRhsExpression + | drlRhsExpression bop=(MUL|DIV|MOD) drlRhsExpression + | drlRhsExpression bop=(ADD|SUB) drlRhsExpression + | drlRhsExpression (LT LT | GT GT GT | GT GT) drlRhsExpression + | drlRhsExpression bop=(LE | GE | GT | LT) drlRhsExpression + | drlRhsExpression bop=INSTANCEOF (typeType | pattern) + | drlRhsExpression bop=DRL_MATCHES drlRhsExpression + | drlRhsExpression bop=(EQUAL | NOTEQUAL) drlRhsExpression + | drlRhsExpression bop=BITAND drlRhsExpression + | drlRhsExpression bop=CARET drlRhsExpression + | drlRhsExpression bop=BITOR drlRhsExpression + | drlRhsExpression bop=AND drlRhsExpression + | drlRhsExpression bop=OR drlRhsExpression + | drlRhsExpression bop=QUESTION drlRhsExpression COLON drlRhsExpression + | drlRhsExpression + bop=(ASSIGN | ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | RSHIFT_ASSIGN | URSHIFT_ASSIGN | LSHIFT_ASSIGN | MOD_ASSIGN) + drlRhsExpression + | lambdaExpression // Java8 + | switchExpression // Java17 + + // Java 8 methodReference + | drlRhsExpression COLONCOLON typeArguments? identifier + | typeType COLONCOLON (typeArguments? identifier | NEW) + | classType COLONCOLON typeArguments? NEW + ; \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 8caa78a977d..d45028d82a8 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -59,7 +59,7 @@ public Object visitUnitdef(DRLParser.UnitdefContext ctx) { @Override public Object visitGlobaldef(DRLParser.GlobaldefContext ctx) { - GlobalDescr globalDescr = new GlobalDescr(ctx.IDENTIFIER().getText(), ctx.type().getText()); + GlobalDescr globalDescr = new GlobalDescr(ctx.drlIdentifier().getText(), ctx.type().getText()); populateStartEnd(globalDescr, ctx); packageDescr.addGlobal(globalDescr); return super.visitGlobaldef(ctx); @@ -67,8 +67,8 @@ public Object visitGlobaldef(DRLParser.GlobaldefContext ctx) { @Override public Object visitImportdef(DRLParser.ImportdefContext ctx) { - String target = ctx.qualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); - if (ctx.FUNCTION() != null || ctx.STATIC() != null) { + String target = ctx.drlQualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); + if (ctx.DRL_FUNCTION() != null || ctx.DRL_STATIC() != null) { FunctionImportDescr functionImportDescr = new FunctionImportDescr(); functionImportDescr.setTarget(target); populateStartEnd(functionImportDescr, ctx); @@ -180,14 +180,11 @@ public Object visitDrlPrimary(DRLParser.DrlPrimaryContext ctx) { } @Override - public Object visitIdentifier(DRLParser.IdentifierContext ctx) { - if (ctx.IDENTIFIER() == null) { - return ""; - } else { - return ctx.IDENTIFIER().getText(); - } + public Object visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { + return ctx.getText(); } + @Override public Object visitDrlLiteral(DRLParser.DrlLiteralContext ctx) { ParseTree node = ctx; diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index baaaa5a5e4d..079b3ccb9ae 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -494,4 +494,16 @@ public void testEmptyRuleWithoutWhen() throws Exception { // Note : RuleParserTest.testEmptyRule allows this DRL, but I think is doesn't make sense to pass this DRL } + + @Test + public void testKeywordCollisions() throws Exception { + String source = readResource("eol_funny_business.drl"); // keywords everywhere + PackageDescr pkg = parser.parse(source); + + assertFalse( parser.getErrors().toString(), + parser.hasErrors() ); + + assertEquals( 1, + pkg.getRules().size() ); + } } diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eol_funny_business.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eol_funny_business.drl new file mode 100644 index 00000000000..0090d3d0181 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eol_funny_business.drl @@ -0,0 +1,35 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package test.dialect.rule.end.package.mine; + +global java.lang.String rule; + +import com.dialect.something.SomeClass + +function boolean test() { + return true; +} + +rule type1 + when + $id : Something( duration == "foo") + then + The.method(); + attributes; + rule; + package; +end + From acfa336ac277b9d9a710e02edec0383d382f00bc Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 5 Oct 2022 17:12:04 +0900 Subject: [PATCH 021/141] Enhance test/grammar coverage. function, attributes, consequence (#12) * Enhance test/grammar coverage. function, attributes, consequence - better getText preserving whitespaces - resolving WARNs because of overlapping keywords * - No need to declare duplicate keywords --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 14 +- .../antlr4/org/drools/parser/DRLParser.g4 | 79 +++++--- .../org/drools/parser/DRLVisitorImpl.java | 34 +++- .../org/drools/parser/ParserStringUtils.java | 14 ++ .../java/org/drools/parser/DRLParserTest.java | 3 +- .../org/drools/parser/MiscDRLParserTest.java | 175 ++++++++++++++++++ .../org/drools/parser/almost_empty_rule.drl | 20 ++ .../resources/org/drools/parser/autofocus.drl | 23 +++ .../parser/declaration-in-consequence.drl | 46 +++++ .../org/drools/parser/eol_funny_business.drl | 8 +- .../org/drools/parser/function_arrays.drl | 29 +++ .../resources/org/drools/parser/no-loop.drl | 23 +++ .../drools/parser/quoted_string_name_rule.drl | 19 ++ .../org/drools/parser/ruleflowgroup.drl | 23 +++ .../org/drools/parser/ternary_expression.drl | 24 +++ 15 files changed, 500 insertions(+), 34 deletions(-) create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/almost_empty_rule.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/autofocus.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declaration-in-consequence.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/function_arrays.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/no-loop.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/quoted_string_name_rule.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/ruleflowgroup.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/ternary_expression.drl diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index f92c120d0a6..60e282c49fb 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -18,16 +18,20 @@ import JavaLexer; // KEYWORDS ///////////////// -DRL_PACKAGE : 'package'; +// These keywords are already declared in JavaLexer. They should not be overriden with different names, or else Vocabulary's literalName will be null. +// So no need to declare by DRLLexer +// PACKAGE : 'package'; +// IMPORT : 'import'; +// STATIC : 'static'; +// EXTENDS : 'extends'; +// SUPER : 'super'; + +// DRL keywords DRL_UNIT : 'unit'; -DRL_IMPORT : 'import'; DRL_FUNCTION : 'function'; -DRL_STATIC : 'static'; DRL_GLOBAL : 'global'; DRL_RULE : 'rule'; DRL_QUERY : 'query'; -DRL_EXTENDS : 'extends'; -DRL_SUPER : 'super'; DRL_WHEN : 'when'; DRL_THEN : 'then'; DRL_END : 'end'; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 690828a176e..00c61cbc1e5 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -24,20 +24,20 @@ drlStatementdef | ruledef ; -packagedef : DRL_PACKAGE name=drlQualifiedName SEMI? ; +packagedef : PACKAGE name=drlQualifiedName SEMI? ; unitdef : DRL_UNIT name=drlQualifiedName SEMI? ; -importdef : DRL_IMPORT (DRL_FUNCTION|DRL_STATIC)? drlQualifiedName (DOT MUL)? SEMI? ; +importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? SEMI? ; globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; // rule := RULE stringId (EXTENDS stringId)? annotation* attributes? lhs? rhs END -ruledef : DRL_RULE name=stringId (DRL_EXTENDS stringId)? drlAnnotation* attributes? DRL_WHEN lhs DRL_THEN rhs DRL_END ; +ruledef : DRL_RULE name=stringId (EXTENDS stringId)? drlAnnotation* attributes? DRL_WHEN lhs DRL_THEN rhs DRL_END ; lhs : lhsExpression? ; -lhsExpression : lhsOr* ; +lhsExpression : lhsOr+ ; lhsOr : LPAREN DRL_OR lhsAnd+ RPAREN | lhsAnd (DRL_OR lhsAnd)* ; lhsAnd : LPAREN DRL_AND lhsUnary+ RPAREN | lhsUnary (DRL_AND lhsUnary)* ; @@ -111,16 +111,11 @@ drlIdentifier ; drlKeywords - : DRL_PACKAGE - | DRL_UNIT - | DRL_IMPORT + : DRL_UNIT | DRL_FUNCTION - | DRL_STATIC | DRL_GLOBAL | DRL_RULE | DRL_QUERY - | DRL_EXTENDS - | DRL_SUPER | DRL_WHEN | DRL_THEN | DRL_END @@ -154,7 +149,7 @@ drlExpression : drlPrimary | drlExpression bop=DOT ( - identifier + drlIdentifier | methodCall | THIS | NEW nonWildcardTypeArguments? innerCreator @@ -163,7 +158,7 @@ drlExpression ) | drlExpression LBRACK drlExpression RBRACK | methodCall - | NEW creator + | NEW drlCreator | LPAREN annotation* typeType (BITAND typeType)* RPAREN drlExpression | drlExpression postfix=(INC | DEC) | prefix=(ADD|SUB|INC|DEC) drlExpression @@ -188,8 +183,8 @@ drlExpression | switchExpression // Java17 // Java 8 methodReference - | drlExpression COLONCOLON typeArguments? identifier - | typeType COLONCOLON (typeArguments? identifier | NEW) + | drlExpression COLONCOLON typeArguments? drlIdentifier + | typeType COLONCOLON (typeArguments? drlIdentifier | NEW) | classType COLONCOLON typeArguments? NEW ; @@ -290,11 +285,38 @@ unif : IDENTIFIER UNIFY ; /* extending JavaParser blockStatement */ drlRhsBlockStatement - : localVariableDeclaration SEMI + : drlLocalVariableDeclaration SEMI | drlRhsStatement | localTypeDeclaration ; +/* extending JavaParser localVariableDeclaration */ +drlLocalVariableDeclaration + : variableModifier* (typeType drlVariableDeclarators | VAR drlIdentifier ASSIGN drlExpression) + ; + +/* extending JavaParser variableDeclarators */ +drlVariableDeclarators + : drlVariableDeclarator (COMMA drlVariableDeclarator)* + ; + +/* extending JavaParser variableDeclarator */ +drlVariableDeclarator + : drlVariableDeclaratorId (ASSIGN drlVariableInitializer)? + ; + +/* extending JavaParser variableDeclaratorId */ +drlVariableDeclaratorId + : drlIdentifier (LBRACK RBRACK)* + ; + +/* extending JavaParser variableInitializer */ +drlVariableInitializer + : arrayInitializer + | drlExpression + ; + + /* extending JavaParser statement */ drlRhsStatement : blockLabel=block @@ -309,13 +331,13 @@ drlRhsStatement | SYNCHRONIZED parExpression block | RETURN drlRhsExpression? SEMI | THROW drlRhsExpression SEMI - | BREAK identifier? SEMI - | CONTINUE identifier? SEMI + | BREAK drlIdentifier? SEMI + | CONTINUE drlIdentifier? SEMI | YIELD drlRhsExpression SEMI // Java17 | SEMI | statementExpression=drlRhsExpression SEMI | switchExpression SEMI? // Java17 - | identifierLabel=identifier COLON drlRhsStatement + | identifierLabel=drlIdentifier COLON drlRhsStatement ; /* extending JavaParser expression */ @@ -323,7 +345,7 @@ drlRhsExpression : drlPrimary | drlRhsExpression bop=DOT ( - identifier + drlIdentifier | methodCall | THIS | NEW nonWildcardTypeArguments? innerCreator @@ -357,7 +379,20 @@ drlRhsExpression | switchExpression // Java17 // Java 8 methodReference - | drlRhsExpression COLONCOLON typeArguments? identifier - | typeType COLONCOLON (typeArguments? identifier | NEW) + | drlRhsExpression COLONCOLON typeArguments? drlIdentifier + | typeType COLONCOLON (typeArguments? drlIdentifier | NEW) | classType COLONCOLON typeArguments? NEW - ; \ No newline at end of file + ; + + drlCreator + : nonWildcardTypeArguments createdName classCreatorRest + | createdName (drlArrayCreatorRest | classCreatorRest) + ; + + drlArrayCreatorRest + : LBRACK (RBRACK (LBRACK RBRACK)* drlArrayInitializer | expression RBRACK (LBRACK expression RBRACK)* (LBRACK RBRACK)*) + ; + + drlArrayInitializer + : LBRACE (drlVariableInitializer (COMMA drlVariableInitializer)* (COMMA)? )? RBRACE + ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index d45028d82a8..28775cfa8d9 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -16,6 +16,7 @@ import org.drools.drl.ast.descr.ExistsDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; import org.drools.drl.ast.descr.FromDescr; +import org.drools.drl.ast.descr.FunctionDescr; import org.drools.drl.ast.descr.FunctionImportDescr; import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.ImportDescr; @@ -68,7 +69,7 @@ public Object visitGlobaldef(DRLParser.GlobaldefContext ctx) { @Override public Object visitImportdef(DRLParser.ImportdefContext ctx) { String target = ctx.drlQualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); - if (ctx.DRL_FUNCTION() != null || ctx.DRL_STATIC() != null) { + if (ctx.DRL_FUNCTION() != null || ctx.STATIC() != null) { FunctionImportDescr functionImportDescr = new FunctionImportDescr(); functionImportDescr.setTarget(target); populateStartEnd(functionImportDescr, ctx); @@ -82,10 +83,39 @@ public Object visitImportdef(DRLParser.ImportdefContext ctx) { return super.visitImportdef(ctx); } + @Override + public Object visitFunctiondef(DRLParser.FunctiondefContext ctx) { + FunctionDescr functionDescr = new FunctionDescr(); + functionDescr.setNamespace(packageDescr.getNamespace()); + AttributeDescr dialect = packageDescr.getAttribute("dialect"); + if (dialect != null) { + functionDescr.setDialect(dialect.getValue()); + } + if (ctx.typeTypeOrVoid() != null) { + functionDescr.setReturnType(ctx.typeTypeOrVoid().getText()); + } else { + functionDescr.setReturnType("void"); + } + functionDescr.setName(ctx.IDENTIFIER().getText()); + DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); + DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); + if (formalParameterListContext != null) { + List formalParameterContexts = formalParameterListContext.formalParameter(); + formalParameterContexts.stream().forEach(formalParameterContext -> { + DRLParser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); + DRLParser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); + functionDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); + }); + } + functionDescr.setBody(ParserStringUtils.getTextPreservingWhitespace(ctx.block())); + packageDescr.addFunction(functionDescr); + return super.visitFunctiondef(ctx); + } + @Override public Object visitRuledef(DRLParser.RuledefContext ctx) { currentRule = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); - currentRule.setConsequence(ctx.rhs().getText()); + currentRule.setConsequence(ParserStringUtils.getTextPreservingWhitespace(ctx.rhs())); packageDescr.addRule(currentRule); Object result = super.visitRuledef(ctx); diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java index 966a68b90c7..58410e9ea36 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java @@ -1,5 +1,8 @@ package org.drools.parser; +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.misc.Interval; + /** * will be merged in drools-util */ @@ -17,4 +20,15 @@ public static String safeStripStringDelimiters(String value) { } return value; } + + public static String getTextPreservingWhitespace(ParserRuleContext ctx) { + int startIndex = ctx.start.getStartIndex(); + int stopIndex = ctx.stop.getStopIndex(); + if (startIndex > stopIndex) { + // no text + return ""; + } + Interval interval = new Interval(startIndex, stopIndex); + return ctx.start.getTokenSource().getInputStream().getText(interval); + } } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java index 4e8abc50b0c..1330e7ed509 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java @@ -5,6 +5,7 @@ import org.drools.drl.ast.descr.*; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.drools.parser.DRLParserHelper.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -60,7 +61,7 @@ public void testParse() { ExprConstraintDescr expr = (ExprConstraintDescr) constraints.get(0); assertEquals("age >= 18", expr.getExpression()); - assertEquals("inta=4;System.out.println($p.getName());", ruleDescr.getConsequence()); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int a = 4; System.out.println($p.getName());"); } @Test diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 079b3ccb9ae..48d3460f62a 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -16,6 +16,7 @@ import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; import org.drools.drl.ast.descr.FromDescr; +import org.drools.drl.ast.descr.FunctionDescr; import org.drools.drl.ast.descr.FunctionImportDescr; import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.ImportDescr; @@ -498,6 +499,10 @@ public void testEmptyRuleWithoutWhen() throws Exception { @Test public void testKeywordCollisions() throws Exception { String source = readResource("eol_funny_business.drl"); // keywords everywhere + + // Note: eol_funny_business.drl is modified from the one under drools-test-coverage to be more realistic. + // e.g. "package" is not allowed in a package value in Java, so it doesn't make sense to test. (Right to raise a parser error) + PackageDescr pkg = parser.parse(source); assertFalse( parser.getErrors().toString(), @@ -506,4 +511,174 @@ public void testKeywordCollisions() throws Exception { assertEquals( 1, pkg.getRules().size() ); } + + @Test + public void testTernaryExpression() throws Exception { + String source = readResource("ternary_expression.drl"); + PackageDescr pkg = parser.parse(source); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertEquals( 1, + pkg.getRules().size() ); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if (speed > speedLimit ? true : false;) pullEmOver();"); + } + + @Test + public void testFunctionWithArrays() throws Exception { + String source = readResource("function_arrays.drl"); + + // Note: function_arrays.drl is modified from the one under drools-test-coverage to be more realistic. + // new String[3] {"a","b","c"} is invalid in Java (Cannot define dimension expressions when an array initializer is provided) + // , so it doesn't make sense to test. (Right to raise a parser error) + + PackageDescr pkg = parser.parse(source); + + assertEquals( "foo", + pkg.getName() ); + assertEquals( 1, + pkg.getRules().size() ); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("yourFunction(new String[] {\"a\",\"b\",\"c\"});"); + + final FunctionDescr func = (FunctionDescr) pkg.getFunctions().get(0 ); + + assertEquals( "String[]", + func.getReturnType() ); + assertEquals( "args[]", + func.getParameterNames().get( 0 ) ); + assertEquals( "String", + func.getParameterTypes().get( 0 ) ); + } + + @Test + public void testAlmostEmptyRule() throws Exception { + String source = readResource("almost_empty_rule.drl"); + PackageDescr pkg = parser.parse(source); + + assertFalse( parser.getErrors().toString(), + parser.hasErrors() ); + assertNotNull( pkg ); + + RuleDescr rule = pkg.getRules().get( 0 ); + + assertEquals( "almost_empty", + rule.getName() ); + assertNotNull( rule.getLhs() ); + assertEquals( "", + ((String) rule.getConsequence()).trim() ); + } + + @Test + public void testQuotedStringNameRule() throws Exception { + String source = readResource("quoted_string_name_rule.drl"); + PackageDescr pkg = parser.parse(source); + + assertFalse( parser.getErrors().toString(), + parser.hasErrors() ); + + RuleDescr rule = pkg.getRules().get(0); + assertNotNull( rule ); + + assertEquals( "quoted string name", + rule.getName() ); + assertNotNull( rule.getLhs() ); + assertEquals( "", + ((String) rule.getConsequence()).trim() ); + } + + @Test + public void testNoLoop() throws Exception { + String source = readResource("no-loop.drl"); + PackageDescr pkg = parser.parse(source); + + assertFalse( parser.getErrors().toString(), + parser.hasErrors() ); + + RuleDescr rule = pkg.getRules().get(0); + assertNotNull( rule ); + + assertEquals( "rule1", + rule.getName() ); + final AttributeDescr att = (AttributeDescr) rule.getAttributes().get( "no-loop" ); + assertEquals( "false", + att.getValue() ); + assertEquals( "no-loop", + att.getName() ); + } + + @Test + public void testAutofocus() throws Exception { + String source = readResource("autofocus.drl"); + PackageDescr pkg = parser.parse(source); + + assertFalse( parser.getErrors().toString(), + parser.hasErrors() ); + + RuleDescr rule = pkg.getRules().get(0); + assertNotNull( rule ); + + assertEquals( "rule1", + rule.getName() ); + final AttributeDescr att = (AttributeDescr) rule.getAttributes().get( "auto-focus" ); + assertEquals( "true", + att.getValue() ); + assertEquals( "auto-focus", + att.getName() ); + } + + @Test + public void testRuleFlowGroup() throws Exception { + String source = readResource("ruleflowgroup.drl"); + PackageDescr pkg = parser.parse(source); + + assertFalse( parser.getErrors().toString(), + parser.hasErrors() ); + + RuleDescr rule = pkg.getRules().get(0); + assertNotNull( rule ); + + assertEquals( "rule1", + rule.getName() ); + final AttributeDescr att = (AttributeDescr) rule.getAttributes().get( "ruleflow-group" ); + assertEquals( "a group", + att.getValue() ); + assertEquals( "ruleflow-group", + att.getName() ); + } + + @Test + public void testConsequenceWithDeclaration() throws Exception { + String source = readResource("declaration-in-consequence.drl"); + PackageDescr pkg = parser.parse(source); + + // Note : Removed "i\i;" from the original declaration-in-consequence.drl under drools-test-coverage + // because it's not a valid java expression and doesn't make sense to test. (Right to raise a parser error) + + assertFalse( parser.getErrors().toString(), + parser.hasErrors() ); + + RuleDescr rule = pkg.getRules().get(0); + assertNotNull( rule ); + + assertEquals( "myrule", + rule.getName() ); + + final String expected = "int i = 0; i = 1; i / 1; i == 1; i(i); i = 'i'; i.i.i; ii; i=\"i\"; ++i;" + + "i++; --i; i--; i += i; i -= i; i *= i; i /= i;" + + "int i = 5;" + "for(int j; j 0 ); + assertTrue( ((String) rule.getConsequence()).indexOf( "--" ) > 0 ); + assertTrue( ((String) rule.getConsequence()).indexOf( "+=" ) > 0 ); + assertTrue( ((String) rule.getConsequence()).indexOf( "==" ) > 0 ); + assertTrue( ((String) rule.getConsequence()).indexOf( "i++" ) > 0 ); + // note, need to assert that "i++" is preserved as is, no extra spaces. + } } diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/almost_empty_rule.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/almost_empty_rule.drl new file mode 100644 index 00000000000..149bd5b49a7 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/almost_empty_rule.drl @@ -0,0 +1,20 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule almost_empty + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/autofocus.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/autofocus.drl new file mode 100644 index 00000000000..d968e700c7f --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/autofocus.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule rule1 + auto-focus true + when + not Cheese(type == "stilton") + then + funky(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declaration-in-consequence.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declaration-in-consequence.drl new file mode 100644 index 00000000000..f21bba25dfe --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declaration-in-consequence.drl @@ -0,0 +1,46 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + + +rule myrule + when + then + int i = 0; + i = 1; + i / 1; + i == 1; + i(i); + i = 'i'; + i.i.i; + ii; + i="i"; + ++i; + i++; + --i; + i--; + i += i; + i -= i; + i *= i; + i /= i; + int i = 5; + for(int j; j speedLimit ? true : false;) + pullEmOver(); +end From 4acd6db163650ee26068b3e54c688794b605afe4 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 3 Nov 2022 16:23:55 +0900 Subject: [PATCH 022/141] Enhance test/grammar coverage. OR, inline map (#13) --- .../antlr4/org/drools/parser/DRLParser.g4 | 15 +- .../org/drools/parser/DRLVisitorImpl.java | 17 ++- .../org/drools/parser/MiscDRLParserTest.java | 136 ++++++++++++++++++ .../parser/literal_bool_and_negative.drl | 25 ++++ .../org/drools/parser/test_EmptyPattern.drl | 24 ++++ .../parser/test_SimpleMethodCallWithFrom.drl | 25 ++++ 6 files changed, 240 insertions(+), 2 deletions(-) create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/literal_bool_and_negative.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EmptyPattern.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleMethodCallWithFrom.drl diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 00c61cbc1e5..4684804a10f 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -64,7 +64,7 @@ lhsPattern : xpathPrimary (OVER patternFilter)? | ( QUESTION? qualifiedIdentifier LPAREN positionalConstraints? constraints? RPAREN (OVER patternFilter)? (FROM patternSource)? ) ; */ -lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN (positionalConstraints? constraints? ) RPAREN (DRL_FROM patternSource)? ; +lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN (DRL_FROM patternSource)? ; positionalConstraints : constraint (COMMA constraint)* SEMI ; constraints : constraint (COMMA constraint)* ; constraint : label? ( nestedConstraint | conditionalOrExpression ) ; @@ -198,6 +198,7 @@ drlPrimary | typeTypeOrVoid DOT CLASS | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) | inlineListExpression + | inlineMapExpression ; /* extending JavaParser literal */ @@ -219,6 +220,18 @@ expressionList : drlExpression (COMMA drlExpression)* ; +inlineMapExpression + : LBRACK mapExpressionList RBRACK + ; + +mapExpressionList + : mapEntry (COMMA mapEntry)* + ; + +mapEntry + : drlExpression COLON drlExpression + ; + /* patternSource := FROM ( fromAccumulate diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 28775cfa8d9..a152733d179 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -214,7 +214,6 @@ public Object visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { return ctx.getText(); } - @Override public Object visitDrlLiteral(DRLParser.DrlLiteralContext ctx) { ParseTree node = ctx; @@ -277,6 +276,22 @@ public Object visitLhsNot(DRLParser.LhsNotContext ctx) { } } + @Override + public Object visitLhsOr(DRLParser.LhsOrContext ctx) { + if (!ctx.DRL_OR().isEmpty()) { + OrDescr orDescr = new OrDescr(); + currentConstructStack.peek().addDescr(orDescr); + currentConstructStack.push(orDescr); + try { + return super.visitLhsOr(ctx); + } finally { + currentConstructStack.pop(); + } + } else { + return super.visitLhsOr(ctx); + } + } + public PackageDescr getPackageDescr() { return packageDescr; } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 48d3460f62a..596aa5f926c 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -20,6 +20,7 @@ import org.drools.drl.ast.descr.FunctionImportDescr; import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.ImportDescr; +import org.drools.drl.ast.descr.MVELExprDescr; import org.drools.drl.ast.descr.NotDescr; import org.drools.drl.ast.descr.OrDescr; import org.drools.drl.ast.descr.PackageDescr; @@ -681,4 +682,139 @@ public void testConsequenceWithDeclaration() throws Exception { assertTrue( ((String) rule.getConsequence()).indexOf( "i++" ) > 0 ); // note, need to assert that "i++" is preserved as is, no extra spaces. } + + @Test + public void testRuleParseLhs() throws Exception { + final String text = "rule X when Person(age < 42, location==\"atlanta\") \nor\nPerson(name==\"bob\") then end"; + PackageDescr pkg = parser.parse(text); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + + assertNotNull(rule); + + AndDescr lhs = rule.getLhs(); + assertEquals(1, + lhs.getDescrs().size()); + assertEquals(2, + ((OrDescr) lhs.getDescrs().get(0)).getDescrs().size()); + } + + @Test + public void testRuleParseLhsWithStringQuotes() throws Exception { + final String text = "rule X when Person( location==\"atlanta\\\"\") then end\n"; + PackageDescr pkg = parser.parse(text); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + + assertNotNull(rule); + + AndDescr lhs = rule.getLhs(); + ExprConstraintDescr constr = (ExprConstraintDescr) ((PatternDescr) lhs.getDescrs().get(0)).getDescrs().get(0); + + assertThat(constr.getText()).isEqualToIgnoringWhitespace("location==\"atlanta\\\"\""); + } + + @Test + public void testRuleParseLhsWithStringQuotes2() throws Exception { + final String text = "rule X when Cheese( $x: type, type == \"s\\tti\\\"lto\\nn\" ) then end\n"; + PackageDescr pkg = parser.parse(text); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + + assertNotNull(rule); + + AndDescr lhs = rule.getLhs(); + ExprConstraintDescr constr = (ExprConstraintDescr) ((PatternDescr) lhs.getDescrs().get(0)).getDescrs().get(1); + + assertThat(constr.getText()).isEqualToIgnoringWhitespace("type == \"s\\tti\\\"lto\\nn\""); + } + + @Test + public void testLiteralBoolAndNegativeNumbersRule() throws Exception { + String source = readResource("literal_bool_and_negative.drl"); + PackageDescr pkg = parser.parse(source); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + + assertNotNull(rule); + + assertEquals("simple_rule", + rule.getName()); + assertNotNull(rule.getLhs()); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("cons();"); + + final AndDescr lhs = rule.getLhs(); + assertEquals(3, + lhs.getDescrs().size()); + + PatternDescr pattern = (PatternDescr) lhs.getDescrs().get(0); + assertEquals(1, + pattern.getConstraint().getDescrs().size()); + AndDescr fieldAnd = (AndDescr) pattern.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == false"); + + pattern = (PatternDescr) lhs.getDescrs().get(1); + assertEquals(1, + pattern.getConstraint().getDescrs().size()); + + fieldAnd = (AndDescr) pattern.getConstraint(); + fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + + assertThat(fld.getText()).isEqualToIgnoringWhitespace("boo > -42"); + + pattern = (PatternDescr) lhs.getDescrs().get(2); + assertEquals(1, + pattern.getConstraint().getDescrs().size()); + + fieldAnd = (AndDescr) pattern.getConstraint(); + fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + + assertThat(fld.getText()).isEqualToIgnoringWhitespace("boo > -42.42"); + } + + @Test + public void testEmptyPattern() throws Exception { + String source = readResource("test_EmptyPattern.drl"); + PackageDescr pkg = parser.parse(source); + + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + + assertEquals(1, + pkg.getRules().size()); + final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get(0); + assertEquals("simple rule", + ruleDescr.getName()); + assertNotNull(ruleDescr.getLhs()); + assertEquals(1, + ruleDescr.getLhs().getDescrs().size()); + final PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + assertEquals(0, + patternDescr.getConstraint().getDescrs().size()); // this + assertEquals("Cheese", + patternDescr.getObjectType()); + } + + @Test + public void testSimpleMethodCallWithFrom() throws Exception { + String source = readResource("test_SimpleMethodCallWithFrom.drl"); + PackageDescr pkg = parser.parse(source); + assertFalse(parser.getErrors().toString(), + parser.hasErrors()); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr method = (MVELExprDescr) from.getDataSource(); + + assertThat(method.getExpression()).isEqualToIgnoringWhitespace("something.doIt( foo,bar,42,\"hello\",[ a : \"b\", \"something\" : 42, \"a\" : foo, x : [x:y]],\"end\", [a, \"b\", 42] )"); + } } diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/literal_bool_and_negative.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/literal_bool_and_negative.drl new file mode 100644 index 00000000000..ce6ee78c0c6 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/literal_bool_and_negative.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +//check that it can handle true/false literals, and +//negative numbers +rule simple_rule + when + Foo(bar == false) + Foo(boo > -42) + Foo(boo > -42.42) + then + cons(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EmptyPattern.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EmptyPattern.drl new file mode 100644 index 00000000000..0c70f0ce121 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EmptyPattern.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +rule "simple rule" + when + Cheese( ) + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleMethodCallWithFrom.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleMethodCallWithFrom.drl new file mode 100644 index 00000000000..8c6b5be3be4 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleMethodCallWithFrom.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule blah + + when + + Col1() from something.doIt( foo,bar,42,"hello",[ a : "b", "something" : 42, "a" : foo, x : [x:y]],"end", [a, "b", 42] ) + Col2() + then + partay(); +end From 108e0f2d55fc7954d3f859d956a97097efe67772 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 30 Nov 2022 19:09:35 +0900 Subject: [PATCH 023/141] OpenRewrite applied for junit5 and assertj (#14) --- drools-drl/drools-drl10-parser/pom.xml | 18 +- .../java/org/drools/parser/DRLParserTest.java | 116 ++-- .../org/drools/parser/MiscDRLParserTest.java | 582 +++++++----------- 3 files changed, 295 insertions(+), 421 deletions(-) diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml index 31e015289c6..a3f638cc1c4 100644 --- a/drools-drl/drools-drl10-parser/pom.xml +++ b/drools-drl/drools-drl10-parser/pom.xml @@ -46,18 +46,24 @@ - - junit - junit - ${version.junit} - test - org.assertj assertj-core ${version.org.assertj} test + + org.junit.jupiter + junit-jupiter-api + ${version.org.junit} + test + + + org.junit.jupiter + junit-jupiter-engine + ${version.org.junit} + test + ch.qos.logback logback-classic diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java index 1330e7ed509..cec1ac92b47 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java @@ -2,92 +2,98 @@ import java.util.List; -import org.drools.drl.ast.descr.*; -import org.junit.Test; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.drools.parser.DRLParserHelper.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.drools.parser.DRLParserHelper.computeTokenIndex; +import static org.drools.parser.DRLParserHelper.createDrlParser; +import static org.drools.parser.DRLParserHelper.parse; -public class DRLParserTest { +class DRLParserTest { private static final String drl = "package org.test;\n" + - "import org.test.model.Person;\n" + - "global String result;\n" + - "rule TestRule @Test(true) no-loop salience 15 when \n" + - " $p:Person( age >= 18 )\n" + - "then\n" + - " int a = 4;\n" + - " System.out.println($p.getName());\n" + - "end\n"; + "import org.test.model.Person;\n" + + "global String result;\n" + + "rule TestRule @Test(true) no-loop salience 15 when \n" + + " $p:Person( age >= 18 )\n" + + "then\n" + + " int a = 4;\n" + + " System.out.println($p.getName());\n" + + "end\n"; @Test - public void testParse() { + void testParse() { PackageDescr packageDescr = parse(drl); - assertEquals("org.test", packageDescr.getName()); + assertThat(packageDescr.getName()).isEqualTo("org.test"); - assertEquals(1, packageDescr.getImports().size()); - assertEquals("org.test.model.Person", packageDescr.getImports().get(0).getTarget()); + assertThat(packageDescr.getImports().size()).isEqualTo(1); + assertThat(packageDescr.getImports().get(0).getTarget()).isEqualTo("org.test.model.Person"); - assertEquals(1, packageDescr.getGlobals().size()); + assertThat(packageDescr.getGlobals().size()).isEqualTo(1); GlobalDescr globalDescr = packageDescr.getGlobals().get(0); - assertEquals("String", globalDescr.getType()); - assertEquals("result", globalDescr.getIdentifier()); + assertThat(globalDescr.getType()).isEqualTo("String"); + assertThat(globalDescr.getIdentifier()).isEqualTo("result"); - assertEquals(1, packageDescr.getRules().size()); + assertThat(packageDescr.getRules().size()).isEqualTo(1); RuleDescr ruleDescr = packageDescr.getRules().get(0); AnnotationDescr annotationDescr = ruleDescr.getAnnotation("Test"); - assertNotNull(annotationDescr); - assertEquals("true", annotationDescr.getValue()); + assertThat(annotationDescr).isNotNull(); + assertThat(annotationDescr.getValue()).isEqualTo("true"); - assertEquals(2, ruleDescr.getAttributes().size()); - assertNotNull(ruleDescr.getAttributes().get("no-loop")); + assertThat(ruleDescr.getAttributes().size()).isEqualTo(2); + assertThat(ruleDescr.getAttributes().get("no-loop")).isNotNull(); AttributeDescr salience = ruleDescr.getAttributes().get("salience"); - assertNotNull(salience); - assertEquals("15", salience.getValue()); + assertThat(salience).isNotNull(); + assertThat(salience.getValue()).isEqualTo("15"); - assertEquals("TestRule", ruleDescr.getName()); + assertThat(ruleDescr.getName()).isEqualTo("TestRule"); - assertEquals(1, ruleDescr.getLhs().getDescrs().size()); + assertThat(ruleDescr.getLhs().getDescrs().size()).isEqualTo(1); PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); - assertEquals("$p", patternDescr.getIdentifier()); - assertEquals("Person", patternDescr.getObjectType()); + assertThat(patternDescr.getIdentifier()).isEqualTo("$p"); + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); List constraints = patternDescr.getConstraint().getDescrs(); - assertEquals(1, constraints.size()); + assertThat(constraints.size()).isEqualTo(1); ExprConstraintDescr expr = (ExprConstraintDescr) constraints.get(0); - assertEquals("age >= 18", expr.getExpression()); + assertThat(expr.getExpression()).isEqualTo("age >= 18"); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int a = 4; System.out.println($p.getName());"); } @Test - public void testComputeTokenIndex() { + void testComputeTokenIndex() { DRLParser parser = createDrlParser(drl); parser.compilationUnit(); - assertEquals(0, (int) computeTokenIndex(parser, 1, 0)); - assertEquals(0, (int) computeTokenIndex(parser, 1, 1)); - assertEquals(0, (int) computeTokenIndex(parser, 1, 7)); - assertEquals(1, (int) computeTokenIndex(parser, 1, 8)); - assertEquals(2, (int) computeTokenIndex(parser, 1, 9)); - assertEquals(2, (int) computeTokenIndex(parser, 1, 9)); - assertEquals(3, (int) computeTokenIndex(parser, 1, 12)); - assertEquals(4, (int) computeTokenIndex(parser, 1, 13)); - assertEquals(5, (int) computeTokenIndex(parser, 1, 17)); - assertEquals(6, (int) computeTokenIndex(parser, 1, 18)); - assertEquals(6, (int) computeTokenIndex(parser, 2, 0)); - assertEquals(7, (int) computeTokenIndex(parser, 2, 1)); - assertEquals(7, (int) computeTokenIndex(parser, 2, 6)); - assertEquals(8, (int) computeTokenIndex(parser, 2, 7)); - assertEquals(80, (int) computeTokenIndex(parser, 9, 0)); - assertEquals(81, (int) computeTokenIndex(parser, 9, 1)); - assertEquals(82, (int) computeTokenIndex(parser, 9, 4)); - assertEquals(82, (int) computeTokenIndex(parser, 9, 5)); - assertEquals(82, (int) computeTokenIndex(parser, 10, 0)); // EOF + assertThat((int) computeTokenIndex(parser, 1, 0)).isEqualTo(0); + assertThat((int) computeTokenIndex(parser, 1, 1)).isEqualTo(0); + assertThat((int) computeTokenIndex(parser, 1, 7)).isEqualTo(0); + assertThat((int) computeTokenIndex(parser, 1, 8)).isEqualTo(1); + assertThat((int) computeTokenIndex(parser, 1, 9)).isEqualTo(2); + assertThat((int) computeTokenIndex(parser, 1, 9)).isEqualTo(2); + assertThat((int) computeTokenIndex(parser, 1, 12)).isEqualTo(3); + assertThat((int) computeTokenIndex(parser, 1, 13)).isEqualTo(4); + assertThat((int) computeTokenIndex(parser, 1, 17)).isEqualTo(5); + assertThat((int) computeTokenIndex(parser, 1, 18)).isEqualTo(6); + assertThat((int) computeTokenIndex(parser, 2, 0)).isEqualTo(6); + assertThat((int) computeTokenIndex(parser, 2, 1)).isEqualTo(7); + assertThat((int) computeTokenIndex(parser, 2, 6)).isEqualTo(7); + assertThat((int) computeTokenIndex(parser, 2, 7)).isEqualTo(8); + assertThat((int) computeTokenIndex(parser, 9, 0)).isEqualTo(80); + assertThat((int) computeTokenIndex(parser, 9, 1)).isEqualTo(81); + assertThat((int) computeTokenIndex(parser, 9, 4)).isEqualTo(82); + assertThat((int) computeTokenIndex(parser, 9, 5)).isEqualTo(82); + assertThat((int) computeTokenIndex(parser, 10, 0)).isEqualTo(82); // EOF } - } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 596aa5f926c..77f2485ae46 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -2,15 +2,11 @@ import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import junit.framework.TestCase; -import org.assertj.core.api.Assertions; import org.drools.drl.ast.descr.AndDescr; import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; @@ -26,28 +22,26 @@ import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.ast.descr.PatternDescr; import org.drools.drl.ast.descr.RuleDescr; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /* * This test class is being ported from org.drools.mvel.compiler.lang.RuleParserTest */ -public class MiscDRLParserTest extends TestCase { +class MiscDRLParserTest { private DRLParserWrapper parser; - @Before - protected void setUp() throws Exception { - super.setUp(); + @BeforeEach + public void setUp() { parser = new DRLParserWrapper(); } - @After - protected void tearDown() throws Exception { - super.tearDown(); + @AfterEach + public void tearDown() { } private String readResource(final String filename) throws Exception { @@ -64,202 +58,151 @@ private String readResource(final String filename) throws Exception { } @Test - public void testPackage() throws Exception { + void testPackage() { final String source = "package foo.bar.baz"; final PackageDescr pkg = parser.parse(source); - assertEquals("foo.bar.baz", pkg.getName()); + assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); } @Test - public void testPackageWithErrorNode() throws Exception { + void testPackageWithErrorNode() { final String source = "package 12 foo.bar.baz"; final PackageDescr pkg = parser.parse(source); - assertTrue(parser.hasErrors()); - assertEquals("foo.bar.baz", pkg.getName()); + assertThat(parser.hasErrors()).isTrue(); + assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); } @Test - public void testPackageWithAllErrorNode() throws Exception { + void testPackageWithAllErrorNode() { final String source = "package 12 12312 231"; final PackageDescr pkg = parser.parse(source); - assertTrue(parser.hasErrors()); - assertEquals("", pkg.getName()); + assertThat(parser.hasErrors()).isTrue(); + assertThat(pkg.getName()).isEqualTo(""); } @Test - public void testCompilationUnit() throws Exception { + void testCompilationUnit() { final String source = "package foo; import com.foo.Bar; import com.foo.Baz;"; PackageDescr pkg = parser.parse(source); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); - assertEquals("foo", - pkg.getName()); - assertEquals(2, - pkg.getImports().size()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(pkg.getName()).isEqualTo("foo"); + assertThat(pkg.getImports().size()).isEqualTo(2); ImportDescr impdescr = pkg.getImports().get(0); - assertEquals("com.foo.Bar", - impdescr.getTarget()); - assertEquals(source.indexOf("import " + impdescr.getTarget()), - impdescr.getStartCharacter()); - assertEquals(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length(), - impdescr.getEndCharacter()); + assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); impdescr = pkg.getImports().get(1); - assertEquals("com.foo.Baz", - impdescr.getTarget()); - assertEquals(source.indexOf("import " + impdescr.getTarget()), - impdescr.getStartCharacter()); - assertEquals(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length(), - impdescr.getEndCharacter()); + assertThat(impdescr.getTarget()).isEqualTo("com.foo.Baz"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); } @Test - public void testFunctionImport() throws Exception { + void testFunctionImport() { final String source = "package foo\n" + "import function java.lang.Math.max\n" + "import function java.lang.Math.min;\n" + "import foo.bar.*\n" + "import baz.Baz"; PackageDescr pkg = parser.parse(source); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); - assertEquals("foo", - pkg.getName()); - assertEquals(2, - pkg.getImports().size()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(pkg.getName()).isEqualTo("foo"); + assertThat(pkg.getImports().size()).isEqualTo(2); ImportDescr impdescr = pkg.getImports().get(0); - assertEquals("foo.bar.*", - impdescr.getTarget()); - assertEquals(source.indexOf("import " + impdescr.getTarget()), - impdescr.getStartCharacter()); + assertThat(impdescr.getTarget()).isEqualTo("foo.bar.*"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); - assertEquals(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1, - impdescr.getEndCharacter()); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); impdescr = pkg.getImports().get(1); - assertEquals("baz.Baz", - impdescr.getTarget()); - assertEquals(source.indexOf("import " + impdescr.getTarget()), - impdescr.getStartCharacter()); - assertEquals(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1, - impdescr.getEndCharacter()); - - assertEquals(2, - pkg.getFunctionImports().size()); + assertThat(impdescr.getTarget()).isEqualTo("baz.Baz"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); + + assertThat(pkg.getFunctionImports().size()).isEqualTo(2); impdescr = pkg.getFunctionImports().get(0); - assertEquals("java.lang.Math.max", - impdescr.getTarget()); - assertEquals(source.indexOf("import function " + impdescr.getTarget()), - impdescr.getStartCharacter()); - assertEquals(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length() - 1, - impdescr.getEndCharacter()); + assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.max"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length() - 1); impdescr = pkg.getFunctionImports().get(1); - assertEquals("java.lang.Math.min", - impdescr.getTarget()); - assertEquals(source.indexOf("import function " + impdescr.getTarget()), - impdescr.getStartCharacter()); - assertEquals(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length(), - impdescr.getEndCharacter()); + assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.min"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length()); } @Test - public void testGlobalWithComplexType() throws Exception { + void testGlobalWithComplexType() { final String source = "package foo.bar.baz\n" + "import com.foo.Bar\n" + "global java.util.List> aList;\n" + "global Integer aNumber"; PackageDescr pkg = parser.parse(source); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); - assertEquals("foo.bar.baz", - pkg.getName()); - assertEquals(1, - pkg.getImports().size()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); + assertThat(pkg.getImports().size()).isEqualTo(1); ImportDescr impdescr = pkg.getImports().get(0); - assertEquals("com.foo.Bar", - impdescr.getTarget()); - assertEquals(source.indexOf("import " + impdescr.getTarget()), - impdescr.getStartCharacter()); - assertEquals(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1, - impdescr.getEndCharacter()); + assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); - assertEquals(2, - pkg.getGlobals().size()); + assertThat(pkg.getGlobals().size()).isEqualTo(2); GlobalDescr global = pkg.getGlobals().get(0); - assertEquals("java.util.List>", - global.getType()); - assertEquals("aList", - global.getIdentifier()); - assertEquals(source.indexOf("global " + global.getType()), - global.getStartCharacter()); - assertEquals(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + - ("global " + global.getType() + " " + global.getIdentifier()).length(), - global.getEndCharacter()); + assertThat(global.getType()).isEqualTo("java.util.List>"); + assertThat(global.getIdentifier()).isEqualTo("aList"); + assertThat(global.getStartCharacter()).isEqualTo(source.indexOf("global " + global.getType())); + assertThat(global.getEndCharacter()).isEqualTo(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + + ("global " + global.getType() + " " + global.getIdentifier()).length()); global = pkg.getGlobals().get(1); - assertEquals("Integer", - global.getType()); - assertEquals("aNumber", - global.getIdentifier()); - assertEquals(source.indexOf("global " + global.getType()), - global.getStartCharacter()); - assertEquals(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + - ("global " + global.getType() + " " + global.getIdentifier()).length() - 1, - global.getEndCharacter()); + assertThat(global.getType()).isEqualTo("Integer"); + assertThat(global.getIdentifier()).isEqualTo("aNumber"); + assertThat(global.getStartCharacter()).isEqualTo(source.indexOf("global " + global.getType())); + assertThat(global.getEndCharacter()).isEqualTo(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + + ("global " + global.getType() + " " + global.getIdentifier()).length() - 1); } @Test - public void testGlobalWithOrWithoutSemi() throws Exception { + void testGlobalWithOrWithoutSemi() throws Exception { String source = readResource("globals.drl"); PackageDescr pkg = parser.parse(source); - assertEquals(1, - pkg.getRules().size()); + assertThat(pkg.getRules().size()).isEqualTo(1); final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertEquals(1, - rule.getLhs().getDescrs().size()); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - assertEquals(1, - pkg.getImports().size()); - assertEquals(2, - pkg.getGlobals().size()); + assertThat(pkg.getImports().size()).isEqualTo(1); + assertThat(pkg.getGlobals().size()).isEqualTo(2); final GlobalDescr foo = (GlobalDescr) pkg.getGlobals().get(0); - assertEquals("java.lang.String", - foo.getType()); - assertEquals("foo", - foo.getIdentifier()); + assertThat(foo.getType()).isEqualTo("java.lang.String"); + assertThat(foo.getIdentifier()).isEqualTo("foo"); final GlobalDescr bar = (GlobalDescr) pkg.getGlobals().get(1); - assertEquals("java.lang.Integer", - bar.getType()); - assertEquals("bar", - bar.getIdentifier()); + assertThat(bar.getType()).isEqualTo("java.lang.Integer"); + assertThat(bar.getIdentifier()).isEqualTo("bar"); } @Test - public void testFunctionImportWithNotExist() throws Exception { + void testFunctionImportWithNotExist() throws Exception { String source = readResource("test_FunctionImport.drl"); PackageDescr pkg = parser.parse(source); - assertEquals(2, - pkg.getFunctionImports().size()); + assertThat(pkg.getFunctionImports().size()).isEqualTo(2); - assertEquals("abd.def.x", - ((FunctionImportDescr) pkg.getFunctionImports().get(0)).getTarget()); - assertFalse(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getStartCharacter() == -1); - assertFalse(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getEndCharacter() == -1); - assertEquals("qed.wah.*", - ((FunctionImportDescr) pkg.getFunctionImports().get(1)).getTarget()); - assertFalse(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getStartCharacter() == -1); - assertFalse(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getEndCharacter() == -1); + assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getTarget()).isEqualTo("abd.def.x"); + assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getStartCharacter() == -1).isFalse(); + assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getEndCharacter() == -1).isFalse(); + assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getTarget()).isEqualTo("qed.wah.*"); + assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getStartCharacter() == -1).isFalse(); + assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getEndCharacter() == -1).isFalse(); } @Test - public void testFromComplexAcessor() throws Exception { + void testFromComplexAcessor() { String source = "rule \"Invalid customer id\" ruleflow-group \"validate\" lock-on-active true \n" + " when \n" + " o: Order( ) \n" + @@ -271,27 +214,22 @@ public void testFromComplexAcessor() throws Exception { "end \n"; PackageDescr pkg = parser.parse(source); - assertFalse(parser.getErrorMessages().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertEquals("Invalid customer id", - rule.getName()); + assertThat(rule.getName()).isEqualTo("Invalid customer id"); - assertEquals(2, - rule.getLhs().getDescrs().size()); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(1); PatternDescr customer = (PatternDescr) not.getDescrs().get(0); - assertEquals("Customer", - customer.getObjectType()); - assertEquals("customerService.getCustomer(o.getCustomerId())", - ((FromDescr) customer.getSource()).getDataSource().getText()); + assertThat(customer.getObjectType()).isEqualTo("Customer"); + assertThat(((FromDescr) customer.getSource()).getDataSource().getText()).isEqualTo("customerService.getCustomer(o.getCustomerId())"); } @Test - public void testFromWithInlineList() throws Exception { + void testFromWithInlineList() { String source = "rule XYZ \n" + " when \n" + " o: Order( ) \n" + @@ -301,19 +239,17 @@ public void testFromWithInlineList() throws Exception { " o.addError(\"Invalid customer id\"); \n" + "end \n"; PackageDescr pkg = parser.parse(source); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertEquals("XYZ", - rule.getName()); + assertThat(rule.getName()).isEqualTo("XYZ"); PatternDescr number = (PatternDescr) ((NotDescr) rule.getLhs().getDescrs().get(1)).getDescrs().get(0); assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3]"); } @Test - public void testFromWithInlineListMethod() throws Exception { + void testFromWithInlineListMethod() { String source = "rule XYZ \n" + " when \n" + " o: Order( ) \n" + @@ -323,21 +259,19 @@ public void testFromWithInlineListMethod() throws Exception { " o.addError(\"Invalid customer id\"); \n" + "end \n"; PackageDescr pkg = parser.parse(source); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertEquals("XYZ", - rule.getName()); + assertThat(rule.getName()).isEqualTo("XYZ"); - assertFalse(parser.hasErrors()); + assertThat(parser.hasErrors()).isFalse(); PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3].sublist(1, 2)"); } @Test - public void testFromWithInlineListIndex() throws Exception { + void testFromWithInlineListIndex() { String source = "rule XYZ \n" + " when \n" + " o: Order( ) \n" + @@ -348,31 +282,29 @@ public void testFromWithInlineListIndex() throws Exception { "end \n"; PackageDescr pkg = parser.parse(source); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertEquals("XYZ", - rule.getName()); + assertThat(rule.getName()).isEqualTo("XYZ"); - assertFalse(parser.hasErrors()); + assertThat(parser.hasErrors()).isFalse(); PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3][1]"); } @Test - public void testRuleWithoutEnd() throws Exception { + void testRuleWithoutEnd() { String source = "rule \"Invalid customer id\" \n" + " when \n" + " o: Order( ) \n" + " then \n" + " System.err.println(\"Invalid customer id found!\"); \n"; parser.parse(source); - assertTrue(parser.hasErrors()); + assertThat(parser.hasErrors()).isTrue(); } @Test - public void testOrWithSpecialBind() throws Exception { + void testOrWithSpecialBind() { String source = "rule \"A and (B or C or D)\" \n" + " when \n" + " pdo1 : ParametricDataObject( paramID == 101, stringValue == \"1000\" ) and \n" + @@ -383,122 +315,98 @@ public void testOrWithSpecialBind() throws Exception { " System.out.println( \"Rule: A and (B or C or D) Fired. pdo1: \" + pdo1 + \" pdo2: \"+ pdo2); \n" + "end\n"; PackageDescr pkg = parser.parse(source); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = pkg.getRules().get(0); AndDescr lhs = rule.getLhs(); - assertEquals(2, - lhs.getDescrs().size()); + assertThat(lhs.getDescrs().size()).isEqualTo(2); PatternDescr pdo1 = (PatternDescr) lhs.getDescrs().get(0); - assertEquals("pdo1", - pdo1.getIdentifier()); + assertThat(pdo1.getIdentifier()).isEqualTo("pdo1"); OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(1); - assertEquals(3, - or.getDescrs().size()); + assertThat(or.getDescrs().size()).isEqualTo(3); for (BaseDescr pdo2 : or.getDescrs()) { - assertEquals("pdo2", - ((PatternDescr) pdo2).getIdentifier()); + assertThat(((PatternDescr) pdo2).getIdentifier()).isEqualTo("pdo2"); } } @Test - public void testCompatibleRestriction() throws Exception { + void testCompatibleRestriction() { String source = "package com.sample rule test when Test( ( text == null || text2 matches \"\" ) ) then end"; PackageDescr pkg = parser.parse(source); - assertEquals( "com.sample", - pkg.getName() ); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertEquals( "test", - rule.getName() ); - ExprConstraintDescr expr = (ExprConstraintDescr) ((PatternDescr) rule.getLhs().getDescrs().get(0 )).getDescrs().get(0 ); - assertEquals( "( text == null || text2 matches \"\" )", - expr.getText() ); + assertThat(pkg.getName()).isEqualTo("com.sample"); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("test"); + ExprConstraintDescr expr = (ExprConstraintDescr) ((PatternDescr) rule.getLhs().getDescrs().get(0)).getDescrs().get(0); + assertThat(expr.getText()).isEqualTo("( text == null || text2 matches \"\" )"); } @Test - public void testSimpleConstraint() throws Exception { + void testSimpleConstraint() { String source = "package com.sample rule test when Cheese( type == 'stilton', price > 10 ) then end"; PackageDescr pkg = parser.parse(source); - assertEquals( "com.sample", - pkg.getName() ); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertEquals( "test", - rule.getName() ); + assertThat(pkg.getName()).isEqualTo("com.sample"); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("test"); - assertEquals( 1, - rule.getLhs().getDescrs().size() ); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); AndDescr constraint = (AndDescr) pattern.getConstraint(); - assertEquals( 2, - constraint.getDescrs().size() ); - assertEquals( "type == \"stilton\"", - constraint.getDescrs().get( 0 ).toString() ); - assertEquals( "price > 10", - constraint.getDescrs().get( 1 ).toString() ); + assertThat(constraint.getDescrs().size()).isEqualTo(2); + assertThat(constraint.getDescrs().get(0).toString()).isEqualTo("type == \"stilton\""); + assertThat(constraint.getDescrs().get(1).toString()).isEqualTo("price > 10"); } @Test - public void testStringEscapes() throws Exception { + void testStringEscapes() { String source = "package com.sample rule test when Cheese( type matches \"\\..*\\\\.\" ) then end"; PackageDescr pkg = parser.parse(source); - assertEquals( "com.sample", - pkg.getName() ); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertEquals( "test", - rule.getName() ); + assertThat(pkg.getName()).isEqualTo("com.sample"); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("test"); - assertEquals( 1, - rule.getLhs().getDescrs().size() ); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); AndDescr constraint = (AndDescr) pattern.getConstraint(); - assertEquals( 1, - constraint.getDescrs().size() ); - assertEquals( "type matches \"\\..*\\\\.\"", - constraint.getDescrs().get( 0 ).toString() ); + assertThat(constraint.getDescrs().size()).isEqualTo(1); + assertThat(constraint.getDescrs().get(0).toString()).isEqualTo("type matches \"\\..*\\\\.\""); } @Test - public void testDialect() throws Exception { + void testDialect() { final String source = "dialect 'mvel'"; PackageDescr pkg = parser.parse(source); AttributeDescr attr = (AttributeDescr) pkg.getAttributes().get(0); - assertEquals("dialect", - attr.getName()); - assertEquals("mvel", - attr.getValue()); + assertThat(attr.getName()).isEqualTo("dialect"); + assertThat(attr.getValue()).isEqualTo("mvel"); } @Test - public void testDialect2() throws Exception { + void testDialect2() { final String source = "dialect \"mvel\""; PackageDescr pkg = parser.parse(source); AttributeDescr attr = pkg.getAttributes().get(0); - assertEquals("dialect", - attr.getName()); - assertEquals("mvel", - attr.getValue()); + assertThat(attr.getName()).isEqualTo("dialect"); + assertThat(attr.getValue()).isEqualTo("mvel"); } @Test - public void testEmptyRuleWithoutWhen() throws Exception { + void testEmptyRuleWithoutWhen() throws Exception { String source = readResource("empty_rule.drl"); // without WHEN PackageDescr pkg = parser.parse(source); - assertTrue(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isTrue(); // Note : RuleParserTest.testEmptyRule allows this DRL, but I think is doesn't make sense to pass this DRL } @Test - public void testKeywordCollisions() throws Exception { + void testKeywordCollisions() throws Exception { String source = readResource("eol_funny_business.drl"); // keywords everywhere // Note: eol_funny_business.drl is modified from the one under drools-test-coverage to be more realistic. @@ -506,27 +414,24 @@ public void testKeywordCollisions() throws Exception { PackageDescr pkg = parser.parse(source); - assertFalse( parser.getErrors().toString(), - parser.hasErrors() ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertEquals( 1, - pkg.getRules().size() ); + assertThat(pkg.getRules().size()).isEqualTo(1); } @Test - public void testTernaryExpression() throws Exception { + void testTernaryExpression() throws Exception { String source = readResource("ternary_expression.drl"); PackageDescr pkg = parser.parse(source); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertEquals( 1, - pkg.getRules().size() ); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(pkg.getRules().size()).isEqualTo(1); assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if (speed > speedLimit ? true : false;) pullEmOver();"); } @Test - public void testFunctionWithArrays() throws Exception { + void testFunctionWithArrays() throws Exception { String source = readResource("function_arrays.drl"); // Note: function_arrays.drl is modified from the one under drools-test-coverage to be more realistic. @@ -535,137 +440,112 @@ public void testFunctionWithArrays() throws Exception { PackageDescr pkg = parser.parse(source); - assertEquals( "foo", - pkg.getName() ); - assertEquals( 1, - pkg.getRules().size() ); + assertThat(pkg.getName()).isEqualTo("foo"); + assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("yourFunction(new String[] {\"a\",\"b\",\"c\"});"); - final FunctionDescr func = (FunctionDescr) pkg.getFunctions().get(0 ); + final FunctionDescr func = (FunctionDescr) pkg.getFunctions().get(0); - assertEquals( "String[]", - func.getReturnType() ); - assertEquals( "args[]", - func.getParameterNames().get( 0 ) ); - assertEquals( "String", - func.getParameterTypes().get( 0 ) ); + assertThat(func.getReturnType()).isEqualTo("String[]"); + assertThat(func.getParameterNames().get(0)).isEqualTo("args[]"); + assertThat(func.getParameterTypes().get(0)).isEqualTo("String"); } @Test - public void testAlmostEmptyRule() throws Exception { + void testAlmostEmptyRule() throws Exception { String source = readResource("almost_empty_rule.drl"); PackageDescr pkg = parser.parse(source); - assertFalse( parser.getErrors().toString(), - parser.hasErrors() ); - assertNotNull( pkg ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(pkg).isNotNull(); - RuleDescr rule = pkg.getRules().get( 0 ); + RuleDescr rule = pkg.getRules().get(0); - assertEquals( "almost_empty", - rule.getName() ); - assertNotNull( rule.getLhs() ); - assertEquals( "", - ((String) rule.getConsequence()).trim() ); + assertThat(rule.getName()).isEqualTo("almost_empty"); + assertThat(rule.getLhs()).isNotNull(); + assertThat(((String) rule.getConsequence()).trim()).isEqualTo(""); } @Test - public void testQuotedStringNameRule() throws Exception { + void testQuotedStringNameRule() throws Exception { String source = readResource("quoted_string_name_rule.drl"); PackageDescr pkg = parser.parse(source); - assertFalse( parser.getErrors().toString(), - parser.hasErrors() ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = pkg.getRules().get(0); - assertNotNull( rule ); + assertThat(rule).isNotNull(); - assertEquals( "quoted string name", - rule.getName() ); - assertNotNull( rule.getLhs() ); - assertEquals( "", - ((String) rule.getConsequence()).trim() ); + assertThat(rule.getName()).isEqualTo("quoted string name"); + assertThat(rule.getLhs()).isNotNull(); + assertThat(((String) rule.getConsequence()).trim()).isEqualTo(""); } @Test - public void testNoLoop() throws Exception { + void testNoLoop() throws Exception { String source = readResource("no-loop.drl"); PackageDescr pkg = parser.parse(source); - assertFalse( parser.getErrors().toString(), - parser.hasErrors() ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = pkg.getRules().get(0); - assertNotNull( rule ); + assertThat(rule).isNotNull(); - assertEquals( "rule1", - rule.getName() ); - final AttributeDescr att = (AttributeDescr) rule.getAttributes().get( "no-loop" ); - assertEquals( "false", - att.getValue() ); - assertEquals( "no-loop", - att.getName() ); + assertThat(rule.getName()).isEqualTo("rule1"); + final AttributeDescr att = (AttributeDescr) rule.getAttributes().get("no-loop"); + assertThat(att.getValue()).isEqualTo("false"); + assertThat(att.getName()).isEqualTo("no-loop"); } @Test - public void testAutofocus() throws Exception { + void testAutofocus() throws Exception { String source = readResource("autofocus.drl"); PackageDescr pkg = parser.parse(source); - assertFalse( parser.getErrors().toString(), - parser.hasErrors() ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = pkg.getRules().get(0); - assertNotNull( rule ); + assertThat(rule).isNotNull(); - assertEquals( "rule1", - rule.getName() ); - final AttributeDescr att = (AttributeDescr) rule.getAttributes().get( "auto-focus" ); - assertEquals( "true", - att.getValue() ); - assertEquals( "auto-focus", - att.getName() ); + assertThat(rule.getName()).isEqualTo("rule1"); + final AttributeDescr att = (AttributeDescr) rule.getAttributes().get("auto-focus"); + assertThat(att.getValue()).isEqualTo("true"); + assertThat(att.getName()).isEqualTo("auto-focus"); } @Test - public void testRuleFlowGroup() throws Exception { + void testRuleFlowGroup() throws Exception { String source = readResource("ruleflowgroup.drl"); PackageDescr pkg = parser.parse(source); - assertFalse( parser.getErrors().toString(), - parser.hasErrors() ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = pkg.getRules().get(0); - assertNotNull( rule ); + assertThat(rule).isNotNull(); - assertEquals( "rule1", - rule.getName() ); - final AttributeDescr att = (AttributeDescr) rule.getAttributes().get( "ruleflow-group" ); - assertEquals( "a group", - att.getValue() ); - assertEquals( "ruleflow-group", - att.getName() ); + assertThat(rule.getName()).isEqualTo("rule1"); + final AttributeDescr att = (AttributeDescr) rule.getAttributes().get("ruleflow-group"); + assertThat(att.getValue()).isEqualTo("a group"); + assertThat(att.getName()).isEqualTo("ruleflow-group"); } @Test - public void testConsequenceWithDeclaration() throws Exception { + void testConsequenceWithDeclaration() throws Exception { String source = readResource("declaration-in-consequence.drl"); PackageDescr pkg = parser.parse(source); // Note : Removed "i\i;" from the original declaration-in-consequence.drl under drools-test-coverage // because it's not a valid java expression and doesn't make sense to test. (Right to raise a parser error) - assertFalse( parser.getErrors().toString(), - parser.hasErrors() ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = pkg.getRules().get(0); - assertNotNull( rule ); + assertThat(rule).isNotNull(); - assertEquals( "myrule", - rule.getName() ); + assertThat(rule.getName()).isEqualTo("myrule"); final String expected = "int i = 0; i = 1; i / 1; i == 1; i(i); i = 'i'; i.i.i; ii; i=\"i\"; ++i;" + "i++; --i; i--; i += i; i -= i; i *= i; i /= i;" + @@ -675,42 +555,38 @@ public void testConsequenceWithDeclaration() throws Exception { "String s = (String) o;"; assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace(expected); - assertTrue( ((String) rule.getConsequence()).indexOf( "++" ) > 0 ); - assertTrue( ((String) rule.getConsequence()).indexOf( "--" ) > 0 ); - assertTrue( ((String) rule.getConsequence()).indexOf( "+=" ) > 0 ); - assertTrue( ((String) rule.getConsequence()).indexOf( "==" ) > 0 ); - assertTrue( ((String) rule.getConsequence()).indexOf( "i++" ) > 0 ); + assertThat(((String) rule.getConsequence()).indexOf("++") > 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("--") > 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("+=") > 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("==") > 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("i++") > 0).isTrue(); // note, need to assert that "i++" is preserved as is, no extra spaces. } @Test - public void testRuleParseLhs() throws Exception { + void testRuleParseLhs() { final String text = "rule X when Person(age < 42, location==\"atlanta\") \nor\nPerson(name==\"bob\") then end"; PackageDescr pkg = parser.parse(text); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertNotNull(rule); + assertThat(rule).isNotNull(); AndDescr lhs = rule.getLhs(); - assertEquals(1, - lhs.getDescrs().size()); - assertEquals(2, - ((OrDescr) lhs.getDescrs().get(0)).getDescrs().size()); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + assertThat(((OrDescr) lhs.getDescrs().get(0)).getDescrs().size()).isEqualTo(2); } @Test - public void testRuleParseLhsWithStringQuotes() throws Exception { + void testRuleParseLhsWithStringQuotes() { final String text = "rule X when Person( location==\"atlanta\\\"\") then end\n"; PackageDescr pkg = parser.parse(text); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertNotNull(rule); + assertThat(rule).isNotNull(); AndDescr lhs = rule.getLhs(); ExprConstraintDescr constr = (ExprConstraintDescr) ((PatternDescr) lhs.getDescrs().get(0)).getDescrs().get(0); @@ -719,14 +595,13 @@ public void testRuleParseLhsWithStringQuotes() throws Exception { } @Test - public void testRuleParseLhsWithStringQuotes2() throws Exception { + void testRuleParseLhsWithStringQuotes2() { final String text = "rule X when Cheese( $x: type, type == \"s\\tti\\\"lto\\nn\" ) then end\n"; PackageDescr pkg = parser.parse(text); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertNotNull(rule); + assertThat(rule).isNotNull(); AndDescr lhs = rule.getLhs(); ExprConstraintDescr constr = (ExprConstraintDescr) ((PatternDescr) lhs.getDescrs().get(0)).getDescrs().get(1); @@ -735,36 +610,31 @@ public void testRuleParseLhsWithStringQuotes2() throws Exception { } @Test - public void testLiteralBoolAndNegativeNumbersRule() throws Exception { + void testLiteralBoolAndNegativeNumbersRule() throws Exception { String source = readResource("literal_bool_and_negative.drl"); PackageDescr pkg = parser.parse(source); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertNotNull(rule); + assertThat(rule).isNotNull(); - assertEquals("simple_rule", - rule.getName()); - assertNotNull(rule.getLhs()); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs()).isNotNull(); assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("cons();"); final AndDescr lhs = rule.getLhs(); - assertEquals(3, - lhs.getDescrs().size()); + assertThat(lhs.getDescrs().size()).isEqualTo(3); PatternDescr pattern = (PatternDescr) lhs.getDescrs().get(0); - assertEquals(1, - pattern.getConstraint().getDescrs().size()); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); AndDescr fieldAnd = (AndDescr) pattern.getConstraint(); ExprConstraintDescr fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == false"); pattern = (PatternDescr) lhs.getDescrs().get(1); - assertEquals(1, - pattern.getConstraint().getDescrs().size()); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); fieldAnd = (AndDescr) pattern.getConstraint(); fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); @@ -772,8 +642,7 @@ public void testLiteralBoolAndNegativeNumbersRule() throws Exception { assertThat(fld.getText()).isEqualToIgnoringWhitespace("boo > -42"); pattern = (PatternDescr) lhs.getDescrs().get(2); - assertEquals(1, - pattern.getConstraint().getDescrs().size()); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); fieldAnd = (AndDescr) pattern.getConstraint(); fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); @@ -782,34 +651,27 @@ public void testLiteralBoolAndNegativeNumbersRule() throws Exception { } @Test - public void testEmptyPattern() throws Exception { + void testEmptyPattern() throws Exception { String source = readResource("test_EmptyPattern.drl"); PackageDescr pkg = parser.parse(source); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertEquals(1, - pkg.getRules().size()); + assertThat(pkg.getRules().size()).isEqualTo(1); final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get(0); - assertEquals("simple rule", - ruleDescr.getName()); - assertNotNull(ruleDescr.getLhs()); - assertEquals(1, - ruleDescr.getLhs().getDescrs().size()); + assertThat(ruleDescr.getName()).isEqualTo("simple rule"); + assertThat(ruleDescr.getLhs()).isNotNull(); + assertThat(ruleDescr.getLhs().getDescrs().size()).isEqualTo(1); final PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); - assertEquals(0, - patternDescr.getConstraint().getDescrs().size()); // this - assertEquals("Cheese", - patternDescr.getObjectType()); + assertThat(patternDescr.getConstraint().getDescrs().size()).isEqualTo(0); // this + assertThat(patternDescr.getObjectType()).isEqualTo("Cheese"); } @Test - public void testSimpleMethodCallWithFrom() throws Exception { + void testSimpleMethodCallWithFrom() throws Exception { String source = readResource("test_SimpleMethodCallWithFrom.drl"); PackageDescr pkg = parser.parse(source); - assertFalse(parser.getErrors().toString(), - parser.hasErrors()); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final FromDescr from = (FromDescr) pattern.getSource(); From 79afbdd17e2551a228c74768803dc720238ba9dd Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 6 Dec 2022 23:00:22 +0900 Subject: [PATCH 024/141] =?UTF-8?q?Enhance=20test/grammar=20coverage.=20la?= =?UTF-8?q?bel,=20consequenceLocation,=20test=20refac=E2=80=A6=20(#15)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Enhance test/grammar coverage. label, consequenceLocation, test refactoring, assertj best practice * - better test method names --- .../antlr4/org/drools/parser/DRLParser.g4 | 8 +- .../org/drools/parser/DRLVisitorImpl.java | 21 +- .../java/org/drools/parser/DRLParserTest.java | 4 +- .../org/drools/parser/MiscDRLParserTest.java | 270 ++++++++++++------ .../test/resources/org/drools/parser/from.drl | 29 ++ .../org/drools/parser/simple_rule.drl | 29 ++ .../test_ComplexChainedCallWithFrom.drl | 22 ++ .../parser/test_SimpleAccessorArgWithFrom.drl | 25 ++ .../parser/test_SimpleAccessorWithFrom.drl | 25 ++ .../test_SimpleFunctionCallWithFrom.drl | 25 ++ 10 files changed, 366 insertions(+), 92 deletions(-) create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/from.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_rule.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_ComplexChainedCallWithFrom.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorArgWithFrom.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorWithFrom.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleFunctionCallWithFrom.drl diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 4684804a10f..5c81fff3662 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -34,9 +34,9 @@ globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; // rule := RULE stringId (EXTENDS stringId)? annotation* attributes? lhs? rhs END -ruledef : DRL_RULE name=stringId (EXTENDS stringId)? drlAnnotation* attributes? DRL_WHEN lhs DRL_THEN rhs DRL_END ; +ruledef : DRL_RULE name=stringId (EXTENDS stringId)? drlAnnotation* attributes? lhs rhs DRL_END ; -lhs : lhsExpression? ; +lhs : DRL_WHEN lhsExpression? ; lhsExpression : lhsOr+ ; lhsOr : LPAREN DRL_OR lhsAnd+ RPAREN | lhsAnd (DRL_OR lhsAnd)* ; lhsAnd : LPAREN DRL_AND lhsUnary+ RPAREN | lhsUnary (DRL_AND lhsUnary)* ; @@ -260,7 +260,9 @@ lhsExists : DRL_EXISTS lhsPatternBind ; */ lhsNot : DRL_NOT lhsPatternBind ; -rhs : drlRhsBlockStatement* ; +rhs : DRL_THEN consequence ; + +consequence : drlRhsBlockStatement* ; stringId : ( IDENTIFIER | DRL_STRING_LITERAL ) ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index a152733d179..e9585a9ab10 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -9,6 +9,7 @@ import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; +import org.drools.drl.ast.descr.AndDescr; import org.drools.drl.ast.descr.AnnotationDescr; import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; @@ -115,7 +116,6 @@ public Object visitFunctiondef(DRLParser.FunctiondefContext ctx) { @Override public Object visitRuledef(DRLParser.RuledefContext ctx) { currentRule = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); - currentRule.setConsequence(ParserStringUtils.getTextPreservingWhitespace(ctx.rhs())); packageDescr.addRule(currentRule); Object result = super.visitRuledef(ctx); @@ -137,7 +137,8 @@ public Object visitLhs(DRLParser.LhsContext ctx) { public Object visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { if (ctx.lhsPattern().size() == 1) { Object result = super.visitLhsPatternBind(ctx); - PatternDescr patternDescr = (PatternDescr) currentConstructStack.peek().getDescrs().get(0); + ConditionalElementDescr parentDescr = currentConstructStack.peek(); + PatternDescr patternDescr = (PatternDescr) parentDescr.getDescrs().get(parentDescr.getDescrs().size() - 1); if (ctx.label() != null) { patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); } @@ -175,7 +176,7 @@ public Object visitLhsPattern(DRLParser.LhsPatternContext ctx) { currentPattern.setSource(from); } Object result = super.visitLhsPattern(ctx); - currentConstructStack.peek().addDescr(currentPattern); + currentConstructStack.peek().addDescr(currentPattern); currentPattern = null; return result; } @@ -184,7 +185,12 @@ public Object visitLhsPattern(DRLParser.LhsPatternContext ctx) { public Object visitConstraint(DRLParser.ConstraintContext ctx) { Object constraint = super.visitConstraint(ctx); if (constraint != null) { - ExprConstraintDescr constr = new ExprConstraintDescr(constraint.toString()); + String constraintString = constraint.toString(); + DRLParser.LabelContext label = ctx.label(); + if (label != null) { + constraintString = label.getText() + constraintString; + } + ExprConstraintDescr constr = new ExprConstraintDescr(constraintString); constr.setType(ExprConstraintDescr.Type.NAMED); currentPattern.addConstraint(constr); } @@ -292,6 +298,13 @@ public Object visitLhsOr(DRLParser.LhsOrContext ctx) { } } + @Override + public Object visitRhs(DRLParser.RhsContext ctx) { + currentRule.setConsequenceLocation(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); // location of "then" + currentRule.setConsequence(ParserStringUtils.getTextPreservingWhitespace(ctx.consequence())); + return super.visitChildren(ctx); + } + public PackageDescr getPackageDescr() { return packageDescr; } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java index cec1ac92b47..4b9497b422a 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java @@ -31,7 +31,7 @@ class DRLParserTest { "end\n"; @Test - void testParse() { + void parse_basicRule() { PackageDescr packageDescr = parse(drl); assertThat(packageDescr.getName()).isEqualTo("org.test"); @@ -72,7 +72,7 @@ void testParse() { } @Test - void testComputeTokenIndex() { + void computeTokenIndex_basicRule() { DRLParser parser = createDrlParser(drl); parser.compilationUnit(); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 77f2485ae46..82404dee71a 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -57,15 +57,26 @@ private String readResource(final String filename) throws Exception { return sb.toString(); } + private RuleDescr parseAndGetFirstRule(String drl) { + PackageDescr pkg = parser.parse(drl); + assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); + assertThat(pkg.getRules()).isNotEmpty(); + return pkg.getRules().get(0); + } + + private RuleDescr parseAndGetFirstRuleFromFile(String filename) throws Exception { + return parseAndGetFirstRule(readResource(filename)); + } + @Test - void testPackage() { + void parse_validPackage() { final String source = "package foo.bar.baz"; final PackageDescr pkg = parser.parse(source); assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); } @Test - void testPackageWithErrorNode() { + void parse_packageWithErrorNode() { final String source = "package 12 foo.bar.baz"; final PackageDescr pkg = parser.parse(source); assertThat(parser.hasErrors()).isTrue(); @@ -73,20 +84,20 @@ void testPackageWithErrorNode() { } @Test - void testPackageWithAllErrorNode() { + void parse_packageWithAllErrorNode() { final String source = "package 12 12312 231"; final PackageDescr pkg = parser.parse(source); assertThat(parser.hasErrors()).isTrue(); - assertThat(pkg.getName()).isEqualTo(""); + assertThat(pkg.getName()).isEmpty(); } @Test - void testCompilationUnit() { + void parse_import() { final String source = "package foo; import com.foo.Bar; import com.foo.Baz;"; PackageDescr pkg = parser.parse(source); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(pkg.getName()).isEqualTo("foo"); - assertThat(pkg.getImports().size()).isEqualTo(2); + assertThat(pkg.getImports()).hasSize(2); ImportDescr impdescr = pkg.getImports().get(0); assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); @@ -99,7 +110,7 @@ void testCompilationUnit() { } @Test - void testFunctionImport() { + void parse_functionImport() { final String source = "package foo\n" + "import function java.lang.Math.max\n" + "import function java.lang.Math.min;\n" + @@ -108,7 +119,7 @@ void testFunctionImport() { PackageDescr pkg = parser.parse(source); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(pkg.getName()).isEqualTo("foo"); - assertThat(pkg.getImports().size()).isEqualTo(2); + assertThat(pkg.getImports()).hasSize(2); ImportDescr impdescr = pkg.getImports().get(0); assertThat(impdescr.getTarget()).isEqualTo("foo.bar.*"); assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); @@ -120,7 +131,7 @@ void testFunctionImport() { assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); - assertThat(pkg.getFunctionImports().size()).isEqualTo(2); + assertThat(pkg.getFunctionImports()).hasSize(2); impdescr = pkg.getFunctionImports().get(0); assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.max"); assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget())); @@ -133,7 +144,7 @@ void testFunctionImport() { } @Test - void testGlobalWithComplexType() { + void parse_globalWithComplexType() { final String source = "package foo.bar.baz\n" + "import com.foo.Bar\n" + "global java.util.List> aList;\n" + @@ -141,14 +152,14 @@ void testGlobalWithComplexType() { PackageDescr pkg = parser.parse(source); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); - assertThat(pkg.getImports().size()).isEqualTo(1); + assertThat(pkg.getImports()).hasSize(1); ImportDescr impdescr = pkg.getImports().get(0); assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); - assertThat(pkg.getGlobals().size()).isEqualTo(2); + assertThat(pkg.getGlobals()).hasSize(2); GlobalDescr global = pkg.getGlobals().get(0); assertThat(global.getType()).isEqualTo("java.util.List>"); @@ -166,17 +177,17 @@ void testGlobalWithComplexType() { } @Test - void testGlobalWithOrWithoutSemi() throws Exception { + void parse_globalWithOrWithoutSemi() throws Exception { String source = readResource("globals.drl"); PackageDescr pkg = parser.parse(source); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - assertThat(pkg.getImports().size()).isEqualTo(1); - assertThat(pkg.getGlobals().size()).isEqualTo(2); + assertThat(pkg.getImports()).hasSize(1); + assertThat(pkg.getGlobals()).hasSize(2); final GlobalDescr foo = (GlobalDescr) pkg.getGlobals().get(0); assertThat(foo.getType()).isEqualTo("java.lang.String"); @@ -187,22 +198,22 @@ void testGlobalWithOrWithoutSemi() throws Exception { } @Test - void testFunctionImportWithNotExist() throws Exception { + void parse_functionImportWithNotExist() throws Exception { String source = readResource("test_FunctionImport.drl"); PackageDescr pkg = parser.parse(source); - assertThat(pkg.getFunctionImports().size()).isEqualTo(2); + assertThat(pkg.getFunctionImports()).hasSize(2); assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getTarget()).isEqualTo("abd.def.x"); - assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getStartCharacter() == -1).isFalse(); - assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getEndCharacter() == -1).isFalse(); + assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getStartCharacter()).isNotSameAs(-1); + assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getEndCharacter()).isNotSameAs(-1); assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getTarget()).isEqualTo("qed.wah.*"); - assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getStartCharacter() == -1).isFalse(); - assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getEndCharacter() == -1).isFalse(); + assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getStartCharacter()).isNotSameAs(-1); + assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getEndCharacter()).isNotSameAs(-1); } @Test - void testFromComplexAcessor() { + void parse_fromComplexAccessor() { String source = "rule \"Invalid customer id\" ruleflow-group \"validate\" lock-on-active true \n" + " when \n" + " o: Order( ) \n" + @@ -219,7 +230,7 @@ void testFromComplexAcessor() { RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("Invalid customer id"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + assertThat(rule.getLhs().getDescrs()).hasSize(2); NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(1); PatternDescr customer = (PatternDescr) not.getDescrs().get(0); @@ -229,7 +240,7 @@ void testFromComplexAcessor() { } @Test - void testFromWithInlineList() { + void parse_fromWithInlineList() { String source = "rule XYZ \n" + " when \n" + " o: Order( ) \n" + @@ -249,7 +260,7 @@ void testFromWithInlineList() { } @Test - void testFromWithInlineListMethod() { + void parse_fromWithInlineListMethod() { String source = "rule XYZ \n" + " when \n" + " o: Order( ) \n" + @@ -271,7 +282,7 @@ void testFromWithInlineListMethod() { } @Test - void testFromWithInlineListIndex() { + void parse_fromWithInlineListIndex() { String source = "rule XYZ \n" + " when \n" + " o: Order( ) \n" + @@ -293,7 +304,7 @@ void testFromWithInlineListIndex() { } @Test - void testRuleWithoutEnd() { + void parse_ruleWithoutEnd() { String source = "rule \"Invalid customer id\" \n" + " when \n" + " o: Order( ) \n" + @@ -304,7 +315,7 @@ void testRuleWithoutEnd() { } @Test - void testOrWithSpecialBind() { + void parse_orWithSpecialBind() { String source = "rule \"A and (B or C or D)\" \n" + " when \n" + " pdo1 : ParametricDataObject( paramID == 101, stringValue == \"1000\" ) and \n" + @@ -319,20 +330,20 @@ void testOrWithSpecialBind() { RuleDescr rule = pkg.getRules().get(0); AndDescr lhs = rule.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(2); + assertThat(lhs.getDescrs()).hasSize(2); PatternDescr pdo1 = (PatternDescr) lhs.getDescrs().get(0); assertThat(pdo1.getIdentifier()).isEqualTo("pdo1"); OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(1); - assertThat(or.getDescrs().size()).isEqualTo(3); + assertThat(or.getDescrs()).hasSize(3); for (BaseDescr pdo2 : or.getDescrs()) { assertThat(((PatternDescr) pdo2).getIdentifier()).isEqualTo("pdo2"); } } @Test - void testCompatibleRestriction() { + void parse_compatibleRestriction() { String source = "package com.sample rule test when Test( ( text == null || text2 matches \"\" ) ) then end"; PackageDescr pkg = parser.parse(source); @@ -344,7 +355,7 @@ void testCompatibleRestriction() { } @Test - void testSimpleConstraint() { + void parse_simpleConstraint() { String source = "package com.sample rule test when Cheese( type == 'stilton', price > 10 ) then end"; PackageDescr pkg = parser.parse(source); @@ -352,33 +363,33 @@ void testSimpleConstraint() { RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("test"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(rule.getLhs().getDescrs()).hasSize(1); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); AndDescr constraint = (AndDescr) pattern.getConstraint(); - assertThat(constraint.getDescrs().size()).isEqualTo(2); - assertThat(constraint.getDescrs().get(0).toString()).isEqualTo("type == \"stilton\""); - assertThat(constraint.getDescrs().get(1).toString()).isEqualTo("price > 10"); + assertThat(constraint.getDescrs()).hasSize(2); + assertThat(constraint.getDescrs().get(0)).hasToString("type == \"stilton\""); + assertThat(constraint.getDescrs().get(1)).hasToString("price > 10"); } @Test - void testStringEscapes() { + void parse_stringEscapes() { String source = "package com.sample rule test when Cheese( type matches \"\\..*\\\\.\" ) then end"; PackageDescr pkg = parser.parse(source); assertThat(pkg.getName()).isEqualTo("com.sample"); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("test"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(rule.getLhs().getDescrs()).hasSize(1); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); AndDescr constraint = (AndDescr) pattern.getConstraint(); - assertThat(constraint.getDescrs().size()).isEqualTo(1); - assertThat(constraint.getDescrs().get(0).toString()).isEqualTo("type matches \"\\..*\\\\.\""); + assertThat(constraint.getDescrs()).hasSize(1); + assertThat(constraint.getDescrs().get(0)).hasToString("type matches \"\\..*\\\\.\""); } @Test - void testDialect() { + void parse_dialectWithSingleQuotation() { final String source = "dialect 'mvel'"; PackageDescr pkg = parser.parse(source); AttributeDescr attr = (AttributeDescr) pkg.getAttributes().get(0); @@ -387,7 +398,7 @@ void testDialect() { } @Test - void testDialect2() { + void parse_dialectWithDoubleQuotation() { final String source = "dialect \"mvel\""; PackageDescr pkg = parser.parse(source); AttributeDescr attr = pkg.getAttributes().get(0); @@ -396,7 +407,7 @@ void testDialect2() { } @Test - void testEmptyRuleWithoutWhen() throws Exception { + void parse_emptyRuleWithoutWhen() throws Exception { String source = readResource("empty_rule.drl"); // without WHEN PackageDescr pkg = parser.parse(source); @@ -406,7 +417,7 @@ void testEmptyRuleWithoutWhen() throws Exception { } @Test - void testKeywordCollisions() throws Exception { + void parse_keywordCollisions() throws Exception { String source = readResource("eol_funny_business.drl"); // keywords everywhere // Note: eol_funny_business.drl is modified from the one under drools-test-coverage to be more realistic. @@ -416,22 +427,22 @@ void testKeywordCollisions() throws Exception { assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); } @Test - void testTernaryExpression() throws Exception { + void parse_ternaryExpression() throws Exception { String source = readResource("ternary_expression.drl"); PackageDescr pkg = parser.parse(source); final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if (speed > speedLimit ? true : false;) pullEmOver();"); } @Test - void testFunctionWithArrays() throws Exception { + void parse_functionWithArrays() throws Exception { String source = readResource("function_arrays.drl"); // Note: function_arrays.drl is modified from the one under drools-test-coverage to be more realistic. @@ -441,7 +452,7 @@ void testFunctionWithArrays() throws Exception { PackageDescr pkg = parser.parse(source); assertThat(pkg.getName()).isEqualTo("foo"); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); @@ -455,7 +466,7 @@ void testFunctionWithArrays() throws Exception { } @Test - void testAlmostEmptyRule() throws Exception { + void parse_almostEmptyRule() throws Exception { String source = readResource("almost_empty_rule.drl"); PackageDescr pkg = parser.parse(source); @@ -466,11 +477,11 @@ void testAlmostEmptyRule() throws Exception { assertThat(rule.getName()).isEqualTo("almost_empty"); assertThat(rule.getLhs()).isNotNull(); - assertThat(((String) rule.getConsequence()).trim()).isEqualTo(""); + assertThat(((String) rule.getConsequence()).trim()).isEmpty(); } @Test - void testQuotedStringNameRule() throws Exception { + void parse_quotedStringNameRule() throws Exception { String source = readResource("quoted_string_name_rule.drl"); PackageDescr pkg = parser.parse(source); @@ -481,11 +492,11 @@ void testQuotedStringNameRule() throws Exception { assertThat(rule.getName()).isEqualTo("quoted string name"); assertThat(rule.getLhs()).isNotNull(); - assertThat(((String) rule.getConsequence()).trim()).isEqualTo(""); + assertThat(((String) rule.getConsequence()).trim()).isEmpty(); } @Test - void testNoLoop() throws Exception { + void parse_noLoop() throws Exception { String source = readResource("no-loop.drl"); PackageDescr pkg = parser.parse(source); @@ -501,7 +512,7 @@ void testNoLoop() throws Exception { } @Test - void testAutofocus() throws Exception { + void parse_autofocus() throws Exception { String source = readResource("autofocus.drl"); PackageDescr pkg = parser.parse(source); @@ -517,7 +528,7 @@ void testAutofocus() throws Exception { } @Test - void testRuleFlowGroup() throws Exception { + void parse_ruleFlowGroup() throws Exception { String source = readResource("ruleflowgroup.drl"); PackageDescr pkg = parser.parse(source); @@ -533,7 +544,7 @@ void testRuleFlowGroup() throws Exception { } @Test - void testConsequenceWithDeclaration() throws Exception { + void parse_consequenceWithDeclaration() throws Exception { String source = readResource("declaration-in-consequence.drl"); PackageDescr pkg = parser.parse(source); @@ -564,7 +575,7 @@ void testConsequenceWithDeclaration() throws Exception { } @Test - void testRuleParseLhs() { + void parse_or() { final String text = "rule X when Person(age < 42, location==\"atlanta\") \nor\nPerson(name==\"bob\") then end"; PackageDescr pkg = parser.parse(text); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); @@ -574,12 +585,12 @@ void testRuleParseLhs() { assertThat(rule).isNotNull(); AndDescr lhs = rule.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); - assertThat(((OrDescr) lhs.getDescrs().get(0)).getDescrs().size()).isEqualTo(2); + assertThat(lhs.getDescrs()).hasSize(1); + assertThat(((OrDescr) lhs.getDescrs().get(0)).getDescrs()).hasSize(2); } @Test - void testRuleParseLhsWithStringQuotes() { + void parse_lhsWithStringQuotes() { final String text = "rule X when Person( location==\"atlanta\\\"\") then end\n"; PackageDescr pkg = parser.parse(text); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); @@ -595,7 +606,7 @@ void testRuleParseLhsWithStringQuotes() { } @Test - void testRuleParseLhsWithStringQuotes2() { + void parse_lhsWithStringQuotesEscapeChars() { final String text = "rule X when Cheese( $x: type, type == \"s\\tti\\\"lto\\nn\" ) then end\n"; PackageDescr pkg = parser.parse(text); RuleDescr rule = (RuleDescr) pkg.getRules().get(0); @@ -610,12 +621,8 @@ void testRuleParseLhsWithStringQuotes2() { } @Test - void testLiteralBoolAndNegativeNumbersRule() throws Exception { - String source = readResource("literal_bool_and_negative.drl"); - PackageDescr pkg = parser.parse(source); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + void parse_literalBoolAndNegativeNumbersRule() throws Exception { + RuleDescr rule = parseAndGetFirstRuleFromFile("literal_bool_and_negative.drl"); assertThat(rule).isNotNull(); @@ -625,16 +632,16 @@ void testLiteralBoolAndNegativeNumbersRule() throws Exception { assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("cons();"); final AndDescr lhs = rule.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(3); + assertThat(lhs.getDescrs()).hasSize(3); PatternDescr pattern = (PatternDescr) lhs.getDescrs().get(0); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); AndDescr fieldAnd = (AndDescr) pattern.getConstraint(); ExprConstraintDescr fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == false"); pattern = (PatternDescr) lhs.getDescrs().get(1); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); fieldAnd = (AndDescr) pattern.getConstraint(); fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); @@ -642,7 +649,7 @@ void testLiteralBoolAndNegativeNumbersRule() throws Exception { assertThat(fld.getText()).isEqualToIgnoringWhitespace("boo > -42"); pattern = (PatternDescr) lhs.getDescrs().get(2); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); fieldAnd = (AndDescr) pattern.getConstraint(); fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); @@ -651,32 +658,129 @@ void testLiteralBoolAndNegativeNumbersRule() throws Exception { } @Test - void testEmptyPattern() throws Exception { + void parse_emptyPattern() throws Exception { String source = readResource("test_EmptyPattern.drl"); PackageDescr pkg = parser.parse(source); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get(0); assertThat(ruleDescr.getName()).isEqualTo("simple rule"); assertThat(ruleDescr.getLhs()).isNotNull(); - assertThat(ruleDescr.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(ruleDescr.getLhs().getDescrs()).hasSize(1); final PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); - assertThat(patternDescr.getConstraint().getDescrs().size()).isEqualTo(0); // this + assertThat(patternDescr.getConstraint().getDescrs()).isEmpty(); // this assertThat(patternDescr.getObjectType()).isEqualTo("Cheese"); } @Test - void testSimpleMethodCallWithFrom() throws Exception { - String source = readResource("test_SimpleMethodCallWithFrom.drl"); - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + void parse_simpleMethodCallWithFrom() throws Exception { + RuleDescr rule = parseAndGetFirstRuleFromFile("test_SimpleMethodCallWithFrom.drl"); final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final FromDescr from = (FromDescr) pattern.getSource(); final MVELExprDescr method = (MVELExprDescr) from.getDataSource(); assertThat(method.getExpression()).isEqualToIgnoringWhitespace("something.doIt( foo,bar,42,\"hello\",[ a : \"b\", \"something\" : 42, \"a\" : foo, x : [x:y]],\"end\", [a, \"b\", 42] )"); } + + @Test + void parse_simpleFunctionCallWithFrom() throws Exception { + RuleDescr rule = parseAndGetFirstRuleFromFile("test_SimpleFunctionCallWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr func = (MVELExprDescr) from.getDataSource(); + + assertThat(func.getExpression()).isEqualToIgnoringWhitespace("doIt( foo,bar,42,\"hello\",[ a : \"b\", \"something\" : 42, \"a\" : foo, x : [x:y]],\"end\", [a, \"b\", 42] )"); + } + + @Test + void parse_simpleAccessorWithFrom() throws Exception { + RuleDescr rule = parseAndGetFirstRuleFromFile("test_SimpleAccessorWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); + + assertThat(accessor.getExpression()).isEqualTo("something.doIt"); + } + + @Test + void parse_simpleAccessorAndArgWithFrom() throws Exception { + RuleDescr rule = parseAndGetFirstRuleFromFile("test_SimpleAccessorArgWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); + + assertThat(accessor.getExpression()).isEqualTo("something.doIt[\"key\"]"); + } + + @Test + void parse_complexChainedAccessor() throws Exception { + RuleDescr rule = parseAndGetFirstRuleFromFile("test_ComplexChainedCallWithFrom.drl"); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); + + assertThat(accessor.getExpression()).isEqualToIgnoringWhitespace("doIt1( foo,bar,42,\"hello\",[ a : \"b\"], [a, \"b\", 42] ).doIt2(bar, [a, \"b\", 42]).field[\"key\"]"); + } + + @Test + void parse_from() throws Exception { + RuleDescr rule = parseAndGetFirstRuleFromFile("from.drl"); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("using_from"); + + assertThat(rule.getLhs().getDescrs()).hasSize(9); + } + + @Test + void parse_simpleRuleWithBindings() throws Exception { + RuleDescr rule = parseAndGetFirstRuleFromFile("simple_rule.drl"); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + + assertThat(rule.getConsequenceLine()).isEqualTo(22); + assertThat(rule.getConsequencePattern()).isEqualTo(2); + + final AndDescr lhs = rule.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs()).hasSize(3); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + + assertThat(first.getConstraint().getDescrs()).hasSize(1); + + AndDescr fieldAnd = (AndDescr) first.getConstraint(); + ExprConstraintDescr constraint = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + assertThat(constraint).isNotNull(); + + assertThat(constraint.getExpression()).isEqualToIgnoringWhitespace("a==3"); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get(1); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + // no constraints, only a binding + fieldAnd = (AndDescr) second.getConstraint(); + assertThat(fieldAnd.getDescrs()).hasSize(1); + + final ExprConstraintDescr binding = (ExprConstraintDescr) second.getConstraint().getDescrs().get(0); + assertThat(binding.getExpression()).isEqualToIgnoringWhitespace("a4:a==4"); + + // Check third pattern + final PatternDescr third = (PatternDescr) lhs.getDescrs().get(2); + assertThat(third.getIdentifier()).isNull(); + assertThat(third.getObjectType()).isEqualTo("Baz"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if ( a == b ) { " + " assert( foo3 );" + "} else {" + " retract( foo4 );" + "}" + " System.out.println( a4 );"); + } } diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/from.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/from.drl new file mode 100644 index 00000000000..5c3f9e9775f --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/from.drl @@ -0,0 +1,29 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule using_from + when + Foo() from bar.baz + Foo() from bar.baz["key"] + Foo() from bar.baz[$key] + Foo() from bar.baz[1] + Whee(bar=="baz") from whee("y") + f: Foo(la==2) from bar.la(x) + Bam() from wa() + Kah() from la.wa(42, 42.42, false, null) + Bam(a=="c") + then + whee(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_rule.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_rule.drl new file mode 100644 index 00000000000..7f6a6c4b6a4 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_rule.drl @@ -0,0 +1,29 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + when + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + then + if ( a == b ) { + assert( foo3 ); + } else { + retract( foo4 ); + } + System.out.println( a4 ); +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_ComplexChainedCallWithFrom.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_ComplexChainedCallWithFrom.drl new file mode 100755 index 00000000000..f8029cd9026 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_ComplexChainedCallWithFrom.drl @@ -0,0 +1,22 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule blah + when + Col1() from doIt1( foo,bar,42,"hello",[ a : "b"], [a, "b", 42] ).doIt2(bar, [a, "b", 42]).field["key"] + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorArgWithFrom.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorArgWithFrom.drl new file mode 100644 index 00000000000..40289b97d4b --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorArgWithFrom.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule blah + + when + + Col1() from something.doIt["key"] + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorWithFrom.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorWithFrom.drl new file mode 100644 index 00000000000..375fe578fe4 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorWithFrom.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule blah + + when + + Col1() from something.doIt + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleFunctionCallWithFrom.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleFunctionCallWithFrom.drl new file mode 100644 index 00000000000..8729e98d029 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleFunctionCallWithFrom.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule blah + + when + + Col1() from doIt( foo,bar,42,"hello",[ a : "b", "something" : 42, "a" : foo, x : [x:y]],"end", [a, "b", 42] ) + Col2() + then + partay(); +end From 77e42a62f7ec9592e148ae8c1b5c8a9aee75ca9d Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 16 Dec 2022 17:48:34 +0900 Subject: [PATCH 025/141] [DROOLS-7253] Review and improve drools-lsp parser Visitor design (#16) * [DROOLS-7253] Review and improve drools-lsp parser Visitor design - Remove currentConstructStack. Utilize return object instead. * - Remove instance fields. Utilize return objects instead. --- .../org/drools/parser/DRLParserException.java | 12 + .../org/drools/parser/DRLParserHelper.java | 29 +- .../org/drools/parser/DRLParserWrapper.java | 10 +- .../org/drools/parser/DRLVisitorImpl.java | 355 +++++++++++------- 4 files changed, 245 insertions(+), 161 deletions(-) create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserException.java diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserException.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserException.java new file mode 100644 index 00000000000..6bc5812a78f --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserException.java @@ -0,0 +1,12 @@ +package org.drools.parser; + +public class DRLParserException extends RuntimeException { + + public DRLParserException() { + super(); + } + + public DRLParserException(String message) { + super(message); + } +} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index feabbe39207..9d42bf09641 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -3,7 +3,6 @@ import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; -import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; @@ -12,11 +11,14 @@ public class DRLParserHelper { + private DRLParserHelper() { + } + public static PackageDescr parse(String drl) { - return parseTree2PackageDescr(createParseTree(drl)); + return compilationUnitContext2PackageDescr(createParseTree(drl)); } - public static ParseTree createParseTree(String drl) { + public static DRLParser.CompilationUnitContext createParseTree(String drl) { return createDrlParser(drl).compilationUnit(); } @@ -24,28 +26,31 @@ public static DRLParser createDrlParser(String drl) { CharStream inputStream = CharStreams.fromString(drl); DRLLexer drlLexer = new DRLLexer(inputStream); CommonTokenStream commonTokenStream = new CommonTokenStream(drlLexer); - DRLParser drlParser = new DRLParser(commonTokenStream); - return drlParser; + return new DRLParser(commonTokenStream); } - public static PackageDescr parseTree2PackageDescr(ParseTree parseTree) { + public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.CompilationUnitContext ctx) { DRLVisitorImpl visitor = new DRLVisitorImpl(); - visitor.visit(parseTree); - return visitor.getPackageDescr(); + Object descr = visitor.visit(ctx); + if (descr instanceof PackageDescr) { + return (PackageDescr) descr; + } else { + throw new DRLParserException("CompilationUnitContext should produce PackageDescr. descr = " + descr.getClass()); + } } - public static Integer computeTokenIndex(DRLParser parser, int row, int col) { for (int i = 0; i < parser.getInputStream().size(); i++) { Token token = parser.getInputStream().get(i); int start = token.getCharPositionInLine(); int stop = token.getCharPositionInLine() + token.getText().length(); - if (token.getLine() > row) + if (token.getLine() > row) { return token.getTokenIndex() - 1; - else if (token.getLine() == row && start >= col) + } else if (token.getLine() == row && start >= col) { return token.getTokenIndex() == 0 ? 0 : token.getTokenIndex() - 1; - else if (token.getLine() == row && start < col && stop >= col) + } else if (token.getLine() == row && start < col && stop >= col) { return token.getTokenIndex(); + } } return null; } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java index 251c918190a..7bfdcd89044 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java @@ -4,31 +4,29 @@ import java.util.List; import java.util.stream.Collectors; -import org.antlr.v4.runtime.tree.ParseTree; import org.drools.drl.ast.descr.PackageDescr; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.drools.parser.DRLParserHelper.compilationUnitContext2PackageDescr; + public class DRLParserWrapper { private static final Logger LOGGER = LoggerFactory.getLogger(DRLParserWrapper.class); private final List errors = new ArrayList<>(); - public DRLParserWrapper() { - } - public PackageDescr parse(String drl) { DRLParser drlParser = DRLParserHelper.createDrlParser(drl); DRLErrorListener errorListener = new DRLErrorListener(); drlParser.addErrorListener(errorListener); - ParseTree parseTree = drlParser.compilationUnit(); + DRLParser.CompilationUnitContext cxt = drlParser.compilationUnit(); errors.addAll(errorListener.getErrors()); try { - return DRLParserHelper.parseTree2PackageDescr(parseTree); + return compilationUnitContext2PackageDescr(cxt); } catch (Exception e) { LOGGER.error("Exception while creating PackageDescr", e); errors.add(new DRLParserError(e)); diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index e9585a9ab10..236478d7fb8 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -1,19 +1,19 @@ package org.drools.parser; -import java.util.ArrayDeque; -import java.util.Deque; +import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.stream.Collectors; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.RuleNode; import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.AndDescr; import org.drools.drl.ast.descr.AnnotationDescr; import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; -import org.drools.drl.ast.descr.ConditionalElementDescr; import org.drools.drl.ast.descr.ExistsDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; import org.drools.drl.ast.descr.FromDescr; @@ -35,63 +35,74 @@ public class DRLVisitorImpl extends DRLParserBaseVisitor { - private final PackageDescr packageDescr = new PackageDescr(); - - private RuleDescr currentRule; - private PatternDescr currentPattern; - - private final Deque currentConstructStack = new ArrayDeque<>(); // e.g. whole LHS (= AndDescr), NotDescr, ExistsDescr - @Override - public Object visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { - return super.visitCompilationUnit(ctx); + public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { + PackageDescr packageDescr = new PackageDescr(); + if (ctx.packagedef() != null) { + packageDescr.setName(getTextWithoutErrorNode(ctx.packagedef().name)); + } + List descrList = visitDescrChildren(ctx); + applyChildrenDescrs(packageDescr, descrList); + return packageDescr; } - @Override - public Object visitPackagedef(DRLParser.PackagedefContext ctx) { - packageDescr.setName(getTextWithoutErrorNode(ctx.name)); - return super.visitPackagedef(ctx); + private void applyChildrenDescrs(PackageDescr packageDescr, List descrList) { + descrList.forEach(descr -> { + if (descr instanceof UnitDescr) { + packageDescr.setUnit((UnitDescr) descr); + } else if (descr instanceof GlobalDescr) { + packageDescr.addGlobal((GlobalDescr) descr); + } else if (descr instanceof FunctionImportDescr) { + packageDescr.addFunctionImport((FunctionImportDescr) descr); + } else if (descr instanceof ImportDescr) { + packageDescr.addImport((ImportDescr) descr); + } else if (descr instanceof FunctionDescr) { + FunctionDescr functionDescr = (FunctionDescr) descr; + functionDescr.setNamespace(packageDescr.getNamespace()); + AttributeDescr dialect = packageDescr.getAttribute("dialect"); + if (dialect != null) { + functionDescr.setDialect(dialect.getValue()); + } + packageDescr.addFunction(functionDescr); + } else if (descr instanceof AttributeDescr) { + packageDescr.addAttribute((AttributeDescr) descr); + } else if (descr instanceof RuleDescr) { + packageDescr.addRule((RuleDescr) descr); + } + }); } @Override - public Object visitUnitdef(DRLParser.UnitdefContext ctx) { - packageDescr.setUnit(new UnitDescr(ctx.name.getText())); - return super.visitUnitdef(ctx); + public UnitDescr visitUnitdef(DRLParser.UnitdefContext ctx) { + return new UnitDescr(ctx.name.getText()); } @Override - public Object visitGlobaldef(DRLParser.GlobaldefContext ctx) { + public GlobalDescr visitGlobaldef(DRLParser.GlobaldefContext ctx) { GlobalDescr globalDescr = new GlobalDescr(ctx.drlIdentifier().getText(), ctx.type().getText()); populateStartEnd(globalDescr, ctx); - packageDescr.addGlobal(globalDescr); - return super.visitGlobaldef(ctx); + return globalDescr; } @Override - public Object visitImportdef(DRLParser.ImportdefContext ctx) { + public ImportDescr visitImportdef(DRLParser.ImportdefContext ctx) { String target = ctx.drlQualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); if (ctx.DRL_FUNCTION() != null || ctx.STATIC() != null) { FunctionImportDescr functionImportDescr = new FunctionImportDescr(); functionImportDescr.setTarget(target); populateStartEnd(functionImportDescr, ctx); - packageDescr.addFunctionImport(functionImportDescr); + return functionImportDescr; } else { ImportDescr importDescr = new ImportDescr(); importDescr.setTarget(target); populateStartEnd(importDescr, ctx); - packageDescr.addImport(importDescr); + return importDescr; } - return super.visitImportdef(ctx); } @Override - public Object visitFunctiondef(DRLParser.FunctiondefContext ctx) { + public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { FunctionDescr functionDescr = new FunctionDescr(); - functionDescr.setNamespace(packageDescr.getNamespace()); - AttributeDescr dialect = packageDescr.getAttribute("dialect"); - if (dialect != null) { - functionDescr.setDialect(dialect.getValue()); - } if (ctx.typeTypeOrVoid() != null) { functionDescr.setReturnType(ctx.typeTypeOrVoid().getText()); } else { @@ -102,87 +113,146 @@ public Object visitFunctiondef(DRLParser.FunctiondefContext ctx) { DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); if (formalParameterListContext != null) { List formalParameterContexts = formalParameterListContext.formalParameter(); - formalParameterContexts.stream().forEach(formalParameterContext -> { + formalParameterContexts.forEach(formalParameterContext -> { DRLParser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); DRLParser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); functionDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); }); } functionDescr.setBody(ParserStringUtils.getTextPreservingWhitespace(ctx.block())); - packageDescr.addFunction(functionDescr); - return super.visitFunctiondef(ctx); + return functionDescr; + } + + @Override + public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { + RuleDescr ruleDescr = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); + + ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(ruleDescr::addAnnotation); + + if (ctx.attributes() != null) { + List descrList = visitDescrChildren(ctx.attributes()); + descrList.stream() + .filter(AttributeDescr.class::isInstance) + .map(AttributeDescr.class::cast) + .forEach(ruleDescr::addAttribute); + } + + if (ctx.lhs() != null) { + List lhsDescrList = visitLhs(ctx.lhs()); + lhsDescrList.forEach(descr -> ruleDescr.getLhs().addDescr(descr)); + slimLhsRootDescr(ruleDescr.getLhs()); + } + + if (ctx.rhs() != null) { + ruleDescr.setConsequenceLocation(ctx.rhs().getStart().getLine(), ctx.rhs().getStart().getCharPositionInLine()); // location of "then" + ruleDescr.setConsequence(ParserStringUtils.getTextPreservingWhitespace(ctx.rhs().consequence())); + } + + return ruleDescr; + } + + private void slimLhsRootDescr(AndDescr root) { + List descrList = new ArrayList<>(root.getDescrs()); + root.getDescrs().clear(); + descrList.forEach(root::addOrMerge); // This slims down nested AndDescr } @Override - public Object visitRuledef(DRLParser.RuledefContext ctx) { - currentRule = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); - packageDescr.addRule(currentRule); + public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { + AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); + annotationDescr.setValue(ctx.drlArguments().drlArgument(0).getText()); + return annotationDescr; + } - Object result = super.visitRuledef(ctx); - currentRule = null; - return result; + @Override + public AttributeDescr visitAttribute(DRLParser.AttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.getChild(0).getText()); + if (ctx.getChildCount() > 1) { + // TODO : will likely split visitAttribute methods using labels (e.g. #stringAttribute) + String value = unescapeJava(safeStripStringDelimiters(ctx.getChild(1).getText())); + attributeDescr.setValue(value); + } + return attributeDescr; } @Override - public Object visitLhs(DRLParser.LhsContext ctx) { - currentConstructStack.push(currentRule.getLhs()); - try { - return super.visitLhs(ctx); - } finally { - currentConstructStack.pop(); + public List visitLhs(DRLParser.LhsContext ctx) { + if (ctx.lhsExpression() != null) { + return visitLhsExpression(ctx.lhsExpression()); + } else { + return new ArrayList<>(); } } @Override - public Object visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { + public List visitLhsExpression(DRLParser.LhsExpressionContext ctx) { + return visitDescrChildren(ctx); + } + + @Override + public BaseDescr visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { if (ctx.lhsPattern().size() == 1) { - Object result = super.visitLhsPatternBind(ctx); - ConditionalElementDescr parentDescr = currentConstructStack.peek(); - PatternDescr patternDescr = (PatternDescr) parentDescr.getDescrs().get(parentDescr.getDescrs().size() - 1); - if (ctx.label() != null) { - patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); - } - return result; + return getSinglePatternDescr(ctx); } else if (ctx.lhsPattern().size() > 1) { - OrDescr orDescr = new OrDescr(); - currentConstructStack.peek().addDescr(orDescr); - currentConstructStack.push(orDescr); - try { - Object result = super.visitLhsPatternBind(ctx); - List descrs = orDescr.getDescrs(); - for (BaseDescr descr : descrs) { - PatternDescr patternDescr = (PatternDescr) descr; - if (ctx.label() != null) { - patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); - } - } - return result; - } finally { - currentConstructStack.pop(); - } + return getOrDescrWithMultiplePatternDescr(ctx); } else { throw new IllegalStateException("ctx.lhsPattern().size() == 0 : " + ctx.getText()); } } + private PatternDescr getSinglePatternDescr(DRLParser.LhsPatternBindContext ctx) { + Optional optPatternDescr = visitFirstDescrChild(ctx); + PatternDescr patternDescr = optPatternDescr.filter(PatternDescr.class::isInstance) + .map(PatternDescr.class::cast) + .orElseThrow(() -> new IllegalStateException("lhsPatternBind must have at least one lhsPattern : " + ctx.getText())); + if (ctx.label() != null) { + patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); + } + return patternDescr; + } + + private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindContext ctx) { + OrDescr orDescr = new OrDescr(); + List descrList = visitDescrChildren(ctx); + descrList.stream() + .filter(PatternDescr.class::isInstance) + .map(PatternDescr.class::cast) + .forEach(patternDescr -> { + if (ctx.label() != null) { + patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); + } + orDescr.addDescr(patternDescr); + }); + + return orDescr; + } + @Override - public Object visitLhsPattern(DRLParser.LhsPatternContext ctx) { - currentPattern = new PatternDescr(ctx.objectType.getText()); + public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { + PatternDescr patternDescr = new PatternDescr(ctx.objectType.getText()); if (ctx.patternSource() != null) { String expression = ctx.patternSource().getText(); FromDescr from = new FromDescr(); from.setDataSource(new MVELExprDescr(expression)); - from.setResource(currentPattern.getResource()); - currentPattern.setSource(from); + from.setResource(patternDescr.getResource()); + patternDescr.setSource(from); } - Object result = super.visitLhsPattern(ctx); - currentConstructStack.peek().addDescr(currentPattern); - currentPattern = null; - return result; + List constraintDescrList = visitConstraints(ctx.constraints()); + constraintDescrList.forEach(patternDescr::addConstraint); + return patternDescr; + } + + @Override + public List visitConstraints(DRLParser.ConstraintsContext ctx) { + List descrList = visitDescrChildren(ctx); + return descrList.stream() + .filter(ExprConstraintDescr.class::isInstance) + .map(ExprConstraintDescr.class::cast) + .collect(Collectors.toList()); } @Override - public Object visitConstraint(DRLParser.ConstraintContext ctx) { + public ExprConstraintDescr visitConstraint(DRLParser.ConstraintContext ctx) { Object constraint = super.visitConstraint(ctx); if (constraint != null) { String constraintString = constraint.toString(); @@ -190,15 +260,15 @@ public Object visitConstraint(DRLParser.ConstraintContext ctx) { if (label != null) { constraintString = label.getText() + constraintString; } - ExprConstraintDescr constr = new ExprConstraintDescr(constraintString); - constr.setType(ExprConstraintDescr.Type.NAMED); - currentPattern.addConstraint(constr); + ExprConstraintDescr constraintDescr = new ExprConstraintDescr(constraintString); + constraintDescr.setType(ExprConstraintDescr.Type.NAMED); + return constraintDescr; } return null; } @Override - public Object visitDrlExpression(DRLParser.DrlExpressionContext ctx) { + public String visitDrlExpression(DRLParser.DrlExpressionContext ctx) { return ctx.children.stream() .map(c -> c instanceof TerminalNode ? c : c.accept(this)) .filter(Objects::nonNull) @@ -207,7 +277,7 @@ public Object visitDrlExpression(DRLParser.DrlExpressionContext ctx) { } @Override - public Object visitDrlPrimary(DRLParser.DrlPrimaryContext ctx) { + public String visitDrlPrimary(DRLParser.DrlPrimaryContext ctx) { return ctx.children.stream() .map(c -> c instanceof TerminalNode ? c : c.accept(this)) .filter(Objects::nonNull) @@ -216,97 +286,69 @@ public Object visitDrlPrimary(DRLParser.DrlPrimaryContext ctx) { } @Override - public Object visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { + public String visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { return ctx.getText(); } @Override - public Object visitDrlLiteral(DRLParser.DrlLiteralContext ctx) { + public String visitDrlLiteral(DRLParser.DrlLiteralContext ctx) { ParseTree node = ctx; while (true) { if (node instanceof TerminalNode) { return node.toString(); } if (node.getChildCount() != 1) { - return super.visitDrlLiteral(ctx); + return super.visitDrlLiteral(ctx).toString(); } node = node.getChild(0); } } @Override - public Object visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { - AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); - annotationDescr.setValue(ctx.drlArguments().drlArgument(0).getText()); - currentRule.addAnnotation(annotationDescr); - return super.visitDrlAnnotation(ctx); - } - - @Override - public Object visitAttribute(DRLParser.AttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.getChild(0).getText()); - if (ctx.getChildCount() > 1) { - // TODO : will likely split visitAttribute methods using labels (e.g. #stringAttribute) - String value = unescapeJava(safeStripStringDelimiters(ctx.getChild(1).getText())); - attributeDescr.setValue(value); - } - if (currentRule != null) { - currentRule.addAttribute(attributeDescr); - } else { - packageDescr.addAttribute(attributeDescr); - } - return super.visitAttribute(ctx); - } - - @Override - public Object visitLhsExists(DRLParser.LhsExistsContext ctx) { + public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { ExistsDescr existsDescr = new ExistsDescr(); - currentConstructStack.peek().addDescr(existsDescr); - currentConstructStack.push(existsDescr); - try { - return super.visitLhsExists(ctx); - } finally { - currentConstructStack.pop(); - } + BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); + existsDescr.addDescr(descr); + return existsDescr; } @Override - public Object visitLhsNot(DRLParser.LhsNotContext ctx) { + public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { NotDescr notDescr = new NotDescr(); - currentConstructStack.peek().addDescr(notDescr); - currentConstructStack.push(notDescr); - try { - return super.visitLhsNot(ctx); - } finally { - currentConstructStack.pop(); - } + BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); + notDescr.addDescr(descr); + return notDescr; } @Override - public Object visitLhsOr(DRLParser.LhsOrContext ctx) { + public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { if (!ctx.DRL_OR().isEmpty()) { OrDescr orDescr = new OrDescr(); - currentConstructStack.peek().addDescr(orDescr); - currentConstructStack.push(orDescr); - try { - return super.visitLhsOr(ctx); - } finally { - currentConstructStack.pop(); - } + List descrList = visitDescrChildren(ctx); + descrList.forEach(orDescr::addDescr); + return orDescr; } else { - return super.visitLhsOr(ctx); + // No DRL_OR means only one lhsAnd + return visitLhsAnd(ctx.lhsAnd().get(0)); } } @Override - public Object visitRhs(DRLParser.RhsContext ctx) { - currentRule.setConsequenceLocation(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); // location of "then" - currentRule.setConsequence(ParserStringUtils.getTextPreservingWhitespace(ctx.consequence())); - return super.visitChildren(ctx); + public BaseDescr visitLhsAnd(DRLParser.LhsAndContext ctx) { + if (!ctx.DRL_AND().isEmpty()) { + AndDescr andDescr = new AndDescr(); + List descrList = visitDescrChildren(ctx); + descrList.forEach(andDescr::addDescr); + return andDescr; + } else { + // No DRL_AND means only one lhsUnary + return visitLhsUnary(ctx.lhsUnary().get(0)); + } } - public PackageDescr getPackageDescr() { - return packageDescr; + @Override + public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { + return (BaseDescr) visitChildren(ctx); } private void populateStartEnd(BaseDescr descr, ParserRuleContext ctx) { @@ -315,4 +357,31 @@ private void populateStartEnd(BaseDescr descr, ParserRuleContext ctx) { // I will revisit if this is the right approach. descr.setEndCharacter(ctx.getStop().getStopIndex()); } + + private List visitDescrChildren(RuleNode node) { + List aggregator = new ArrayList<>(); + int n = node.getChildCount(); + + for (int i = 0; i < n && this.shouldVisitNextChild(node, aggregator); ++i) { + ParseTree c = node.getChild(i); + Object childResult = c.accept(this); + if (childResult instanceof BaseDescr) { + aggregator.add((BaseDescr) childResult); + } + } + return aggregator; + } + + private Optional visitFirstDescrChild(RuleNode node) { + int n = node.getChildCount(); + + for (int i = 0; i < n && this.shouldVisitNextChild(node, null); ++i) { + ParseTree c = node.getChild(i); + Object childResult = c.accept(this); + if (childResult instanceof BaseDescr) { + return Optional.of((BaseDescr) childResult); + } + } + return Optional.empty(); + } } From d637f88a0fec8bd6fad1dfe57aa21a46202f2718 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 12 Jan 2023 17:41:33 +0900 Subject: [PATCH 026/141] [DROOLS-7270] Enhance test/grammar coverage : andRestriction, orRestriction (#4) - Removed some unused cast --- .../antlr4/org/drools/parser/DRLParser.g4 | 15 ++- .../org/drools/parser/DRLVisitorImpl.java | 74 +++++++------- .../org/drools/parser/MiscDRLParserTest.java | 96 +++++++++++++------ .../org/drools/parser/restrictions_test.drl | 24 +++++ 4 files changed, 137 insertions(+), 72 deletions(-) create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/restrictions_test.drl diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 5c81fff3662..a15d73dc7d6 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -77,8 +77,19 @@ andExpression : left=equalityExpression (BITAND right=equalityExpression)* ; equalityExpression : left=instanceOfExpression ( ( op=EQUAL | op=NOTEQUAL ) right=instanceOfExpression )* ; instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; inExpression : left=relationalExpression ( 'not'? 'in' LPAREN drlExpression (COMMA drlExpression)* RPAREN )? ; -relationalExpression : drlExpression? ; - +relationalExpression : left=drlExpression (right=orRestriction)* ; +orRestriction : left=andRestriction (OR right=andRestriction)* ; +andRestriction : left=singleRestriction (AND right=singleRestriction)* ; +singleRestriction : op=relationalOperator drlExpression ; + +relationalOperator + : EQUAL + | NOTEQUAL + | LE + | GE + | GT + | LT + ; /* function := FUNCTION type? ID parameters(typed) chunk_{_} */ functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters block ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 236478d7fb8..12fcc510a08 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -244,6 +244,9 @@ public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { @Override public List visitConstraints(DRLParser.ConstraintsContext ctx) { + if (ctx == null) { + return new ArrayList<>(); + } List descrList = visitDescrChildren(ctx); return descrList.stream() .filter(ExprConstraintDescr.class::isInstance) @@ -253,57 +256,20 @@ public List visitConstraints(DRLParser.ConstraintsContext c @Override public ExprConstraintDescr visitConstraint(DRLParser.ConstraintContext ctx) { - Object constraint = super.visitConstraint(ctx); - if (constraint != null) { - String constraintString = constraint.toString(); - DRLParser.LabelContext label = ctx.label(); - if (label != null) { - constraintString = label.getText() + constraintString; - } - ExprConstraintDescr constraintDescr = new ExprConstraintDescr(constraintString); + String constraint = visitConstraintChildren(ctx); + if (!constraint.isEmpty()) { + ExprConstraintDescr constraintDescr = new ExprConstraintDescr(constraint); constraintDescr.setType(ExprConstraintDescr.Type.NAMED); return constraintDescr; } return null; } - @Override - public String visitDrlExpression(DRLParser.DrlExpressionContext ctx) { - return ctx.children.stream() - .map(c -> c instanceof TerminalNode ? c : c.accept(this)) - .filter(Objects::nonNull) - .map(Object::toString) - .collect(Collectors.joining(" ")); - } - - @Override - public String visitDrlPrimary(DRLParser.DrlPrimaryContext ctx) { - return ctx.children.stream() - .map(c -> c instanceof TerminalNode ? c : c.accept(this)) - .filter(Objects::nonNull) - .map(Object::toString) - .collect(Collectors.joining(" ")); - } - @Override public String visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { return ctx.getText(); } - @Override - public String visitDrlLiteral(DRLParser.DrlLiteralContext ctx) { - ParseTree node = ctx; - while (true) { - if (node instanceof TerminalNode) { - return node.toString(); - } - if (node.getChildCount() != 1) { - return super.visitDrlLiteral(ctx).toString(); - } - node = node.getChild(0); - } - } - @Override public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { ExistsDescr existsDescr = new ExistsDescr(); @@ -372,6 +338,34 @@ private List visitDescrChildren(RuleNode node) { return aggregator; } + // leaves of constraint concatenate return Strings + private String visitConstraintChildren(RuleNode node) { + return ((ParserRuleContext) node).children.stream() + .map(c -> c instanceof TerminalNode ? c : c.accept(this)) + .filter(Objects::nonNull) + .map(Object::toString) + .collect(Collectors.joining(" ")); + } + + @Override + public Object visitChildren(RuleNode node) { + if (hasConstraintAsAncestor(node)) { + return visitConstraintChildren(node); + } + return super.visitChildren(node); + } + + private boolean hasConstraintAsAncestor(RuleNode node) { + ParseTree parent = node.getParent(); + if (parent instanceof DRLParser.ConstraintContext) { + return true; + } else if (parent == null) { + return false; + } else { + return hasConstraintAsAncestor((RuleNode) parent); + } + } + private Optional visitFirstDescrChild(RuleNode node) { int n = node.getChildCount(); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 82404dee71a..da89c442562 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -13,7 +13,6 @@ import org.drools.drl.ast.descr.ExprConstraintDescr; import org.drools.drl.ast.descr.FromDescr; import org.drools.drl.ast.descr.FunctionDescr; -import org.drools.drl.ast.descr.FunctionImportDescr; import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.ImportDescr; import org.drools.drl.ast.descr.MVELExprDescr; @@ -24,6 +23,7 @@ import org.drools.drl.ast.descr.RuleDescr; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -49,7 +49,8 @@ private String readResource(final String filename) throws Exception { final StringBuilder sb = new StringBuilder(); try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { for (String line; (line = br.readLine()) != null; ) { - sb.append(line + "\n"); + sb.append(line); + sb.append("\n"); } } catch (IOException e) { e.printStackTrace(); @@ -183,16 +184,16 @@ void parse_globalWithOrWithoutSemi() throws Exception { assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getLhs().getDescrs()).hasSize(1); assertThat(pkg.getImports()).hasSize(1); assertThat(pkg.getGlobals()).hasSize(2); - final GlobalDescr foo = (GlobalDescr) pkg.getGlobals().get(0); + final GlobalDescr foo = pkg.getGlobals().get(0); assertThat(foo.getType()).isEqualTo("java.lang.String"); assertThat(foo.getIdentifier()).isEqualTo("foo"); - final GlobalDescr bar = (GlobalDescr) pkg.getGlobals().get(1); + final GlobalDescr bar = pkg.getGlobals().get(1); assertThat(bar.getType()).isEqualTo("java.lang.Integer"); assertThat(bar.getIdentifier()).isEqualTo("bar"); } @@ -204,12 +205,12 @@ void parse_functionImportWithNotExist() throws Exception { assertThat(pkg.getFunctionImports()).hasSize(2); - assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getTarget()).isEqualTo("abd.def.x"); - assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getStartCharacter()).isNotSameAs(-1); - assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(0)).getEndCharacter()).isNotSameAs(-1); - assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getTarget()).isEqualTo("qed.wah.*"); - assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getStartCharacter()).isNotSameAs(-1); - assertThat(((FunctionImportDescr) pkg.getFunctionImports().get(1)).getEndCharacter()).isNotSameAs(-1); + assertThat(pkg.getFunctionImports().get(0).getTarget()).isEqualTo("abd.def.x"); + assertThat(pkg.getFunctionImports().get(0).getStartCharacter()).isNotSameAs(-1); + assertThat(pkg.getFunctionImports().get(0).getEndCharacter()).isNotSameAs(-1); + assertThat(pkg.getFunctionImports().get(1).getTarget()).isEqualTo("qed.wah.*"); + assertThat(pkg.getFunctionImports().get(1).getStartCharacter()).isNotSameAs(-1); + assertThat(pkg.getFunctionImports().get(1).getEndCharacter()).isNotSameAs(-1); } @Test @@ -227,7 +228,7 @@ void parse_fromComplexAccessor() { assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("Invalid customer id"); assertThat(rule.getLhs().getDescrs()).hasSize(2); @@ -252,7 +253,7 @@ void parse_fromWithInlineList() { PackageDescr pkg = parser.parse(source); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("XYZ"); PatternDescr number = (PatternDescr) ((NotDescr) rule.getLhs().getDescrs().get(1)).getDescrs().get(0); @@ -269,10 +270,11 @@ void parse_fromWithInlineListMethod() { " System.err.println(\"Invalid customer id found!\"); \n" + " o.addError(\"Invalid customer id\"); \n" + "end \n"; + System.out.println(source); PackageDescr pkg = parser.parse(source); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("XYZ"); assertThat(parser.hasErrors()).isFalse(); @@ -295,7 +297,7 @@ void parse_fromWithInlineListIndex() { assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("XYZ"); assertThat(parser.hasErrors()).isFalse(); @@ -348,7 +350,7 @@ void parse_compatibleRestriction() { PackageDescr pkg = parser.parse(source); assertThat(pkg.getName()).isEqualTo("com.sample"); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("test"); ExprConstraintDescr expr = (ExprConstraintDescr) ((PatternDescr) rule.getLhs().getDescrs().get(0)).getDescrs().get(0); assertThat(expr.getText()).isEqualTo("( text == null || text2 matches \"\" )"); @@ -360,7 +362,7 @@ void parse_simpleConstraint() { PackageDescr pkg = parser.parse(source); assertThat(pkg.getName()).isEqualTo("com.sample"); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("test"); assertThat(rule.getLhs().getDescrs()).hasSize(1); @@ -377,7 +379,7 @@ void parse_stringEscapes() { String source = "package com.sample rule test when Cheese( type matches \"\\..*\\\\.\" ) then end"; PackageDescr pkg = parser.parse(source); assertThat(pkg.getName()).isEqualTo("com.sample"); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("test"); assertThat(rule.getLhs().getDescrs()).hasSize(1); @@ -392,7 +394,7 @@ void parse_stringEscapes() { void parse_dialectWithSingleQuotation() { final String source = "dialect 'mvel'"; PackageDescr pkg = parser.parse(source); - AttributeDescr attr = (AttributeDescr) pkg.getAttributes().get(0); + AttributeDescr attr = pkg.getAttributes().get(0); assertThat(attr.getName()).isEqualTo("dialect"); assertThat(attr.getValue()).isEqualTo("mvel"); } @@ -409,7 +411,7 @@ void parse_dialectWithDoubleQuotation() { @Test void parse_emptyRuleWithoutWhen() throws Exception { String source = readResource("empty_rule.drl"); // without WHEN - PackageDescr pkg = parser.parse(source); + parser.parse(source); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isTrue(); @@ -435,7 +437,7 @@ void parse_ternaryExpression() throws Exception { String source = readResource("ternary_expression.drl"); PackageDescr pkg = parser.parse(source); - final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final RuleDescr rule = pkg.getRules().get(0); assertThat(pkg.getRules()).hasSize(1); assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if (speed > speedLimit ? true : false;) pullEmOver();"); @@ -454,11 +456,11 @@ void parse_functionWithArrays() throws Exception { assertThat(pkg.getName()).isEqualTo("foo"); assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final RuleDescr rule = pkg.getRules().get(0); assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("yourFunction(new String[] {\"a\",\"b\",\"c\"});"); - final FunctionDescr func = (FunctionDescr) pkg.getFunctions().get(0); + final FunctionDescr func = pkg.getFunctions().get(0); assertThat(func.getReturnType()).isEqualTo("String[]"); assertThat(func.getParameterNames().get(0)).isEqualTo("args[]"); @@ -506,7 +508,7 @@ void parse_noLoop() throws Exception { assertThat(rule).isNotNull(); assertThat(rule.getName()).isEqualTo("rule1"); - final AttributeDescr att = (AttributeDescr) rule.getAttributes().get("no-loop"); + final AttributeDescr att = rule.getAttributes().get("no-loop"); assertThat(att.getValue()).isEqualTo("false"); assertThat(att.getName()).isEqualTo("no-loop"); } @@ -522,7 +524,7 @@ void parse_autofocus() throws Exception { assertThat(rule).isNotNull(); assertThat(rule.getName()).isEqualTo("rule1"); - final AttributeDescr att = (AttributeDescr) rule.getAttributes().get("auto-focus"); + final AttributeDescr att = rule.getAttributes().get("auto-focus"); assertThat(att.getValue()).isEqualTo("true"); assertThat(att.getName()).isEqualTo("auto-focus"); } @@ -538,7 +540,7 @@ void parse_ruleFlowGroup() throws Exception { assertThat(rule).isNotNull(); assertThat(rule.getName()).isEqualTo("rule1"); - final AttributeDescr att = (AttributeDescr) rule.getAttributes().get("ruleflow-group"); + final AttributeDescr att = rule.getAttributes().get("ruleflow-group"); assertThat(att.getValue()).isEqualTo("a group"); assertThat(att.getName()).isEqualTo("ruleflow-group"); } @@ -578,7 +580,7 @@ void parse_consequenceWithDeclaration() throws Exception { void parse_or() { final String text = "rule X when Person(age < 42, location==\"atlanta\") \nor\nPerson(name==\"bob\") then end"; PackageDescr pkg = parser.parse(text); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + RuleDescr rule = pkg.getRules().get(0); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); @@ -593,7 +595,7 @@ void parse_or() { void parse_lhsWithStringQuotes() { final String text = "rule X when Person( location==\"atlanta\\\"\") then end\n"; PackageDescr pkg = parser.parse(text); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + RuleDescr rule = pkg.getRules().get(0); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); @@ -609,7 +611,7 @@ void parse_lhsWithStringQuotes() { void parse_lhsWithStringQuotesEscapeChars() { final String text = "rule X when Cheese( $x: type, type == \"s\\tti\\\"lto\\nn\" ) then end\n"; PackageDescr pkg = parser.parse(text); - RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + RuleDescr rule = pkg.getRules().get(0); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(rule).isNotNull(); @@ -665,7 +667,7 @@ void parse_emptyPattern() throws Exception { assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(pkg.getRules()).hasSize(1); - final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get(0); + final RuleDescr ruleDescr = pkg.getRules().get(0); assertThat(ruleDescr.getName()).isEqualTo("simple rule"); assertThat(ruleDescr.getLhs()).isNotNull(); assertThat(ruleDescr.getLhs().getDescrs()).hasSize(1); @@ -783,4 +785,38 @@ void parse_simpleRuleWithBindings() throws Exception { assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if ( a == b ) { " + " assert( foo3 );" + "} else {" + " retract( foo4 );" + "}" + " System.out.println( a4 );"); } + + @Test + void parse_multipleRestrictionsConstraint() throws Exception { + RuleDescr rule = parseAndGetFirstRuleFromFile("restrictions_test.drl"); + assertThat(rule).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("consequence();"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + // The first pattern, with 2 restrictions on a single field (plus a + // connective) + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat( pattern.getConstraint().getDescrs()).hasSize(1); + + AndDescr and = (AndDescr) pattern.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + + // the second col, with 2 fields, the first with 2 restrictions, the + // second field with one + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); + + and = (AndDescr) pattern.getConstraint(); + fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace( "type == \"sedan\" || == \"wagon\""); + + // now the second field + fld = (ExprConstraintDescr) and.getDescrs().get( 1 ); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace( "age < 3"); + } } diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/restrictions_test.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/restrictions_test.drl new file mode 100644 index 00000000000..8a6d403cf30 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/restrictions_test.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +//this is for showing off all the new multi restriction stuff + +rule simple_rule + when + Person(age > 30 && < 40) + Vehicle(type == "sedan" || == "wagon", age < 3) + then + consequence(); +end From 413d4cfb65a4826c1c01c959e7b0fd3aa2231533 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 30 Jan 2023 17:23:45 +0900 Subject: [PATCH 027/141] [DROOLS-7271] Fully port RuleParserTest as MiscDRLParserTest with @Disabled and priority comment (#10) --- .../org/drools/parser/MiscDRLParserTest.java | 2490 ++++++++++++++++- .../org/drools/parser/Rule_with_Extends.drl | 23 + .../org/drools/parser/Rule_with_Metadata.drl | 25 + .../drools/parser/Rule_with_nested_LHS.drl | 26 + .../org/drools/parser/accumulate.drl | 23 + .../parser/accumulateExternalFunction.drl | 21 + .../parser/accumulateMultipleFunctions.drl | 28 + .../accumulateMultipleFunctionsConstraint.drl | 30 + .../org/drools/parser/accumulateReverse.drl | 24 + .../parser/accumulate_multi_pattern.drl | 23 + .../parser/accumulate_with_bindings.drl | 23 + .../parser/accumulate_with_nested_from.drl | 23 + .../org/drools/parser/and_or_rule.drl | 25 + .../org/drools/parser/basic_binding.drl | 25 + .../resources/org/drools/parser/bindings.drl | 27 + .../org/drools/parser/brackets_precedence.drl | 21 + .../resources/org/drools/parser/collect.drl | 20 + .../parser/collect_with_nested_from.drl | 22 + .../resources/org/drools/parser/comment.drl | 30 + .../resources/org/drools/parser/complex.dsl | 5 + .../parser/declare_type_with_fields.drl | 33 + .../org/drools/parser/enumeration.drl | 21 + .../org/drools/parser/escaped-string.drl | 21 + .../org/drools/parser/eval_multiple.drl | 24 + .../org/drools/parser/eval_parsing.drl | 24 + .../org/drools/parser/eval_with_newline.drl | 36 + .../parser/expander_multiple_constraints.dslr | 18 + .../expander_multiple_constraints_flush.dslr | 17 + .../drools/parser/expander_spread_lines.dslr | 19 + .../org/drools/parser/extra_lhs_newline.drl | 25 + .../resources/org/drools/parser/forall.drl | 21 + .../org/drools/parser/forallwithfrom.drl | 21 + .../resources/org/drools/parser/functions.drl | 41 + .../org/drools/parser/in_operator_test.drl | 24 + .../org/drools/parser/lhs_semicolon_delim.drl | 27 + .../drools/parser/multiple_constraints.dsl | 6 + .../org/drools/parser/multiple_rules.drl | 32 + .../parser/nested_conditional_elements.drl | 25 + .../drools/parser/not_exist_with_brackets.drl | 24 + .../org/drools/parser/not_with_constraint.drl | 29 + .../org/drools/parser/notin_operator_test.drl | 24 + .../org/drools/parser/or_binding.drl | 25 + .../org/drools/parser/or_binding_complex.drl | 25 + .../parser/or_binding_with_brackets.drl | 23 + .../resources/org/drools/parser/or_ce.drl | 24 + .../org/drools/parser/or_nesting.drl | 25 + .../org/drools/parser/package_attributes.drl | 38 + .../org/drools/parser/pluggable_operators.drl | 26 + .../org/drools/parser/qualified_classname.drl | 23 + .../org/drools/parser/query_and_rule.drl | 45 + .../org/drools/parser/rule_attributes.drl | 31 + .../org/drools/parser/rule_attributes2.drl | 44 + .../org/drools/parser/rule_attributes_alt.drl | 26 + .../parser/rule_calendars_attribute.drl | 24 + .../parser/rule_calendars_attribute2.drl | 24 + .../parser/rule_duration_expression.drl | 24 + .../drools/parser/rule_enabled_expression.drl | 25 + .../parser/rule_names_number_prefix.drl | 25 + .../resources/org/drools/parser/rule_not.drl | 22 + .../resources/org/drools/parser/semicolon.drl | 41 + .../org/drools/parser/simple_query.drl | 23 + .../org/drools/parser/soundslike_operator.drl | 28 + .../drools/parser/statement_ordering_1.drl | 43 + .../test_CommentLineNumbersInConsequence.drl | 32 + .../org/drools/parser/test_EndPosition.drl | 25 + .../org/drools/parser/type_with_meta.drl | 46 + .../resources/org/drools/parser/with_eval.drl | 23 + .../org/drools/parser/with_predicate.drl | 21 + .../org/drools/parser/with_retval.drl | 21 + 69 files changed, 4235 insertions(+), 13 deletions(-) create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Extends.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Metadata.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_nested_LHS.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateExternalFunction.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctions.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctionsConstraint.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateReverse.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_multi_pattern.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_bindings.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_nested_from.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/and_or_rule.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/basic_binding.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/bindings.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/brackets_precedence.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect_with_nested_from.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/comment.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/complex.dsl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declare_type_with_fields.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/enumeration.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/escaped-string.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_multiple.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_parsing.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_with_newline.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints.dslr create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints_flush.dslr create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_spread_lines.dslr create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/extra_lhs_newline.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forall.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forallwithfrom.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/functions.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/in_operator_test.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/lhs_semicolon_delim.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_constraints.dsl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_rules.drl create mode 100755 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/nested_conditional_elements.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_exist_with_brackets.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_with_constraint.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/notin_operator_test.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_complex.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_with_brackets.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_ce.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_nesting.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/package_attributes.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/pluggable_operators.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/qualified_classname.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/query_and_rule.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes2.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes_alt.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute2.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_duration_expression.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_enabled_expression.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_names_number_prefix.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_not.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/semicolon.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_query.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/soundslike_operator.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/statement_ordering_1.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_CommentLineNumbersInConsequence.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EndPosition.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/type_with_meta.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_eval.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_predicate.drl create mode 100644 drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_retval.drl diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index da89c442562..2dcaa0061c2 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -6,11 +6,25 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Pattern; +import org.drools.drl.ast.descr.AccumulateDescr; +import org.drools.drl.ast.descr.AccumulateImportDescr; import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.AnnotationDescr; import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.BehaviorDescr; +import org.drools.drl.ast.descr.CollectDescr; +import org.drools.drl.ast.descr.EntryPointDeclarationDescr; +import org.drools.drl.ast.descr.EntryPointDescr; +import org.drools.drl.ast.descr.EvalDescr; +import org.drools.drl.ast.descr.ExistsDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.ForallDescr; import org.drools.drl.ast.descr.FromDescr; import org.drools.drl.ast.descr.FunctionDescr; import org.drools.drl.ast.descr.GlobalDescr; @@ -20,7 +34,11 @@ import org.drools.drl.ast.descr.OrDescr; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.QueryDescr; import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.TypeDeclarationDescr; +import org.drools.drl.ast.descr.TypeFieldDescr; +import org.drools.drl.ast.descr.WindowDeclarationDescr; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -29,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; /* - * This test class is being ported from org.drools.mvel.compiler.lang.RuleParserTest + * This test class is ported from org.drools.mvel.compiler.lang.RuleParserTest */ class MiscDRLParserTest { @@ -58,15 +76,32 @@ private String readResource(final String filename) throws Exception { return sb.toString(); } - private RuleDescr parseAndGetFirstRule(String drl) { + private RuleDescr parseAndGetFirstRuleDescr(String drl) { PackageDescr pkg = parser.parse(drl); assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); assertThat(pkg.getRules()).isNotEmpty(); return pkg.getRules().get(0); } - private RuleDescr parseAndGetFirstRuleFromFile(String filename) throws Exception { - return parseAndGetFirstRule(readResource(filename)); + private RuleDescr parseAndGetFirstRuleDescrFromFile(String filename) throws Exception { + return parseAndGetFirstRuleDescr(readResource(filename)); + } + + private PackageDescr parseAndGetPackageDescrFromFile(String filename) throws Exception { + return parser.parse(readResource(filename)); + } + + private QueryDescr parseAndGetFirstQueryDescr(String drl) { + PackageDescr pkg = parser.parse(drl); + assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); + assertThat(pkg.getRules()).isNotEmpty(); + Optional optQuery = pkg.getRules().stream().filter(QueryDescr.class::isInstance).map(QueryDescr.class::cast).findFirst(); + assertThat(optQuery).isPresent(); + return optQuery.get(); + } + + private QueryDescr parseAndGetFirstQueryDescrFromFile(String filename) throws Exception { + return parseAndGetFirstQueryDescr(readResource(filename)); } @Test @@ -624,7 +659,7 @@ void parse_lhsWithStringQuotesEscapeChars() { @Test void parse_literalBoolAndNegativeNumbersRule() throws Exception { - RuleDescr rule = parseAndGetFirstRuleFromFile("literal_bool_and_negative.drl"); + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("literal_bool_and_negative.drl"); assertThat(rule).isNotNull(); @@ -678,7 +713,7 @@ void parse_emptyPattern() throws Exception { @Test void parse_simpleMethodCallWithFrom() throws Exception { - RuleDescr rule = parseAndGetFirstRuleFromFile("test_SimpleMethodCallWithFrom.drl"); + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleMethodCallWithFrom.drl"); final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final FromDescr from = (FromDescr) pattern.getSource(); final MVELExprDescr method = (MVELExprDescr) from.getDataSource(); @@ -688,7 +723,7 @@ void parse_simpleMethodCallWithFrom() throws Exception { @Test void parse_simpleFunctionCallWithFrom() throws Exception { - RuleDescr rule = parseAndGetFirstRuleFromFile("test_SimpleFunctionCallWithFrom.drl"); + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleFunctionCallWithFrom.drl"); final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final FromDescr from = (FromDescr) pattern.getSource(); final MVELExprDescr func = (MVELExprDescr) from.getDataSource(); @@ -698,7 +733,7 @@ void parse_simpleFunctionCallWithFrom() throws Exception { @Test void parse_simpleAccessorWithFrom() throws Exception { - RuleDescr rule = parseAndGetFirstRuleFromFile("test_SimpleAccessorWithFrom.drl"); + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleAccessorWithFrom.drl"); final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); final FromDescr from = (FromDescr) pattern.getSource(); final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); @@ -708,7 +743,7 @@ void parse_simpleAccessorWithFrom() throws Exception { @Test void parse_simpleAccessorAndArgWithFrom() throws Exception { - RuleDescr rule = parseAndGetFirstRuleFromFile("test_SimpleAccessorArgWithFrom.drl"); + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleAccessorArgWithFrom.drl"); final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); final FromDescr from = (FromDescr) pattern.getSource(); final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); @@ -718,7 +753,7 @@ void parse_simpleAccessorAndArgWithFrom() throws Exception { @Test void parse_complexChainedAccessor() throws Exception { - RuleDescr rule = parseAndGetFirstRuleFromFile("test_ComplexChainedCallWithFrom.drl"); + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_ComplexChainedCallWithFrom.drl"); final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); final FromDescr from = (FromDescr) pattern.getSource(); @@ -729,7 +764,7 @@ void parse_complexChainedAccessor() throws Exception { @Test void parse_from() throws Exception { - RuleDescr rule = parseAndGetFirstRuleFromFile("from.drl"); + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("from.drl"); assertThat(rule).isNotNull(); assertThat(rule.getName()).isEqualTo("using_from"); @@ -739,7 +774,7 @@ void parse_from() throws Exception { @Test void parse_simpleRuleWithBindings() throws Exception { - RuleDescr rule = parseAndGetFirstRuleFromFile("simple_rule.drl"); + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("simple_rule.drl"); assertThat(rule).isNotNull(); assertThat(rule.getName()).isEqualTo("simple_rule"); @@ -788,7 +823,7 @@ void parse_simpleRuleWithBindings() throws Exception { @Test void parse_multipleRestrictionsConstraint() throws Exception { - RuleDescr rule = parseAndGetFirstRuleFromFile("restrictions_test.drl"); + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("restrictions_test.drl"); assertThat(rule).isNotNull(); assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("consequence();"); @@ -819,4 +854,2433 @@ void parse_multipleRestrictionsConstraint() throws Exception { fld = (ExprConstraintDescr) and.getDescrs().get( 1 ); assertThat(fld.getExpression()).isEqualToIgnoringWhitespace( "age < 3"); } + +//------------------------------------------------------------------------- +// DROOLS-7271 : ported from RuleParserTest +// Failing tests are annotated with @Disabled. We can fix issues one by one +//------------------------------------------------------------------------- + + @Disabled("Priority : Mid | implement Descr lineNumber") + @Test + public void parse_LineNumberInAST() throws Exception { + // also see testSimpleExpander to see how this works with an expander + // (should be the same). + + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "simple_rule.drl" ); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + + assertThat(rule.getConsequenceLine()).isEqualTo(22); + assertThat(rule.getConsequencePattern()).isEqualTo(2); + + final AndDescr lhs = rule.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs().size()).isEqualTo(3); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + final PatternDescr third = (PatternDescr) lhs.getDescrs().get( 2 ); + assertThat(third.getObjectType()).isEqualTo("Baz"); + + assertThat(first.getLine()).isEqualTo(19); + assertThat(second.getLine()).isEqualTo(20); + assertThat(third.getLine()).isEqualTo(21); + } + + @Disabled("Priority : High | Failed to parse comments in RHS") + @Test + public void parse_LineNumberIncludingCommentsInRHS() throws Exception { + PackageDescr pkg = parseAndGetPackageDescrFromFile( + "test_CommentLineNumbersInConsequence.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + final String rhs = (String) ((RuleDescr) pkg.getRules().get( 0 )).getConsequence(); + String expected = "\\s*//woot$\\s*first$\\s*$\\s*//$\\s*$\\s*/\\* lala$\\s*$\\s*\\*/$\\s*second$\\s*"; + assertThat(Pattern.compile(expected, + Pattern.DOTALL | Pattern.MULTILINE).matcher(rhs).matches()).isTrue(); + } + + @Disabled("Priority : High | Implement semicolon delimiter") + @Test + public void parse_LhsSemicolonDelim() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "lhs_semicolon_delim.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + + final AndDescr lhs = rule.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs().size()).isEqualTo(3); + + // System.err.println( lhs.getDescrs() ); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + + assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); + + // LiteralDescr constraint = (LiteralDescr) first.getDescrs().get( 0 ); + AndDescr and = (AndDescr) first.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + assertThat(fld).isNotNull(); + + assertThat(fld.getExpression()).isEqualTo("a==3"); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + assertThat(second.getDescrs().size()).isEqualTo(1); + + final ExprConstraintDescr fieldBindingDescr = (ExprConstraintDescr) second.getDescrs().get( 0 ); + assertThat(fieldBindingDescr.getExpression()).isEqualTo("a4:a==4"); + + // Check third pattern + final PatternDescr third = (PatternDescr) lhs.getDescrs().get( 2 ); + assertThat(third.getIdentifier()).isNull(); + assertThat(third.getObjectType()).isEqualTo("Baz"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if ( a == b ) { " + " assert( foo3 );" + "} else {" + " retract( foo4 );" + "}" + " System.out.println( a4 );"); + } + + @Test + public void parse_NotNode() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_not.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(rule).isNotNull(); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + final AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + final NotDescr not = (NotDescr) lhs.getDescrs().get( 0 ); + assertThat(not.getDescrs().size()).isEqualTo(1); + final PatternDescr pattern = (PatternDescr) not.getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + + final AndDescr and = (AndDescr) pattern.getConstraint(); + final ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); + } + + @Test + public void parse_NotExistWithBrackets() throws Exception { + + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "not_exist_with_brackets.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + assertThat(rule).isNotNull(); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + final AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs().size()).isEqualTo(2); + final NotDescr not = (NotDescr) lhs.getDescrs().get( 0 ); + assertThat(not.getDescrs().size()).isEqualTo(1); + final PatternDescr pattern = (PatternDescr) not.getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + + final ExistsDescr ex = (ExistsDescr) lhs.getDescrs().get(1 ); + assertThat(ex.getDescrs().size()).isEqualTo(1); + final PatternDescr exPattern = (PatternDescr) ex.getDescrs().get( 0 ); + assertThat(exPattern.getObjectType()).isEqualTo("Foo"); + } + + @Disabled("Priority : High | Implement query") + @Test + public void parse_SimpleQuery() throws Exception { + final QueryDescr query = parseAndGetFirstQueryDescrFromFile( + "simple_query.drl" ); + + assertThat(query).isNotNull(); + + assertThat(query.getName()).isEqualTo("simple_query"); + + final AndDescr lhs = query.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs().size()).isEqualTo(3); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + + assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); + + AndDescr and = (AndDescr) first.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + assertThat(fld).isNotNull(); + + assertThat(fld.getExpression()).isEqualTo("a==3"); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + assertThat(second.getDescrs().size()).isEqualTo(1); + // check it has field bindings. + final ExprConstraintDescr bindingDescr = (ExprConstraintDescr) second.getDescrs().get( 0 ); + assertThat(bindingDescr.getExpression()).isEqualTo("a4:a==4"); + } + + @Disabled("Priority : High | Implement query") + @Test + public void parse_QueryRuleMixed() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "query_and_rule.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(4); // as queries are rules + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getName()).isEqualTo("bar"); + + QueryDescr query = (QueryDescr) pkg.getRules().get( 1 ); + assertThat(query.getName()).isEqualTo("simple_query"); + + rule = (RuleDescr) pkg.getRules().get( 2 ); + assertThat(rule.getName()).isEqualTo("bar2"); + + query = (QueryDescr) pkg.getRules().get( 3 ); + assertThat(query.getName()).isEqualTo("simple_query2"); + } + + @Test + public void parse_MultipleRules() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "multiple_rules.drl" ); + + final List rules = pkg.getRules(); + + assertThat(rules.size()).isEqualTo(2); + + final RuleDescr rule0 = rules.get( 0 ); + assertThat(rule0.getName()).isEqualTo("Like Stilton"); + + final RuleDescr rule1 = rules.get( 1 ); + assertThat(rule1.getName()).isEqualTo("Like Cheddar"); + + // checkout the first rule + AndDescr lhs = rule1.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + assertThat((String) rule0.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"I like \" + t);"); + + // Check first pattern + PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(first.getObjectType()).isEqualTo("Cheese"); + + // checkout the second rule + lhs = rule1.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + assertThat((String) rule1.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"I like \" + t);"); + + // Check first pattern + first = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(first.getObjectType()).isEqualTo("Cheese"); + } + + @Disabled("Priority : low | Not yet support DSL") + @Test + public void parse_ExpanderLineSpread() throws Exception { +// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); +// final PackageDescr pkg = parser.parse( this.getReader( "expander_spread_lines.dslr" ), +// this.getReader( "complex.dsl" ) ); +// +// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); +// +// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); +// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); +// +// final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); +// assertThat(or.getDescrs().size()).isEqualTo(2); +// assertThat( (String) rule.getConsequence() ).isNotNull(); + + } + + @Disabled("Priority : low | Not yet support DSL") + @Test + public void parse_ExpanderMultipleConstraints() throws Exception { +// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); +// final PackageDescr pkg = parser.parse( this.getReader( "expander_multiple_constraints.dslr" ), +// this.getReader( "multiple_constraints.dsl" ) ); +// +// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); +// +// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); +// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); +// +// PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); +// assertThat(pattern.getObjectType()).isEqualTo("Person"); +// +// assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); +// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); +// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); +// +// pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); +// assertThat(pattern.getObjectType()).isEqualTo("Bar"); +// +// assertThat( (String) rule.getConsequence() ).isNotNull(); + + } + + @Disabled("Priority : low | Not yet support DSL") + @Test + public void parse_ExpanderMultipleConstraintsFlush() throws Exception { +// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); +// // this is similar to the other test, but it requires a flush to add the +// // constraints +// final PackageDescr pkg = parser.parse( this.getReader( "expander_multiple_constraints_flush.dslr" ), +// this.getReader( "multiple_constraints.dsl" ) ); +// +// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); +// +// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); +// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); +// +// final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); +// assertThat(pattern.getObjectType()).isEqualTo("Person"); +// +// assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); +// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); +// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); +// +// assertThat( (String) rule.getConsequence() ).isNotNull(); + + } + + @Test + public void parse_BasicBinding() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "basic_binding.drl" ); + + final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get( 0 ); + + final AndDescr lhs = ruleDescr.getLhs(); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese.getConstraint().getDescrs().size()).isEqualTo(1); + final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get( 0 ); + assertThat(fieldBinding.getExpression()).isEqualToIgnoringWhitespace("$type:type"); + } + + @Test + public void parse_BoundVariables() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "bindings.drl" ); + + final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get( 0 ); + + final AndDescr lhs = ruleDescr.getLhs(); + assertThat(lhs.getDescrs().size()).isEqualTo(2); + final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get( 0 ); + assertThat(fieldBinding.getExpression()).isEqualTo("$type : type == \"stilton\""); + + final PatternDescr person = (PatternDescr) lhs.getDescrs().get( 1 ); + assertThat(person.getDescrs().size()).isEqualTo(2); + fieldBinding = (ExprConstraintDescr) person.getDescrs().get( 0 ); + assertThat(fieldBinding.getExpression()).isEqualTo("$name : name == \"bob\""); + + ExprConstraintDescr fld = (ExprConstraintDescr) person.getDescrs().get( 1 ); + assertThat(fld.getExpression()).isEqualTo("likes == $type"); + } + + @Disabled("Priority : High | Failed to parse and/or with parentheses in LHS") + @Test + public void parse_OrNesting() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_nesting.drl" ); + + assertThat(pkg).isNotNull(); + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + + final PatternDescr first = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(first.getObjectType()).isEqualTo("Person"); + + final AndDescr and = (AndDescr) or.getDescrs().get( 1 ); + assertThat(and.getDescrs().size()).isEqualTo(2); + + final PatternDescr left = (PatternDescr) and.getDescrs().get( 0 ); + assertThat(left.getObjectType()).isEqualTo("Person"); + + final PatternDescr right = (PatternDescr) and.getDescrs().get( 1 ); + assertThat(right.getObjectType()).isEqualTo("Cheese"); + } + + /** Test that explicit "&&", "||" works as expected */ + @Test + public void parse_AndOrRules() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "and_or_rule.drl" ); + + assertThat(pkg).isNotNull(); + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + // we will have 3 children under the main And node + final AndDescr and = rule.getLhs(); + assertThat(and.getDescrs().size()).isEqualTo(3); + + PatternDescr left = (PatternDescr) and.getDescrs().get( 0 ); + PatternDescr right = (PatternDescr) and.getDescrs().get( 1 ); + assertThat(left.getObjectType()).isEqualTo("Person"); + assertThat(right.getObjectType()).isEqualTo("Cheese"); + + assertThat(left.getConstraint().getDescrs().size()).isEqualTo(1); + + ExprConstraintDescr fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualTo("name == \"mark\""); + + assertThat(right.getConstraint().getDescrs().size()).isEqualTo(1); + + fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); + + // now the "||" part + final OrDescr or = (OrDescr) and.getDescrs().get( 2 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + left = (PatternDescr) or.getDescrs().get( 0 ); + right = (PatternDescr) or.getDescrs().get( 1 ); + assertThat(left.getObjectType()).isEqualTo("Person"); + assertThat(right.getObjectType()).isEqualTo("Cheese"); + assertThat(left.getConstraint().getDescrs().size()).isEqualTo(1); + + fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualTo("name == \"mark\""); + + assertThat(right.getConstraint().getDescrs().size()).isEqualTo(1); + + fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" );"); + } + + /** test basic foo : Fact() || Fact() stuff */ + @Test + public void parse_OrWithBinding() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_binding.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + + final PatternDescr leftPattern = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(leftPattern.getObjectType()).isEqualTo("Person"); + assertThat(leftPattern.getIdentifier()).isEqualTo("foo"); + + final PatternDescr rightPattern = (PatternDescr) or.getDescrs().get( 1 ); + assertThat(rightPattern.getObjectType()).isEqualTo("Person"); + assertThat(rightPattern.getIdentifier()).isEqualTo("foo"); + + final PatternDescr cheeseDescr = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(cheeseDescr.getObjectType()).isEqualTo("Cheese"); + assertThat(cheeseDescr.getIdentifier()).isEqualTo(null); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); + } + + /** test basic foo : Fact() || Fact() stuff binding to an "or" */ + @Test + public void parse_OrBindingComplex() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_binding_complex.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + + // first fact + final PatternDescr firstFact = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(firstFact.getObjectType()).isEqualTo("Person"); + assertThat(firstFact.getIdentifier()).isEqualTo("foo"); + + // second "option" + final PatternDescr secondFact = (PatternDescr) or.getDescrs().get( 1 ); + assertThat(secondFact.getObjectType()).isEqualTo("Person"); + assertThat(secondFact.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(secondFact.getIdentifier()).isEqualTo("foo"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); + } + + @Test + public void parse_OrBindingWithBrackets() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_binding_with_brackets.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + + // first fact + final PatternDescr firstFact = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(firstFact.getObjectType()).isEqualTo("Person"); + assertThat(firstFact.getIdentifier()).isEqualTo("foo"); + + // second "option" + final PatternDescr secondFact = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(secondFact.getObjectType()).isEqualTo("Person"); + assertThat(secondFact.getIdentifier()).isEqualTo("foo"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); + } + + @Disabled("Priority : High | Failed to parse complex parentheses") + @Test + public void parse_BracketsPrecedence() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "brackets_precedence.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + + assertThat(rootAnd.getDescrs().size()).isEqualTo(2); + + final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get( 0 ); + + assertThat(leftOr.getDescrs().size()).isEqualTo(2); + final NotDescr not = (NotDescr) leftOr.getDescrs().get( 0 ); + final PatternDescr foo1 = (PatternDescr) not.getDescrs().get( 0 ); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final PatternDescr foo2 = (PatternDescr) leftOr.getDescrs().get( 1 ); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + + final OrDescr rightOr = (OrDescr) rootAnd.getDescrs().get( 1 ); + + assertThat(rightOr.getDescrs().size()).isEqualTo(2); + final PatternDescr shoes = (PatternDescr) rightOr.getDescrs().get( 0 ); + assertThat(shoes.getObjectType()).isEqualTo("Shoes"); + final PatternDescr butt = (PatternDescr) rightOr.getDescrs().get( 1 ); + assertThat(butt.getObjectType()).isEqualTo("Butt"); + } + + @Disabled("Priority : High | Implement eval") + @Test + public void parse_EvalMultiple() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "eval_multiple.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(4); + + final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(0 ); + assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace( "abc(\"foo\") + 5"); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("Foo"); + + } + + @Disabled("Priority : High | Implement eval") + @Test + public void parse_WithEval() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "with_eval.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(3); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Foo"); + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("Bar"); + + final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get( 2 ); + assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace( "abc(\"foo\")"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "Kapow"); + } + + @Test + public void parse_WithRetval() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "with_retval.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(col.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(col.getObjectType()).isEqualTo("Foo"); + final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("name== (a + b)"); + } + + @Test + public void parse_WithPredicate() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "with_predicate.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + AndDescr and = (AndDescr) col.getConstraint(); + assertThat(and.getDescrs().size()).isEqualTo(2); + + final ExprConstraintDescr field = (ExprConstraintDescr) col.getDescrs().get( 0 ); + final ExprConstraintDescr pred = (ExprConstraintDescr) and.getDescrs().get( 1 ); + assertThat(field.getExpression()).isEqualToIgnoringWhitespace("$age2:age"); + assertThat(pred.getExpression()).isEqualToIgnoringWhitespace( "$age2 == $age1+2"); + } + + @Test + public void parse_NotWithConstraint() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "not_with_constraint.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fieldBinding.getExpression()).isEqualToIgnoringWhitespace("$likes:like"); + + final NotDescr not = (NotDescr) rule.getLhs().getDescrs().get( 1 ); + pattern = (PatternDescr) not.getDescrs().get( 0 ); + + final ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type == $likes"); + } + + @Disabled("Priority : Mid | Implement Descr lineNumber") + @Test + public void parse_Functions() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "functions.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(2); + + final List functions = pkg.getFunctions(); + assertThat(functions.size()).isEqualTo(2); + + FunctionDescr func = functions.get( 0 ); + assertThat(func.getName()).isEqualTo("functionA"); + assertThat(func.getReturnType()).isEqualTo("String"); + assertThat(func.getParameterNames().size()).isEqualTo(2); + assertThat(func.getParameterTypes().size()).isEqualTo(2); + assertThat(func.getLine()).isEqualTo(19); + assertThat(func.getColumn()).isEqualTo(0); + + assertThat(func.getParameterTypes().get(0)).isEqualTo("String"); + assertThat(func.getParameterNames().get(0)).isEqualTo("s"); + + assertThat(func.getParameterTypes().get(1)).isEqualTo("Integer"); + assertThat(func.getParameterNames().get(1)).isEqualTo("i"); + + assertThat(func.getBody()).isEqualToIgnoringWhitespace( "foo();"); + + func = functions.get( 1 ); + assertThat(func.getName()).isEqualTo("functionB"); + assertThat(func.getText()).isEqualToIgnoringWhitespace( "bar();"); + } + + @Test + public void parse_Comment() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "comment.drl" ); + + assertThat(pkg).isNotNull(); + + assertThat(pkg.getName()).isEqualTo("foo.bar"); + } + + @Disabled("Priority : High | Parse attribute without value => true") + @Test + public void parse_Attributes() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_attributes.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(6); + + 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"); + assertThat(at.getValue()).isEqualTo("my_group"); + + at = (AttributeDescr) attrs.get( "no-loop" ); + assertThat(at.getName()).isEqualTo("no-loop"); + assertThat(at.getValue()).isEqualTo("true"); + + at = (AttributeDescr) attrs.get( "duration" ); + assertThat(at.getName()).isEqualTo("duration"); + assertThat(at.getValue()).isEqualTo("42"); + + at = (AttributeDescr) attrs.get( "activation-group" ); + assertThat(at.getName()).isEqualTo("activation-group"); + assertThat(at.getValue()).isEqualTo("my_activation_group"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Disabled("Priority : High | Parse attribute with parentheses") + @Test + public void parse_Attributes2() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "rule_attributes2.drl" ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + List rules = pkg.getRules(); + assertThat(rules.size()).isEqualTo(3); + + RuleDescr rule = rules.get( 0 ); + assertThat(rule.getName()).isEqualTo("rule1"); + Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + 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"); + assertThat(at.getValue()).isEqualTo("my_group"); + + rule = rules.get( 1 ); + assertThat(rule.getName()).isEqualTo("rule2"); + attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + at = (AttributeDescr) attrs.get( "salience" ); + assertThat(at.getName()).isEqualTo("salience"); + assertThat(at.getValue()).isEqualTo("(Integer.MIN_VALUE)"); + at = (AttributeDescr) attrs.get( "no-loop" ); + assertThat(at.getName()).isEqualTo("no-loop"); + + rule = rules.get( 2 ); + assertThat(rule.getName()).isEqualTo("rule3"); + attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + at = (AttributeDescr) attrs.get( "enabled" ); + assertThat(at.getName()).isEqualTo("enabled"); + assertThat(at.getValue()).isEqualTo("(Boolean.TRUE)"); + at = (AttributeDescr) attrs.get( "activation-group" ); + assertThat(at.getName()).isEqualTo("activation-group"); + assertThat(at.getValue()).isEqualTo("my_activation_group"); + + } + + @Disabled("Priority : High | Parse attribute without value => true") + @Test + public void parse_AttributeRefract() throws Exception { + final String source = "rule Test refract when Person() then end"; + + PackageDescr pkg = parser.parse( + source ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + assertThat(rule.getName()).isEqualTo("Test"); + Map attributes = rule.getAttributes(); + assertThat(attributes.size()).isEqualTo(1); + AttributeDescr refract = attributes.get( "refract" ); + assertThat(refract).isNotNull(); + assertThat(refract.getValue()).isEqualTo("true"); + + } + + @Disabled("Priority : High | Parse attribute with parentheses") + @Test + public void parse_EnabledExpression() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_enabled_expression.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(3); + + AttributeDescr at = (AttributeDescr) attrs.get( "enabled" ); + assertThat(at.getName()).isEqualTo("enabled"); + assertThat(at.getValue()).isEqualTo("( 1 + 1 == 2 )"); + + at = (AttributeDescr) attrs.get( "salience" ); + assertThat(at.getName()).isEqualTo("salience"); + assertThat(at.getValue()).isEqualTo("( 1+2 )"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Disabled("Priority : High | Parse attribute with parentheses") + @Test + public void parse_DurationExpression() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_duration_expression.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + + AttributeDescr at = (AttributeDescr) attrs.get( "duration" ); + assertThat(at.getName()).isEqualTo("duration"); + assertThat(at.getValue()).isEqualTo("1h30m"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Disabled("Priority : Mid | Parse calendar attribute") + @Test + public void parse_Calendars() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_calendars_attribute.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + + AttributeDescr at = (AttributeDescr) attrs.get( "calendars" ); + assertThat(at.getName()).isEqualTo("calendars"); + assertThat(at.getValue()).isEqualTo("[ \"cal1\" ]"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Disabled("Priority : Mid | Parse calendar attribute") + @Test + public void parse_Calendars2() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_calendars_attribute2.drl" ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + + AttributeDescr at = (AttributeDescr) attrs.get( "calendars" ); + assertThat(at.getName()).isEqualTo("calendars"); + assertThat(at.getValue()).isEqualTo("[ \"cal 1\", \"cal 2\", \"cal 3\" ]"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Disabled("Priority : Low | Not written in docs nor other unit tests. Drop the support?") + @Test + public void parse_Attributes_alternateSyntax() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_attributes_alt.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(6); + + 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"); + assertThat(at.getValue()).isEqualTo("my_group"); + + at = (AttributeDescr) attrs.get( "no-loop" ); + assertThat(at.getName()).isEqualTo("no-loop"); + assertThat(at.getValue()).isEqualTo("true"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + + at = (AttributeDescr) attrs.get( "duration" ); + assertThat(at.getName()).isEqualTo("duration"); + assertThat(at.getValue()).isEqualTo("42"); + + at = (AttributeDescr) attrs.get( "activation-group" ); + assertThat(at.getName()).isEqualTo("activation-group"); + assertThat(at.getValue()).isEqualTo("my_activation_group"); + } + + @Test + public void parse_Enumeration() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "enumeration.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(col.getObjectType()).isEqualTo("Foo"); + assertThat(col.getConstraint().getDescrs().size()).isEqualTo(1); + final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get( 0 ); + + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == Foo.BAR"); + } + + @Test + public void parse_ExtraLhsNewline() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "extra_lhs_newline.drl" ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + } + + @Disabled("Priority : Low | Implement soundslike") + @Test + public void parse_SoundsLike() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "soundslike_operator.drl" ); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + PatternDescr pat = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + pat.getConstraint(); + } + + @Disabled("Priority : High | Parse attribute agenda-group") + @Test + public void parse_PackageAttributes() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "package_attributes.drl" ); + + AttributeDescr at = (AttributeDescr) pkg.getAttributes().get( 0 ); + assertThat(at.getName()).isEqualTo("agenda-group"); + assertThat(at.getValue()).isEqualTo("x"); + at = (AttributeDescr) pkg.getAttributes().get( 1 ); + assertThat(at.getName()).isEqualTo("dialect"); + assertThat(at.getValue()).isEqualTo("java"); + + assertThat(pkg.getRules().size()).isEqualTo(2); + + assertThat(pkg.getImports().size()).isEqualTo(2); + + 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"); + assertThat(at.getValue()).isEqualTo("x"); + at = (AttributeDescr) rule.getAttributes().get( "dialect" ); + assertThat(at.getName()).isEqualTo("dialect"); + assertThat(at.getValue()).isEqualTo("java"); + + rule = (RuleDescr) pkg.getRules().get( 1 ); + assertThat(rule.getName()).isEqualTo("baz"); + 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"); + assertThat(at.getValue()).isEqualTo("x"); + + } + + @Test + public void parse_StatementOrdering1() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "statement_ordering_1.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(2); + + assertThat(((RuleDescr) pkg.getRules().get(0)).getName()).isEqualTo("foo"); + assertThat(((RuleDescr) pkg.getRules().get(1)).getName()).isEqualTo("bar"); + + assertThat(pkg.getFunctions().size()).isEqualTo(2); + + assertThat(((FunctionDescr) pkg.getFunctions().get(0)).getName()).isEqualTo("cheeseIt"); + assertThat(((FunctionDescr) pkg.getFunctions().get(1)).getName()).isEqualTo("uncheeseIt"); + + assertThat(pkg.getImports().size()).isEqualTo(4); + assertThat(((ImportDescr) pkg.getImports().get(0)).getTarget()).isEqualTo("im.one"); + assertThat(((ImportDescr) pkg.getImports().get(1)).getTarget()).isEqualTo("im.two"); + assertThat(((ImportDescr) pkg.getImports().get(2)).getTarget()).isEqualTo("im.three"); + assertThat(((ImportDescr) pkg.getImports().get(3)).getTarget()).isEqualTo("im.four"); + } + + @Test + public void parse_RuleNamesStartingWithNumbers() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "rule_names_number_prefix.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(2); + + assertThat(((RuleDescr) pkg.getRules().get(0)).getName()).isEqualTo("1. Do Stuff!"); + assertThat(((RuleDescr) pkg.getRules().get(1)).getName()).isEqualTo("2. Do More Stuff!"); + } + + @Test + public void parse_EvalWithNewline() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "eval_with_newline.drl"); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + } + + @Disabled("Priority : Mid | implement Descr lineNumber") + @Test + public void parse_EndPosition() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "test_EndPosition.drl" ); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(col.getLine()).isEqualTo(21); + assertThat(col.getEndLine()).isEqualTo(23); + } + + @Test + public void parse_QualifiedClassname() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "qualified_classname.drl" ); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + final PatternDescr p = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + assertThat(p.getObjectType()).isEqualTo("com.cheeseco.Cheese"); + } + + @Disabled("Priority : High | Implement accumulate") + @Test + public void parse_Accumulate() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;"); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;"); + assertThat(accum.getReverseCode()).isNull(); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)"); + + assertThat(accum.isExternalFunction()).isFalse(); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Disabled("Priority : High | Implement accumulate") + @Test + public void parse_AccumulateWithBindings() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate_with_bindings.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace( "$counter"); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;"); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;"); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Disabled("Priority : High | Implement from collect") + @Test + public void parse_Collect() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "collect.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final CollectDescr collect = (CollectDescr) outPattern.getSource(); + + final PatternDescr pattern = (PatternDescr) collect.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Test + public void parse_Predicate2() throws Exception { + // predicates are also prefixed by the eval keyword + final RuleDescr rule = parseAndGetFirstRuleDescr( + "rule X when Foo(eval( $var.equals(\"xyz\") )) then end" ); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final List< ? > constraints = pattern.getConstraint().getDescrs(); + assertThat(constraints.size()).isEqualTo(1); + + final ExprConstraintDescr predicate = (ExprConstraintDescr) constraints.get( 0 ); + assertThat(predicate.getExpression()).isEqualToIgnoringWhitespace("eval( $var.equals(\"xyz\") )"); + } + + @Test + public void parse_EscapedStrings() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "escaped-string.drl" ); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("test_Quotes"); + + final String expected = "String s = \"\\\"\\n\\t\\\\\";"; + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( expected); + } + + @Disabled("Priority : High | parse nested parentheses") + @Test + public void parse_NestedCEs() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "nested_conditional_elements.drl" ); + + assertThat(rule).isNotNull(); + + final AndDescr root = rule.getLhs(); + final NotDescr not1 = (NotDescr) root.getDescrs().get( 0 ); + final AndDescr and1 = (AndDescr) not1.getDescrs().get( 0 ); + + final PatternDescr state = (PatternDescr) and1.getDescrs().get( 0 ); + final NotDescr not2 = (NotDescr) and1.getDescrs().get( 1 ); + final AndDescr and2 = (AndDescr) not2.getDescrs().get( 0 ); + final PatternDescr person = (PatternDescr) and2.getDescrs().get( 0 ); + final PatternDescr cheese = (PatternDescr) and2.getDescrs().get( 1 ); + + final PatternDescr person2 = (PatternDescr) root.getDescrs().get( 1 ); + final OrDescr or = (OrDescr) root.getDescrs().get( 2 ); + final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get( 0 ); + final PatternDescr cheese3 = (PatternDescr) or.getDescrs().get( 1 ); + + assertThat("State").isEqualTo(state.getObjectType()); + assertThat("Person").isEqualTo(person.getObjectType()); + assertThat("Cheese").isEqualTo(cheese.getObjectType()); + assertThat("Person").isEqualTo(person2.getObjectType()); + assertThat("Cheese").isEqualTo(cheese2.getObjectType()); + assertThat("Cheese").isEqualTo(cheese3.getObjectType()); + } + + @Disabled("Priority : High | Implement forall") + @Test + public void parse_Forall() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "forall.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0 ); + + assertThat(forall.getDescrs().size()).isEqualTo(2); + final PatternDescr pattern = forall.getBasePattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + final List remaining = forall.getRemainingPatterns(); + assertThat(remaining.size()).isEqualTo(1); + final PatternDescr cheese = (PatternDescr) remaining.get( 0 ); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + } + + @Disabled("Priority : High | Implement forall") + @Test + public void parse_ForallWithFrom() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "forallwithfrom.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get( 0 ); + + assertThat(forall.getDescrs().size()).isEqualTo(2); + final PatternDescr pattern = forall.getBasePattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(((FromDescr) pattern.getSource()).getDataSource().toString()).isEqualTo("$village"); + final List remaining = forall.getRemainingPatterns(); + assertThat(remaining.size()).isEqualTo(1); + final PatternDescr cheese = (PatternDescr) remaining.get( 0 ); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + assertThat(((FromDescr) cheese.getSource()).getDataSource().toString()).isEqualTo("$cheesery"); + } + + @Disabled("Priority : High | Implement memberOf") + @Test + public void parse_Memberof() throws Exception { + final String text = "rule X when Country( $cities : city )\nPerson( city memberOf $cities )\n then end"; + AndDescr descrs = parseAndGetFirstRuleDescr( + text).getLhs(); + + assertThat(descrs.getDescrs().size()).isEqualTo(2); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 1 ); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); + + assertThat(fieldConstr.getExpression()).isEqualTo("city memberOf $cities"); + } + + @Disabled("Priority : High | Implement not memberOf") + @Test + public void parse_NotMemberof() throws Exception { + final String text = "rule X when Country( $cities : city )\nPerson( city not memberOf $cities ) then end\n"; + AndDescr descrs = parseAndGetFirstRuleDescr( + text).getLhs(); + + assertThat(descrs.getDescrs().size()).isEqualTo(2); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 1 ); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); + + assertThat(fieldConstr.getExpression()).isEqualTo("city not memberOf $cities"); + } + + @Test + public void parse_InOperator() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "in_operator_test.drl" ); + + assertThat(rule).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "consequence();"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + // The first pattern, with 2 restrictions on a single field (plus a + // connective) + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + + ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + + // the second col, with 2 fields, the first with 2 restrictions, the + // second field with one + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); + + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type in ( \"sedan\", \"wagon\" )"); + + // now the second field + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 1 ); + assertThat(fld.getExpression()).isEqualTo("age < 3"); + + } + + @Test + public void parse_NotInOperator() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "notin_operator_test.drl" ); + + assertThat(rule).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "consequence();"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + // The first pattern, with 2 restrictions on a single field (plus a + // connective) + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + + ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + + // the second col, with 2 fields, the first with 2 restrictions, the + // second field with one + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); + + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type not in ( \"sedan\", \"wagon\" )"); + + // now the second field + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 1 ); + assertThat(fld.getExpression()).isEqualTo("age < 3"); + + } + + @Test + public void parse_CheckOrDescr() throws Exception { + final String text = "rule X when Person( eval( age == 25 ) || ( eval( name.equals( \"bob\" ) ) && eval( age == 30 ) ) ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + assertThat(AndDescr.class).isEqualTo(pattern.getConstraint().getClass()); + + assertThat(pattern.getConstraint().getDescrs().get(0).getClass()).isEqualTo(ExprConstraintDescr.class); + + } + + @Test + public void parse_ConstraintAndConnective() throws Exception { + final String text = "rule X when Person( age < 42 && location==\"atlanta\") then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 && location==\"atlanta\""); + } + + @Test + public void parse_ConstraintOrConnective() throws Exception { + final String text = "rule X when Person( age < 42 || location==\"atlanta\") then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 || location==\"atlanta\""); + } + + @Test + public void parse_Restrictions() throws Exception { + final String text = "rule X when Foo( bar > 1 || == 1 ) then end\n"; + + AndDescr descrs = (AndDescr) parseAndGetFirstRuleDescr( + text ).getLhs(); + + assertThat(descrs.getDescrs().size()).isEqualTo(1); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 0 ); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); + + assertThat(fieldConstr.getExpression()).isEqualTo("bar > 1 || == 1"); + } + + @Disabled("Priority : High | Implement semicolon delimiter") + @Test + public void parse_Semicolon() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "semicolon.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); + assertThat(pkg.getGlobals().size()).isEqualTo(1); + assertThat(pkg.getRules().size()).isEqualTo(3); + + final RuleDescr rule1 = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule1.getLhs().getDescrs().size()).isEqualTo(2); + + final RuleDescr query1 = (RuleDescr) pkg.getRules().get( 1 ); + assertThat(query1.getLhs().getDescrs().size()).isEqualTo(3); + + final RuleDescr rule2 = (RuleDescr) pkg.getRules().get( 2 ); + assertThat(rule2.getLhs().getDescrs().size()).isEqualTo(2); + } + + @Test + public void parse_Eval() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "eval_parsing.drl" ); + + assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); + assertThat(pkg.getRules().size()).isEqualTo(1); + + final RuleDescr rule1 = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule1.getLhs().getDescrs().size()).isEqualTo(1); + } + + @Disabled("Priority : High | Implement accumulate") + @Test + public void parse_AccumulateReverse() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateReverse.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;" + ); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;" + ); + assertThat(accum.getReverseCode()).isEqualToIgnoringWhitespace( "x--;" + ); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)" + ); + assertThat(accum.isExternalFunction()).isFalse(); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Disabled("Priority : High | Implement accumulate") + @Test + public void parse_AccumulateExternalFunction() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateExternalFunction.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.getFunctions().get( 0 ).getParams()[0]).isEqualToIgnoringWhitespace( "$age" + ); + assertThat(accum.getFunctions().get( 0 ).getFunction()).isEqualToIgnoringWhitespace( "average" + ); + assertThat(accum.isExternalFunction()).isTrue(); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Disabled("Priority : High | Implement from collect") + @Test + public void parse_CollectWithNestedFrom() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "collect_with_nested_from.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final CollectDescr collect = (CollectDescr) out.getSource(); + + PatternDescr person = (PatternDescr) collect.getInputPattern(); + assertThat(person.getObjectType()).isEqualTo("Person"); + + final CollectDescr collect2 = (CollectDescr) person.getSource(); + + final PatternDescr people = collect2.getInputPattern(); + assertThat(people.getObjectType()).isEqualTo("People"); + } + + @Disabled("Priority : High | Implement accumulate") + @Test + public void parse_AccumulateWithNestedFrom() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate_with_nested_from.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accumulate = (AccumulateDescr) out.getSource(); + + PatternDescr person = (PatternDescr) accumulate.getInputPattern(); + assertThat(person.getObjectType()).isEqualTo("Person"); + + final CollectDescr collect2 = (CollectDescr) person.getSource(); + + final PatternDescr people = collect2.getInputPattern(); + assertThat(people.getObjectType()).isEqualTo("People"); + } + + @Disabled("Priority : High | Implement accumulate") + @Test + public void parse_AccumulateMultipleFunctions() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateMultipleFunctions.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(3); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$a1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(1).getFunction()).isEqualTo("min"); + assertThat(functions.get(1).getBind()).isEqualTo("$m1"); + assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(2).getFunction()).isEqualTo("max"); + assertThat(functions.get(2).getBind()).isEqualTo("$M1"); + assertThat(functions.get(2).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Disabled("Priority : High | Implement accumulate") + @Test + public void parse_AccumulateMnemonic() throws Exception { + String drl = "package org.drools.mvel.compiler\n" + + "rule \"Accumulate 1\"\n" + + "when\n" + + " acc( Cheese( $price : price ),\n" + + " $a1 : average( $price ) )\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parser.parse( + drl ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(1); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$a1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Disabled("Priority : High | Implement accumulate") + @Test + public void parse_AccumulateMnemonic2() throws Exception { + String drl = "package org.drools.mvel.compiler\n" + + "rule \"Accumulate 1\"\n" + + "when\n" + + " Number() from acc( Cheese( $price : price ),\n" + + " average( $price ) )\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parser.parse( + drl ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Number"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(1); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Disabled("Priority : High | Implement import accumulate") + @Test + public void parse_ImportAccumulate() throws Exception { + String drl = "package org.drools.mvel.compiler\n" + + "import acc foo.Bar baz\n" + + "import accumulate foo.Bar2 baz2\n" + + "rule \"Accumulate 1\"\n" + + "when\n" + + " acc( Cheese( $price : price ),\n" + + " $v1 : baz( $price ), \n" + + " $v2 : baz2( $price ) )\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parser.parse( + drl ); + + assertThat(pkg.getAccumulateImports().size()).isEqualTo(2); + AccumulateImportDescr imp = (AccumulateImportDescr) pkg.getAccumulateImports().get(0); + assertThat(imp.getTarget()).isEqualTo("foo.Bar"); + assertThat(imp.getFunctionName()).isEqualTo("baz"); + + imp = (AccumulateImportDescr) pkg.getAccumulateImports().get(1); + assertThat(imp.getTarget()).isEqualTo("foo.Bar2"); + assertThat(imp.getFunctionName()).isEqualTo("baz2"); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(2); + assertThat(functions.get(0).getFunction()).isEqualTo("baz"); + assertThat(functions.get(0).getBind()).isEqualTo("$v1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(1).getFunction()).isEqualTo("baz2"); + assertThat(functions.get(1).getBind()).isEqualTo("$v2"); + assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Disabled("Priority : High | Implement accumulate") + @Test + public void parse_AccumulateMultipleFunctionsConstraint() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateMultipleFunctionsConstraint.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Object"); + assertThat(out.getConstraint().getDescrs().size()).isEqualTo(2); + assertThat(out.getConstraint().getDescrs().get(0).toString()).isEqualTo("$a1 > 10 && $M1 <= 100"); + assertThat(out.getConstraint().getDescrs().get(1).toString()).isEqualTo("$m1 == 5"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(3); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$a1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(1).getFunction()).isEqualTo("min"); + assertThat(functions.get(1).getBind()).isEqualTo("$m1"); + assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(2).getFunction()).isEqualTo("max"); + assertThat(functions.get(2).getBind()).isEqualTo("$M1"); + assertThat(functions.get(2).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + public void parse_OrCE() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_ce.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + final PatternDescr person = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(person.getObjectType()).isEqualTo("Person"); + assertThat(person.getIdentifier()).isEqualTo("$p"); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + + final PatternDescr cheese1 = (PatternDescr) or.getDescrs().get( 0 ); + assertThat(cheese1.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese1.getIdentifier()).isEqualTo("$c"); + final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get( 1 ); + assertThat(cheese2.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese2.getIdentifier()).isNull(); + } + + @Test + public void parse_RuleSingleLine() throws Exception { + final String text = "rule \"another test\" salience 10 when eval( true ) then System.out.println(1); end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text ); + + assertThat(rule.getName()).isEqualTo("another test"); + assertThat((String)rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1); "); + } + + @Test + public void parse_RuleTwoLines() throws Exception { + final String text = "rule \"another test\" salience 10 when eval( true ) then System.out.println(1);\n end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text ); + + assertThat(rule.getName()).isEqualTo("another test"); + assertThat((String)rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1);\n "); + } + + @Test + public void parse_RuleParseLhs3() throws Exception { + final String text = "rule X when (or\nnot Person()\n(and Cheese()\nMeat()\nWine())) then end"; + AndDescr pattern = parseAndGetFirstRuleDescr( + text ).getLhs(); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + OrDescr or = (OrDescr) pattern.getDescrs().get( 0 ); + assertThat(or.getDescrs().size()).isEqualTo(2); + NotDescr not = (NotDescr) or.getDescrs().get( 0 ); + AndDescr and = (AndDescr) or.getDescrs().get( 1 ); + assertThat(not.getDescrs().size()).isEqualTo(1); + PatternDescr person = (PatternDescr) not.getDescrs().get( 0 ); + assertThat(person.getObjectType()).isEqualTo("Person"); + assertThat(and.getDescrs().size()).isEqualTo(3); + PatternDescr cheese = (PatternDescr) and.getDescrs().get( 0 ); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + PatternDescr meat = (PatternDescr) and.getDescrs().get( 1 ); + assertThat(meat.getObjectType()).isEqualTo("Meat"); + PatternDescr wine = (PatternDescr) and.getDescrs().get( 2 ); + assertThat(wine.getObjectType()).isEqualTo("Wine"); + + } + + @Disabled("Priority : High | Implement accumulate") + @Test + public void parse_AccumulateMultiPattern() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate_multi_pattern.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace( "$counter" + ); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;" + ); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;" + ); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)" + ); + + final AndDescr and = (AndDescr) accum.getInput(); + assertThat(and.getDescrs().size()).isEqualTo(2); + final PatternDescr person = (PatternDescr) and.getDescrs().get( 0 ); + final PatternDescr cheese = (PatternDescr) and.getDescrs().get( 1 ); + assertThat(person.getObjectType()).isEqualTo("Person"); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + } + + @Disabled("Priority : High | Implement temporal operators") + @Test + public void parse_PluggableOperators() throws Exception { + + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "pluggable_operators.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(5); + + final PatternDescr eventA = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(eventA.getIdentifier()).isEqualTo("$a"); + assertThat(eventA.getObjectType()).isEqualTo("EventA"); + + final PatternDescr eventB = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(eventB.getIdentifier()).isEqualTo("$b"); + assertThat(eventB.getObjectType()).isEqualTo("EventB"); + assertThat(eventB.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(eventB.getConstraint().getDescrs().size()).isEqualTo(1); + + final ExprConstraintDescr fcdB = (ExprConstraintDescr) eventB.getConstraint().getDescrs().get( 0 ); + assertThat(fcdB.getExpression()).isEqualTo("this after[1,10] $a || this not after[15,20] $a"); + + final PatternDescr eventC = (PatternDescr) rule.getLhs().getDescrs().get( 2 ); + assertThat(eventC.getIdentifier()).isEqualTo("$c"); + assertThat(eventC.getObjectType()).isEqualTo("EventC"); + assertThat(eventC.getConstraint().getDescrs().size()).isEqualTo(1); + final ExprConstraintDescr fcdC = (ExprConstraintDescr) eventC.getConstraint().getDescrs().get( 0 ); + assertThat(fcdC.getExpression()).isEqualTo("this finishes $b"); + + final PatternDescr eventD = (PatternDescr) rule.getLhs().getDescrs().get( 3 ); + assertThat(eventD.getIdentifier()).isEqualTo("$d"); + assertThat(eventD.getObjectType()).isEqualTo("EventD"); + assertThat(eventD.getConstraint().getDescrs().size()).isEqualTo(1); + final ExprConstraintDescr fcdD = (ExprConstraintDescr) eventD.getConstraint().getDescrs().get( 0 ); + assertThat(fcdD.getExpression()).isEqualTo("this not starts $a"); + + final PatternDescr eventE = (PatternDescr) rule.getLhs().getDescrs().get( 4 ); + assertThat(eventE.getIdentifier()).isEqualTo("$e"); + assertThat(eventE.getObjectType()).isEqualTo("EventE"); + assertThat(eventE.getConstraint().getDescrs().size()).isEqualTo(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"); + } + + @Test + public void parse_RuleMetadata() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "Rule_with_Metadata.drl" ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + // @fooAttribute(barValue) + // @fooAtt2(barVal2) + RuleDescr rule = pkg.getRules().get( 0 ); + assertThat(rule.getAnnotationNames().contains("fooMeta1")).isTrue(); + assertThat(rule.getAnnotation("fooMeta1").getValue()).isEqualTo("barVal1"); + assertThat(rule.getAnnotationNames().contains("fooMeta2")).isTrue(); + assertThat(rule.getAnnotation("fooMeta2").getValue()).isEqualTo("barVal2"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"Consequence\");" + ); + } + + @Disabled("Priority : High | Implement extends") + @Test + public void parse_RuleExtends() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "Rule_with_Extends.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get( 0 ); + assertThat(rule.getParentName() != null).isTrue(); + assertThat(rule.getParentName()).isEqualTo("rule1"); + + AndDescr lhs = rule.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs().size()).isEqualTo(1); + + PatternDescr pattern = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("foo"); + assertThat(pattern.getIdentifier()).isEqualTo("$foo"); + + } + + @Disabled("Priority : High | Implement type declaration") + @Test + public void parse_TypeDeclarationWithFields() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "declare_type_with_fields.drl" ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + List td = pkg.getTypeDeclarations(); + assertThat(td.size()).isEqualTo(3); + + TypeDeclarationDescr d = td.get( 0 ); + assertThat(d.getTypeName()).isEqualTo("SomeFact"); + assertThat(d.getFields().size()).isEqualTo(2); + assertThat(d.getFields().containsKey("name")).isTrue(); + assertThat(d.getFields().containsKey("age")).isTrue(); + + TypeFieldDescr f = d.getFields().get("name" ); + assertThat(f.getPattern().getObjectType()).isEqualTo("String"); + + f = d.getFields().get( "age" ); + assertThat(f.getPattern().getObjectType()).isEqualTo("Integer"); + + d = td.get( 1 ); + assertThat(d.getTypeName()).isEqualTo("AnotherFact"); + + TypeDeclarationDescr type = td.get( 2 ); + assertThat(type.getTypeName()).isEqualTo("Person"); + + assertThat(type.getAnnotation("role").getValue()).isEqualTo("fact"); + assertThat(type.getAnnotation("doc").getValue("descr")).isEqualTo("\"Models a person\""); + assertThat(type.getAnnotation("doc").getValue("author")).isEqualTo("\"Bob\""); + assertThat(type.getAnnotation("doc").getValue("date")).isEqualTo("Calendar.getInstance().getDate()"); + + assertThat(type.getFields().size()).isEqualTo(2); + TypeFieldDescr field = type.getFields().get( "name" ); + assertThat(field.getFieldName()).isEqualTo("name"); + assertThat(field.getPattern().getObjectType()).isEqualTo("String"); + assertThat(field.getInitExpr()).isEqualTo("\"John Doe\""); + assertThat(field.getAnnotation("length").getValue("max")).isEqualTo("50"); + assertThat( field.getAnnotation( "key" ) ).isNotNull(); + + field = type.getFields().get( "age" ); + assertThat(field.getFieldName()).isEqualTo("age"); + assertThat(field.getPattern().getObjectType()).isEqualTo("int"); + assertThat(field.getInitExpr()).isEqualTo("-1"); + assertThat(field.getAnnotation("ranged").getValue("min")).isEqualTo("0"); + assertThat(field.getAnnotation("ranged").getValue("max")).isEqualTo("150"); + assertThat(field.getAnnotation("ranged").getValue("unknown")).isEqualTo("-1"); + + } + + @Disabled("Priority : High | Failed to parse or with parentheses in LHS") + @Test + public void parse_RuleWithLHSNesting() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "Rule_with_nested_LHS.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get( 0 ); + assertThat(rule.getName()).isEqualTo("test"); + + AndDescr lhs = rule.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs().size()).isEqualTo(2); + + PatternDescr a = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(a.getObjectType()).isEqualTo("A"); + + OrDescr or = (OrDescr) lhs.getDescrs().get( 1 ); + assertThat(or.getDescrs().size()).isEqualTo(3); + + AndDescr and1 = (AndDescr) or.getDescrs().get( 0 ); + assertThat(and1.getDescrs().size()).isEqualTo(2); + PatternDescr b = (PatternDescr) and1.getDescrs().get( 0 ); + PatternDescr c = (PatternDescr) and1.getDescrs().get( 1 ); + assertThat(b.getObjectType()).isEqualTo("B"); + assertThat(c.getObjectType()).isEqualTo("C"); + + AndDescr and2 = (AndDescr) or.getDescrs().get( 1 ); + assertThat(and2.getDescrs().size()).isEqualTo(2); + PatternDescr d = (PatternDescr) and2.getDescrs().get( 0 ); + PatternDescr e = (PatternDescr) and2.getDescrs().get( 1 ); + assertThat(d.getObjectType()).isEqualTo("D"); + assertThat(e.getObjectType()).isEqualTo("E"); + + AndDescr and3 = (AndDescr) or.getDescrs().get( 2 ); + assertThat(and3.getDescrs().size()).isEqualTo(2); + PatternDescr f = (PatternDescr) and3.getDescrs().get( 0 ); + PatternDescr g = (PatternDescr) and3.getDescrs().get( 1 ); + assertThat(f.getObjectType()).isEqualTo("F"); + assertThat(g.getObjectType()).isEqualTo("G"); + } + + @Disabled("Priority : High | Implement from entry-point") + @Test + public void parse_EntryPoint() throws Exception { + final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point StreamA then end"; + + PackageDescr pkg = parser.parse( + text ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); + + assertThat(pattern.getSource()).isNotNull(); + EntryPointDescr entry = (EntryPointDescr) pattern.getSource(); + assertThat(entry.getEntryId()).isEqualTo("StreamA"); + } + + @Disabled("Priority : High | Implement from entry-point") + @Test + public void parse_EntryPoint2() throws Exception { + final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point \"StreamA\" then end"; + + PackageDescr pkg = parser.parse( + text ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); + + assertThat(pattern.getSource()).isNotNull(); + EntryPointDescr entry = (EntryPointDescr) pattern.getSource(); + assertThat(entry.getEntryId()).isEqualTo("StreamA"); + } + + @Disabled("Priority : High | Implement sliding window") + @Test + public void parse_SlidingWindow() throws Exception { + final String text = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end"; + + PackageDescr pkg = parser.parse( + text ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + RuleDescr rule = pkg.getRules().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); + + List behaviors = pattern.getBehaviors(); + assertThat(behaviors).isNotNull(); + assertThat(behaviors.size()).isEqualTo(1); + BehaviorDescr descr = behaviors.get( 0 ); + assertThat(descr.getType()).isEqualTo("window"); + assertThat(descr.getSubType()).isEqualTo("length"); + assertThat(descr.getParameters().get(0)).isEqualTo("10"); + } + + @Disabled("Priority : Mid | outmost parentheses") + @Test + public void parse_RuleOldSyntax1() throws Exception { + final String source = "rule \"Test\" when ( not $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; + + PackageDescr pkg = parser.parse( + source ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + assertThat(rule.getName()).isEqualTo("Test"); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(((NotDescr) rule.getLhs().getDescrs().get(0)).getDescrs().size()).isEqualTo(1); + NotDescr notDescr = (NotDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr patternDescr = (PatternDescr) notDescr.getDescrs().get( 0 ); + assertThat(patternDescr.getIdentifier()).isEqualTo("$r"); + assertThat(patternDescr.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get( 0 ); + assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); + } + + @Disabled("Priority : Mid | outmost parentheses") + @Test + public void parse_RuleOldSyntax2() throws Exception { + final String source = "rule \"Test\" when ( $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; + + PackageDescr pkg = parser.parse( + source ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + + assertThat(rule.getName()).isEqualTo("Test"); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + PatternDescr patternDescr = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(patternDescr.getIdentifier()).isEqualTo("$r"); + assertThat(patternDescr.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get( 0 ); + assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); + } + + @Disabled("Priority : High | Implement type declaration") + @Test + public void parse_TypeWithMetaData() throws Exception { + + PackageDescr pkg = parseAndGetPackageDescrFromFile( + "type_with_meta.drl" ); + + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + final List declarations = pkg.getTypeDeclarations(); + + assertThat(declarations.size()).isEqualTo(3); + } + + @Disabled("Priority : Mid | Implement Descr position") + @Test + public void parse_NullConstraints() throws Exception { + final String text = "rule X when Person( name == null ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("name == null"); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); + } + + @Disabled("Priority : High | Implement positional constraint") + @Test + public void parse_PositionalConstraintsOnly() throws Exception { + final String text = "rule X when Person( \"Mark\", 42; ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(2); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + assertThat(fcd.getExpression()).isEqualTo("42"); + assertThat(fcd.getPosition()).isEqualTo(1); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + } + + @Disabled("Priority : High | Implement query") + @Test + public void parse_IsQuery() throws Exception { + final String text = "rule X when ?person( \"Mark\", 42; ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.isQuery()).isTrue(); + + assertThat(pattern.getDescrs().size()).isEqualTo(2); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + assertThat(fcd.getExpression()).isEqualTo("42"); + assertThat(fcd.getPosition()).isEqualTo(1); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + } + + @Disabled("Priority : Mid | Implement query with from") + @Test + public void parse_FromFollowedByQuery() throws Exception { + // the 'from' expression requires a ";" to disambiguate the "?" + // prefix for queries from the ternary operator "? :" + final String text = "rule X when Cheese() from $cheesery ?person( \"Mark\", 42; ) then end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + assertThat(pattern.getSource().getText()).isEqualTo("from $cheesery"); + assertThat(pattern.isQuery()).isFalse(); + + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("person"); + assertThat(pattern.isQuery()).isTrue(); + + } + + @Disabled("Priority : Mid | Implement query with from") + @Test + public void parse_FromWithTernaryFollowedByQuery() throws Exception { + // the 'from' expression requires a ";" to disambiguate the "?" + // prefix for queries from the ternary operator "? :" + final String text = "rule X when Cheese() from (isFull ? $cheesery : $market) ?person( \"Mark\", 42; ) then end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + assertThat(pattern.getSource().getText()).isEqualToIgnoringWhitespace("from (isFull ? $cheesery : $market)"); + assertThat(pattern.isQuery()).isFalse(); + + pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + assertThat(pattern.getObjectType()).isEqualTo("person"); + assertThat(pattern.isQuery()).isTrue(); + + } + + @Disabled("Priority : Low | Implement multi-value annotation. Not written in docs") + @Test + public void parse_MultiValueAnnotationsBackwardCompatibility() throws Exception { + // multiple values with no keys are parsed as a single value + final String text = "rule X @ann1( val1, val2 ) @ann2( \"val1\", \"val2\" ) when then end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text ); + + AnnotationDescr ann = rule.getAnnotation("ann1" ); + assertThat(ann).isNotNull(); + assertThat(ann.getValue()).isEqualTo("val1, val2"); + + ann = rule.getAnnotation( "ann2" ); + assertThat(ann).isNotNull(); + assertThat(ann.getValue()).isEqualTo("\"val1\", \"val2\""); + } + + @Disabled("Priority : High | Implement positional constraint") + @Test + public void parse_PositionalsAndNamedConstraints() throws Exception { + final String text = "rule X when Person( \"Mark\", 42; location == \"atlanta\" ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(3); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + assertThat(fcd.getExpression()).isEqualTo("42"); + assertThat(fcd.getPosition()).isEqualTo(1); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + + fcd = (ExprConstraintDescr) pattern.getDescrs().get( 2 ); + assertThat(fcd.getExpression()).isEqualTo("location == \"atlanta\""); + assertThat(fcd.getPosition()).isEqualTo(2); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); + + } + + @Disabled("Priority : High | Implement unification") + @Test + public void parse_UnificationBinding() throws Exception { + final String text = "rule X when $p := Person( $name := name, $loc : location ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getIdentifier()).isEqualTo("$p"); + assertThat(pattern.isUnification()).isTrue(); + + assertThat(pattern.getDescrs().size()).isEqualTo(2); + ExprConstraintDescr bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(bindingDescr.getExpression()).isEqualTo("$name := name"); + + bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + assertThat(bindingDescr.getExpression()).isEqualTo("$loc : location"); + + } + + @Disabled("Priority : High | Implement BigInteger literal, BigDecimal literal") + @Test + public void parse_BigLiterals() throws Exception { + final String text = "rule X when Primitives( bigInteger == (10I), " + + " bigDecimal == (10B), " + + " bigInteger < 50I, " + + " bigDecimal < 50B ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getDescrs().size()).isEqualTo(4); + ExprConstraintDescr ecd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(ecd.getExpression()).isEqualTo("bigInteger == (10I)"); + + ecd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + assertThat(ecd.getExpression()).isEqualTo("bigDecimal == (10B)"); + + ecd = (ExprConstraintDescr) pattern.getDescrs().get( 2 ); + assertThat(ecd.getExpression()).isEqualTo("bigInteger < 50I"); + + ecd = (ExprConstraintDescr) pattern.getDescrs().get( 3 ); + assertThat(ecd.getExpression()).isEqualTo("bigDecimal < 50B"); + } + + @Disabled("Priority : High | Failed to parse binding with ||") + @Test + public void parse_BindingComposite() throws Exception { + final String text = "rule X when Person( $name : name == \"Bob\" || $loc : location == \"Montreal\" ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.isUnification()).isFalse(); + + // embedded bindings are extracted at compile time + List< ? > constraints = pattern.getDescrs(); + assertThat(constraints.size()).isEqualTo(1); + assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name == \"Bob\" || $loc : location == \"Montreal\""); + } + + @Disabled("Priority : High | Failed to parse binding with ||") + @Test + public void parse_BindingCompositeWithMethods() throws Exception { + final String text = "rule X when Person( $name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\" ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.isUnification()).isFalse(); + + // embedded bindings are extracted at compile time + List< ? > constraints = pattern.getDescrs(); + assertThat(constraints.size()).isEqualTo(1); + assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\""); + } + + @Disabled("Priority : High | Implement temporal operators") + @Test + public void parse_PluggableOperators2() throws Exception { + final String text = "rule \"tt\"\n" + + " dialect \"mvel\"\n" + + "when\n" + + " exists (TelephoneCall( this finishes [1m] \"25-May-2011\" ))\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) ((ExistsDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 )).getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("TelephoneCall"); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(constr.getText()).isEqualTo("this finishes [1m] \"25-May-2011\""); + + } + + @Test + public void parse_InlineEval() throws Exception { + final String text = "rule \"inline eval\"\n" + + "when\n" + + " Person( eval( name.startsWith(\"b\") && name.finishesWith(\"b\")) )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("Person"); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(constr.getText()).isEqualToIgnoringWhitespace("eval( name.startsWith(\"b\") && name.finishesWith(\"b\"))"); + + } + + @Disabled("Priority : High | Implement temporal operators") + @Test + public void parse_InfinityLiteral() throws Exception { + final String text = "rule \"infinity\"\n" + + "when\n" + + " StockTick( this after[-*,*] $another )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text ).getLhs().getDescrs().get( 0 ); + + assertThat(pattern.getObjectType()).isEqualTo("StockTick"); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + assertThat(constr.getText()).isEqualTo("this after[-*,*] $another"); + + } + + @Disabled("Priority : High | Implement entry-point declaration") + @Test + public void parse_EntryPointDeclaration() throws Exception { + final String text = "package org.drools\n" + + "declare entry-point eventStream\n" + + " @source(\"jndi://queues/events\")\n" + + " @foo( true )\n" + + "end"; + PackageDescr pkg = parser.parse( + text ); + + assertThat(pkg.getName()).isEqualTo("org.drools"); + assertThat(pkg.getEntryPointDeclarations().size()).isEqualTo(1); + + EntryPointDeclarationDescr epd = pkg.getEntryPointDeclarations().iterator().next(); + + assertThat(epd.getEntryPointId()).isEqualTo("eventStream"); + assertThat(epd.getAnnotations().size()).isEqualTo(2); + assertThat(epd.getAnnotation("source").getValue()).isEqualTo("\"jndi://queues/events\""); + assertThat(epd.getAnnotation("foo").getValue()).isEqualTo("true"); + } + + @Disabled("Priority : Mid | Implement sliding window declaration") + @Test + public void parse_WindowDeclaration() throws Exception { + final String text = "package org.drools\n" + + "declare window Ticks\n" + + " @doc(\"last 10 stock ticks\")\n" + + " $s : StockTick( source == \"NYSE\" )\n" + + " over window:length( 10, $s.symbol )\n" + + " from entry-point stStream\n" + + "end"; + PackageDescr pkg = parser.parse( + text ); + + assertThat(pkg.getName()).isEqualTo("org.drools"); + assertThat(pkg.getWindowDeclarations().size()).isEqualTo(1); + + WindowDeclarationDescr wdd = pkg.getWindowDeclarations().iterator().next(); + + assertThat(wdd.getName()).isEqualTo("Ticks"); + assertThat(wdd.getAnnotations().size()).isEqualTo(1); + assertThat(wdd.getAnnotation("doc").getValue()).isEqualTo("\"last 10 stock ticks\""); + + PatternDescr pd = wdd.getPattern(); + assertThat(pd).isNotNull(); + assertThat(pd.getIdentifier()).isEqualTo("$s"); + assertThat(pd.getObjectType()).isEqualTo("StockTick"); + assertThat(pd.getSource().getText()).isEqualTo("stStream"); + + assertThat(pd.getBehaviors().size()).isEqualTo(1); + BehaviorDescr bd = pd.getBehaviors().get( 0 ); + assertThat(bd.getType()).isEqualTo("window"); + assertThat(bd.getSubType()).isEqualTo("length"); + assertThat(bd.getParameters().size()).isEqualTo(2); + assertThat(bd.getParameters().get(0)).isEqualTo("10"); + assertThat(bd.getParameters().get(1)).isEqualTo("$s.symbol"); + } + + @Disabled("Priority : Mid | Implement using declared window. Not written in docs, but unit tests found.") + @Test + public void parse_WindowUsage() throws Exception { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " StockTick() from window Y\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parser.parse( + text ); + + assertThat(pkg.getName()).isEqualTo("org.drools"); + assertThat(pkg.getRules().size()).isEqualTo(1); + + RuleDescr rd = pkg.getRules().get(0); + + assertThat(rd.getName()).isEqualTo("X"); + assertThat(rd.getLhs().getDescrs().size()).isEqualTo(1); + + PatternDescr pd = (PatternDescr) rd.getLhs().getDescrs().get(0); + assertThat(pd).isNotNull(); + assertThat(pd.getObjectType()).isEqualTo("StockTick"); + assertThat(pd.getSource().getText()).isEqualTo("Y"); + } + } diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Extends.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Extends.drl new file mode 100644 index 00000000000..f80499fb3aa --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Extends.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler + +rule test_rule extends rule1 + when + $foo : foo() + then + +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Metadata.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Metadata.drl new file mode 100644 index 00000000000..9af877c9df0 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Metadata.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +package org.drools.compiler + +rule test_rule + @fooMeta1(barVal1) + @fooMeta2(barVal2) + when + then + System.out.println("Consequence"); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_nested_LHS.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_nested_LHS.drl new file mode 100644 index 00000000000..02202de44e1 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_nested_LHS.drl @@ -0,0 +1,26 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler + +rule test + when + A() + ( B() and C() ) or + ( D() and E() ) or + ( F() and G() ) + then + +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate.drl new file mode 100755 index 00000000000..be01b70b8a6 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "AccumulateParserTest" +when + Integer() from accumulate( Person( age > 21 ), + init( int x = 0; ), + action( x++; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateExternalFunction.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateExternalFunction.drl new file mode 100755 index 00000000000..e6d7e40d5f3 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateExternalFunction.drl @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "AccumulateReverseParserTest" +when + Number() from accumulate( Person( $age : age > 21 ), + average( $age ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctions.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctions.drl new file mode 100755 index 00000000000..7a9d52d3e61 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctions.drl @@ -0,0 +1,28 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler + +rule "Accumulate 1" +when + accumulate( Cheese( $price : price ), + $a1 : average( $price ), + $m1 : min( $price ), + $M1 : max( $price ) // binds are optional, but it makes no sense to not have a binding in this case + ) +then + // do something +end + diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctionsConstraint.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctionsConstraint.drl new file mode 100755 index 00000000000..1c828960220 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctionsConstraint.drl @@ -0,0 +1,30 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler + +rule "Accumulate 1" +when + accumulate( Cheese( $price : price ); + $a1 : average( $price ), + $m1 : min( $price ), + $M1 : max( $price ); // binds are optional, but it makes no sense to not have a binding in this case + $a1 > 10 && $M1 <= 100, + $m1 == 5 // inline evals + ) +then + // do something +end + diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateReverse.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateReverse.drl new file mode 100755 index 00000000000..c81cca42267 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateReverse.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "AccumulateReverseParserTest" +when + Integer() from accumulate( Person( age > 21 ), + init( int x = 0; ), + action( x++; ), + reverse( x--; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_multi_pattern.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_multi_pattern.drl new file mode 100755 index 00000000000..f0efaae91b7 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_multi_pattern.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "AccumulateMultiPatternParserTest" +when + $counter:Integer() from accumulate( $person : Person( age > 21 ) and Cheese( type == $person.likes ), + init( int x = 0; ), + action( x++; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_bindings.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_bindings.drl new file mode 100755 index 00000000000..5623f98cd2d --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_bindings.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "AccumulateParserTest" +when + $counter:Integer() from accumulate( $person : Person( age > 21 ), + init( int x = 0; ), + action( x++; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_nested_from.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_nested_from.drl new file mode 100755 index 00000000000..aa3487820bc --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_nested_from.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +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() ), + max( $age ) ); +then +end + diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/and_or_rule.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/and_or_rule.drl new file mode 100644 index 00000000000..3cc58efd0e2 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/and_or_rule.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +import org.drools.compiler.Person + +rule simple_rule + when + Person(name == "mark") and Cheese(type == "stilton") + Person(name == "mark") or Cheese(type == "stilton") + then + System.out.println( "Mark and Michael" ); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/basic_binding.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/basic_binding.drl new file mode 100644 index 00000000000..d6cdfb3ee3f --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/basic_binding.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +rule "like cheddar" + when + Cheese( $type:type ) + then + System.out.println("I like " + $type); +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/bindings.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/bindings.drl new file mode 100644 index 00000000000..c80fd4da819 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/bindings.drl @@ -0,0 +1,27 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; +import org.drools.compiler.Person; + +rule "Who likes Stilton" + when + Cheese($type : type == "stilton") + $person : Person( $name : name == "bob", likes == $type) + then + System.out.println( $name + " likes " + $type); +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/brackets_precedence.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/brackets_precedence.drl new file mode 100644 index 00000000000..d4e5f449bd4 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/brackets_precedence.drl @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + when + ( (not Foo(x=="a") or Foo(x=="y") ) and ( Shoes() or Butt() ) ) + then +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect.drl new file mode 100755 index 00000000000..0305d1e85da --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect.drl @@ -0,0 +1,20 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "CollectParserTest" +when + $personList : ArrayList() from collect( Person( age > 21 ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect_with_nested_from.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect_with_nested_from.drl new file mode 100755 index 00000000000..3b57fd222f5 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect_with_nested_from.drl @@ -0,0 +1,22 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "CollectParserTest" +when + // below statement makes no sense, but is useful to test parsing recursiveness + $personList : ArrayList() from collect( $p : Person( age > 21 || age < 10 ) from collect( People() from $town.getPeople() ) ); +then +end + diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/comment.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/comment.drl new file mode 100644 index 00000000000..a786bfb9607 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/comment.drl @@ -0,0 +1,30 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +//this starts with a comment +package foo.bar + +//and another comment + +/* +yet + another + style +*/ + +rule "test" + when + then +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/complex.dsl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/complex.dsl new file mode 100644 index 00000000000..b2cf4cb9c84 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/complex.dsl @@ -0,0 +1,5 @@ +#place your comments here - this is just a description for your own purposes. +[when]There is a Person with name of {name}=Person(name=="{name}") +[when]Person is at least {age} years old and lives in {location}=Person(age > {age}, location == "{location}") +[then]Log "{message}"=System.out.println("{message}"); +[when]Or=or diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declare_type_with_fields.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declare_type_with_fields.drl new file mode 100644 index 00000000000..ead6a91080e --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declare_type_with_fields.drl @@ -0,0 +1,33 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +declare SomeFact + name : String + age: Integer +end + +declare AnotherFact + +end + +declare Person + @role( fact ) + @doc( descr="Models a person", + author="Bob", + date=Calendar.getInstance().getDate() ) + + name : String = "John Doe" @key @length( max = 50 ) + age : int = -1 @ranged( min = 0, max = 150, unknown = -1 ) +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/enumeration.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/enumeration.drl new file mode 100644 index 00000000000..c60f47f139e --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/enumeration.drl @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + when + Foo(bar == Foo.BAR) + then +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/escaped-string.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/escaped-string.drl new file mode 100755 index 00000000000..e9ccb4759a3 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/escaped-string.drl @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "test_Quotes" + when + InitialFact() + then + String s = "\"\n\t\\"; +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_multiple.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_multiple.drl new file mode 100644 index 00000000000..f1eb801e325 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_multiple.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + when + eval(abc("foo") + 5) + Foo() + eval(qed()) + Bar() + then +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_parsing.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_parsing.drl new file mode 100644 index 00000000000..bf545890f57 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_parsing.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.mvel.compiler + +rule "Test Parse" + +when + eval( 3==3 ) +then + System.out.println("OK"); +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_with_newline.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_with_newline.drl new file mode 100644 index 00000000000..93648e357da --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_with_newline.drl @@ -0,0 +1,36 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + when + Foo() + Bar() + eval( + + + + abc( + + "foo") + + 5 + + + + + ) + then + +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints.dslr b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints.dslr new file mode 100644 index 00000000000..cfb3bdf78b9 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints.dslr @@ -0,0 +1,18 @@ +//created on: 13/04/2006 +package mydsl + + +expander multiple_constraints.dsl + + +rule "Your First Rule" + + when + There is a Person with + - age less than 42 + -location is 'atlanta' + Bar bar black sheep + then + Log "hola bob" + +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints_flush.dslr b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints_flush.dslr new file mode 100644 index 00000000000..f352d9196fa --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints_flush.dslr @@ -0,0 +1,17 @@ +//created on: 13/04/2006 +package mydsl + + +expander multiple_constraints.dsl + + +rule "Your First Rule" + + when + There is a Person with + -age less than 42 + -location is 'atlanta' + then + Log "hola bob" + +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_spread_lines.dslr b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_spread_lines.dslr new file mode 100644 index 00000000000..02ae6b5bcca --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_spread_lines.dslr @@ -0,0 +1,19 @@ +//created on: 13/04/2006 +package mydsl + + +expander complex.dsl + + +rule "Your First Rule" + + when + Person is at least 42 years old and lives in atlanta + + Or + + There is a Person with name of bob + then + Log "hola bob" + +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/extra_lhs_newline.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/extra_lhs_newline.drl new file mode 100644 index 00000000000..1434c800cec --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/extra_lhs_newline.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule "another test" + when + s : String() + eval(s.equals("foo") && s.startsWith("f")) + + + then + list.add( s ); +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forall.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forall.drl new file mode 100755 index 00000000000..9fe9d276517 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forall.drl @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "ForallParserTest" +when + forall( Person( age > 21, $likes : likes ) + Cheese( type == $likes ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forallwithfrom.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forallwithfrom.drl new file mode 100644 index 00000000000..578329f1437 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forallwithfrom.drl @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "ForallParserTest" +when + forall( Person( age > 21, $likes : likes ) from $village + Cheese( type == $likes ) from $cheesery ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/functions.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/functions.drl new file mode 100644 index 00000000000..82df0791678 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/functions.drl @@ -0,0 +1,41 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +import java.lang.String + +function String functionA(String s, Integer i) { + + foo(); + +} + +function void functionB() { + bar(); +} + + +rule something + when + then +end + +rule "one more thing" + when + then +end + + + diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/in_operator_test.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/in_operator_test.drl new file mode 100644 index 00000000000..7a84ed571b2 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/in_operator_test.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +//testing 'in' operator + +rule simple_rule + when + Person(age > 30 && < 40) + Vehicle(type in ( "sedan", "wagon" ), age < 3) + then + consequence(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/lhs_semicolon_delim.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/lhs_semicolon_delim.drl new file mode 100644 index 00000000000..88c0961377f --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/lhs_semicolon_delim.drl @@ -0,0 +1,27 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + when + foo3 : Bar(a==3) ; foo4 : Bar(a4:a==4) ; Baz() + then + if ( a == b ) { + assert( foo3 ); + } else { + retract( foo4 ); + } + System.out.println( a4 ); +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_constraints.dsl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_constraints.dsl new file mode 100644 index 00000000000..92a142ec007 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_constraints.dsl @@ -0,0 +1,6 @@ +#place your comments here - this is just a description for your own purposes. +[when]There is a Person with=Person() +[when]- age less than {age}=age < {age} +[when]- location is '{city}'=location=={city} +[when]Bar bar black sheep=Bar() +[then]Log "{message}"=System.out.println("{message}"); diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_rules.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_rules.drl new file mode 100644 index 00000000000..cdfa359765f --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_rules.drl @@ -0,0 +1,32 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler.test; + +import org.drools.integrationtests.Cheese; + +rule "Like Stilton" + when + Cheese( t:type == "stilton" ) + then + System.out.println("I like " + t); +end + +rule "Like Cheddar" + when + Cheese( t:type == "cheddar" ) + then + System.out.println("I like " + t ); +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/nested_conditional_elements.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/nested_conditional_elements.drl new file mode 100755 index 00000000000..fc7b1ed00a9 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/nested_conditional_elements.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule "test nested CEs" + when + not ( State( $state : state ) and + not( Person( status == $state, $likes : likes ) and + Cheese( type == $likes ) ) ) + Person( name == "Bob" ) + ( Cheese( price == 10 ) or Cheese( type == "brie" ) ) + then + results.add("OK"); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_exist_with_brackets.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_exist_with_brackets.drl new file mode 100644 index 00000000000..ff8ae8c50ea --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_exist_with_brackets.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package HR1 + +rule simple_rule + when + not ( Cheese(type == "stilton") ) + exists ( Foo() ) + then + funky(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_with_constraint.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_with_constraint.drl new file mode 100644 index 00000000000..0efd3eb6ebb --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_with_constraint.drl @@ -0,0 +1,29 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +global java.util.List list; +global java.lang.Integer five; + +rule "not rule test" + when + $person : Person( $likes:like ) + not Cheese( type == $likes ) + then + list.add( $person ); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/notin_operator_test.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/notin_operator_test.drl new file mode 100644 index 00000000000..3cb202cd7a0 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/notin_operator_test.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +//testing not 'in' operator + +rule simple_rule + when + Person(age > 30 && < 40) + Vehicle(type not in ( "sedan", "wagon" ), age < 3) + then + consequence(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding.drl new file mode 100644 index 00000000000..e8c78d9e687 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +import org.drools.compiler.Person + +rule simple_rule + when + foo : ( Person(name == "mark") or Person(type == "fan") ) + Cheese(type == "green") + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_complex.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_complex.drl new file mode 100644 index 00000000000..01331cc0d5c --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_complex.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + + +rule simple_rule + when + foo : ( Person(name == "mark") + or + Person(type == "fan") ) + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_with_brackets.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_with_brackets.drl new file mode 100644 index 00000000000..02c2a320a55 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_with_brackets.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +rule simple_rule + when + foo : ( + Person(name == "mark") or Person(type == "fan") + ) + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_ce.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_ce.drl new file mode 100644 index 00000000000..fb74e43f789 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_ce.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler + +rule "testing OR CE" +when + $p : Person( name == "bob" ) + $c : Cheese( type == $p.likes ) or Cheese( price == 10 ) +then + // do something +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_nesting.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_nesting.drl new file mode 100644 index 00000000000..3da6c4811cc --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_nesting.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +import org.drools.compiler.Person + +rule simple_rule + when + Person(name == "mark") or + ( Person(type == "fan") and Cheese(type == "green") ) + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/package_attributes.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/package_attributes.drl new file mode 100644 index 00000000000..477ca8aa608 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/package_attributes.drl @@ -0,0 +1,38 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package com.foo; + +agenda-group "x" + +import goo.ber +import wee.waa + + +dialect "java" + + + + +rule bar + when + then +end + +rule baz + dialect "mvel" + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/pluggable_operators.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/pluggable_operators.drl new file mode 100644 index 00000000000..6b287929946 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/pluggable_operators.drl @@ -0,0 +1,26 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler + +rule "test pluggable operators" +when + $a : EventA() + $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 ) +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/qualified_classname.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/qualified_classname.drl new file mode 100644 index 00000000000..131da29239d --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/qualified_classname.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler.test; + +rule "Who likes Stilton" + when + com.cheeseco.Cheese($type : type == "stilton") + then + System.out.println( $name + " likes " + $type); +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/query_and_rule.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/query_and_rule.drl new file mode 100644 index 00000000000..621e1509833 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/query_and_rule.drl @@ -0,0 +1,45 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +package foo + +rule bar + when + Baz() + then + Boo() +end + +query "simple_query" + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + +end + +rule bar2 + when + Baz() + then + Boo() +end + +query "simple_query2" + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes.drl new file mode 100644 index 00000000000..9ac9870bf8b --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes.drl @@ -0,0 +1,31 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + + + +rule simple_rule + // attributes keywork (and colon) is totally optional + salience 42 + agenda-group "my_group" + no-loop + duration 42 + activation-group "my_activation_group" + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes2.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes2.drl new file mode 100644 index 00000000000..66d83801ca1 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes2.drl @@ -0,0 +1,44 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package foo.bar + + +rule rule1 + salience (42) + agenda-group "my_group" + when + Foo() + then + bar(); +end + +rule rule2 + salience (Integer.MIN_VALUE) + no-loop + when + Foo() + then + bar(); +end + +rule rule3 + enabled (Boolean.TRUE) + activation-group "my_activation_group" + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes_alt.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes_alt.drl new file mode 100644 index 00000000000..c60c76513af --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes_alt.drl @@ -0,0 +1,26 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + + + +rule simple_rule + attributes: + salience 42, agenda-group "my_group", no-loop, lock-on-active, duration 42, activation-group "my_activation_group" + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute.drl new file mode 100644 index 00000000000..0bc1aca9a38 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + calendars "cal1" + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute2.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute2.drl new file mode 100644 index 00000000000..3950f6643e7 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute2.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + calendars "cal 1", "cal 2", "cal 3" + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_duration_expression.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_duration_expression.drl new file mode 100644 index 00000000000..e3dadd58cf2 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_duration_expression.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + duration ( 1h30m ) + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_enabled_expression.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_enabled_expression.drl new file mode 100644 index 00000000000..dd90e32fdbe --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_enabled_expression.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + enabled ( 1 + 1 == 2 ) + salience ( 1+2 ) + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_names_number_prefix.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_names_number_prefix.drl new file mode 100644 index 00000000000..981bfb446b1 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_names_number_prefix.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule "1. Do Stuff!" + when + then +end + +rule "2. Do More Stuff!" + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_not.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_not.drl new file mode 100644 index 00000000000..e2cfc444e8d --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_not.drl @@ -0,0 +1,22 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + when + not Cheese(type == "stilton") + then + funky(); +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/semicolon.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/semicolon.drl new file mode 100644 index 00000000000..d81c66b398f --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/semicolon.drl @@ -0,0 +1,41 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.mvel.compiler + +global java.util.List list; + +rule "rule1" +when + Pattern1(); + Pattern2() from x.y.z; +then + System.out.println("Test"); +end; + +query "query1" + Pattern5(); + Pattern6(); + Pattern7(); +end; + +rule "rule2" +when + Pattern3(); + Pattern4() from collect( Pattern5() ); +then + System.out.println("Test"); +end; + diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_query.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_query.drl new file mode 100644 index 00000000000..66e65f33968 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_query.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + + +query "simple_query" + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/soundslike_operator.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/soundslike_operator.drl new file mode 100644 index 00000000000..587b1baa3c6 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/soundslike_operator.drl @@ -0,0 +1,28 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package nesting; + + + + +rule "test something" + + when + p: Person( name soundslike "Michael" ) + then + p.name = "goober" + System.out.println(p.name) +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/statement_ordering_1.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/statement_ordering_1.drl new file mode 100644 index 00000000000..120e884ea76 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/statement_ordering_1.drl @@ -0,0 +1,43 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +package com.foo; + +import im.one + +import im.two + +rule foo + when + then +end + +function cheeseIt() { + +} + +import im.three; + +rule bar + when + then +end + +function uncheeseIt() { + +} + +import im.four; \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_CommentLineNumbersInConsequence.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_CommentLineNumbersInConsequence.drl new file mode 100644 index 00000000000..0a120702c34 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_CommentLineNumbersInConsequence.drl @@ -0,0 +1,32 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package la + + +rule simple_rule + when + Baz() + then + //woot + first + + // + + /* lala + + */ + second +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EndPosition.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EndPosition.drl new file mode 100644 index 00000000000..e74a5d098b6 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EndPosition.drl @@ -0,0 +1,25 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + + + +rule simple_rule + when + Foo( + bar == baz, la==laz + ) + then +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/type_with_meta.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/type_with_meta.drl new file mode 100644 index 00000000000..64e8eb999bd --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/type_with_meta.drl @@ -0,0 +1,46 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +package org.drools.compiler + +declare NetworkNode + locElevation: java.math.BigDecimal + name: String @key + nodeClass: String + locLongitude: java.math.BigDecimal + nodeType: String + locLatitude: java.math.BigDecimal +end + +declare NetworkConnection + id: String @key + node1: NetworkNode + node2: NetworkNode + hops: Integer +end + +declare NetworkEvent + @role( event ) + @timestamp( creationTime ) + + id: String @key + locElevation: java.math.BigDecimal + description: String + sourceComponent: NetworkNode + locLongitude: java.math.BigDecimal + severity: Integer + creationTime: java.util.Date + locLatitude: java.math.BigDecimal +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_eval.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_eval.drl new file mode 100644 index 00000000000..b888b36ad8e --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_eval.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + when + Foo() + Bar() + eval(abc("foo")) + then +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_predicate.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_predicate.drl new file mode 100644 index 00000000000..8198cc0bfa9 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_predicate.drl @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + when + Person( $age2:age, $age2 == $age1+2 ) + then +end diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_retval.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_retval.drl new file mode 100644 index 00000000000..2dc779a1cce --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_retval.drl @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + + +rule simple_rule + when + Foo(name== (a + b)) + then +end From 72ac4967cc974a17e45f99be7960cbb44f724f89 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 13 Mar 2023 16:33:40 +0900 Subject: [PATCH 028/141] [DROOLS-7285] Failed to parse and/or with parentheses in LHS (#15) --- .../src/main/antlr4/org/drools/parser/DRLParser.g4 | 2 +- .../src/main/java/org/drools/parser/DRLVisitorImpl.java | 3 +++ .../src/test/java/org/drools/parser/MiscDRLParserTest.java | 1 - 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index a15d73dc7d6..e1b625306c9 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -39,7 +39,7 @@ ruledef : DRL_RULE name=stringId (EXTENDS stringId)? drlAnnotation* attributes? lhs : DRL_WHEN lhsExpression? ; lhsExpression : lhsOr+ ; lhsOr : LPAREN DRL_OR lhsAnd+ RPAREN | lhsAnd (DRL_OR lhsAnd)* ; -lhsAnd : LPAREN DRL_AND lhsUnary+ RPAREN | lhsUnary (DRL_AND lhsUnary)* ; +lhsAnd : LPAREN lhsAnd RPAREN | LPAREN DRL_AND lhsUnary+ RPAREN | lhsUnary (DRL_AND lhsUnary)* ; /* lhsUnary : ( lhsExists namedConsequence? diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 12fcc510a08..fcc05872af3 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -301,6 +301,9 @@ public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { @Override public BaseDescr visitLhsAnd(DRLParser.LhsAndContext ctx) { + if (ctx.lhsAnd() != null) { + return visitLhsAnd(ctx.lhsAnd()); + } if (!ctx.DRL_AND().isEmpty()) { AndDescr andDescr = new AndDescr(); List descrList = visitDescrChildren(ctx); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 2dcaa0061c2..9e896cd6e0c 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -1224,7 +1224,6 @@ public void parse_BoundVariables() throws Exception { assertThat(fld.getExpression()).isEqualTo("likes == $type"); } - @Disabled("Priority : High | Failed to parse and/or with parentheses in LHS") @Test public void parse_OrNesting() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( From 1fdeea8ff76a03c7bd1c5c2856bd16bacee6bee2 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 18 May 2023 20:52:48 +0900 Subject: [PATCH 029/141] [DROOLS-7286] Failed to parse binding with || (#21) --- .../antlr4/org/drools/parser/DRLParser.g4 | 4 +- .../org/drools/parser/DRLParserHelper.java | 12 +++--- .../org/drools/parser/DRLParserWrapper.java | 2 +- .../org/drools/parser/DRLVisitorImpl.java | 42 ++++++------------- .../org/drools/parser/ParserStringUtils.java | 7 ++++ .../org/drools/parser/MiscDRLParserTest.java | 2 - 6 files changed, 28 insertions(+), 41 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index e1b625306c9..be4ab9c6712 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -67,14 +67,14 @@ lhsPattern : xpathPrimary (OVER patternFilter)? | lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN (DRL_FROM patternSource)? ; positionalConstraints : constraint (COMMA constraint)* SEMI ; constraints : constraint (COMMA constraint)* ; -constraint : label? ( nestedConstraint | conditionalOrExpression ) ; +constraint : ( nestedConstraint | conditionalOrExpression ) ; nestedConstraint : ( IDENTIFIER ( DOT | HASH ) )* IDENTIFIER DOT LPAREN constraints RPAREN ; conditionalOrExpression : left=conditionalAndExpression (OR right=conditionalAndExpression)* ; conditionalAndExpression : left=inclusiveOrExpression (AND right=inclusiveOrExpression)* ; inclusiveOrExpression : left=exclusiveOrExpression (BITOR right=exclusiveOrExpression)* ; exclusiveOrExpression : left=andExpression (CARET right=andExpression)* ; andExpression : left=equalityExpression (BITAND right=equalityExpression)* ; -equalityExpression : left=instanceOfExpression ( ( op=EQUAL | op=NOTEQUAL ) right=instanceOfExpression )* ; +equalityExpression : label? left=instanceOfExpression ( ( op=EQUAL | op=NOTEQUAL ) right=instanceOfExpression )* ; instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; inExpression : left=relationalExpression ( 'not'? 'in' LPAREN drlExpression (COMMA drlExpression)* RPAREN )? ; relationalExpression : left=drlExpression (right=orRestriction)* ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index 9d42bf09641..3bd15b3f4fa 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -4,6 +4,7 @@ import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; @@ -15,11 +16,8 @@ private DRLParserHelper() { } public static PackageDescr parse(String drl) { - return compilationUnitContext2PackageDescr(createParseTree(drl)); - } - - public static DRLParser.CompilationUnitContext createParseTree(String drl) { - return createDrlParser(drl).compilationUnit(); + DRLParser drlParser = createDrlParser(drl); + return compilationUnitContext2PackageDescr(drlParser.compilationUnit(), drlParser.getTokenStream()); } public static DRLParser createDrlParser(String drl) { @@ -29,8 +27,8 @@ public static DRLParser createDrlParser(String drl) { return new DRLParser(commonTokenStream); } - public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.CompilationUnitContext ctx) { - DRLVisitorImpl visitor = new DRLVisitorImpl(); + public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.CompilationUnitContext ctx, TokenStream tokenStream) { + DRLVisitorImpl visitor = new DRLVisitorImpl(tokenStream); Object descr = visitor.visit(ctx); if (descr instanceof PackageDescr) { return (PackageDescr) descr; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java index 7bfdcd89044..06992f0440e 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java @@ -26,7 +26,7 @@ public PackageDescr parse(String drl) { errors.addAll(errorListener.getErrors()); try { - return compilationUnitContext2PackageDescr(cxt); + return compilationUnitContext2PackageDescr(cxt, drlParser.getTokenStream()); } catch (Exception e) { LOGGER.error("Exception while creating PackageDescr", e); errors.add(new DRLParserError(e)); diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index fcc05872af3..2a2a2088eff 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -2,14 +2,13 @@ import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.RuleNode; -import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.AndDescr; import org.drools.drl.ast.descr.AnnotationDescr; import org.drools.drl.ast.descr.AttributeDescr; @@ -30,11 +29,19 @@ import org.drools.drl.ast.descr.UnitDescr; import static org.drools.parser.DRLParserHelper.getTextWithoutErrorNode; +import static org.drools.parser.ParserStringUtils.getTextPreservingWhitespace; +import static org.drools.parser.ParserStringUtils.getTokenTextPreservingWhitespace; import static org.drools.parser.ParserStringUtils.safeStripStringDelimiters; import static org.drools.util.StringUtils.unescapeJava; public class DRLVisitorImpl extends DRLParserBaseVisitor { + private TokenStream tokenStream; + + public DRLVisitorImpl(TokenStream tokenStream) { + this.tokenStream = tokenStream; + } + @Override public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { PackageDescr packageDescr = new PackageDescr(); @@ -119,7 +126,7 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { functionDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); }); } - functionDescr.setBody(ParserStringUtils.getTextPreservingWhitespace(ctx.block())); + functionDescr.setBody(getTextPreservingWhitespace(ctx.block())); return functionDescr; } @@ -145,7 +152,7 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { if (ctx.rhs() != null) { ruleDescr.setConsequenceLocation(ctx.rhs().getStart().getLine(), ctx.rhs().getStart().getCharPositionInLine()); // location of "then" - ruleDescr.setConsequence(ParserStringUtils.getTextPreservingWhitespace(ctx.rhs().consequence())); + ruleDescr.setConsequence(getTextPreservingWhitespace(ctx.rhs().consequence())); } return ruleDescr; @@ -342,31 +349,8 @@ private List visitDescrChildren(RuleNode node) { } // leaves of constraint concatenate return Strings - private String visitConstraintChildren(RuleNode node) { - return ((ParserRuleContext) node).children.stream() - .map(c -> c instanceof TerminalNode ? c : c.accept(this)) - .filter(Objects::nonNull) - .map(Object::toString) - .collect(Collectors.joining(" ")); - } - - @Override - public Object visitChildren(RuleNode node) { - if (hasConstraintAsAncestor(node)) { - return visitConstraintChildren(node); - } - return super.visitChildren(node); - } - - private boolean hasConstraintAsAncestor(RuleNode node) { - ParseTree parent = node.getParent(); - if (parent instanceof DRLParser.ConstraintContext) { - return true; - } else if (parent == null) { - return false; - } else { - return hasConstraintAsAncestor((RuleNode) parent); - } + private String visitConstraintChildren(ParserRuleContext ctx) { + return getTokenTextPreservingWhitespace(ctx, tokenStream); } private Optional visitFirstDescrChild(RuleNode node) { diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java index 58410e9ea36..0fcef4e5a10 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java @@ -1,6 +1,7 @@ package org.drools.parser; import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.misc.Interval; /** @@ -22,6 +23,7 @@ public static String safeStripStringDelimiters(String value) { } public static String getTextPreservingWhitespace(ParserRuleContext ctx) { + // Using raw CharStream int startIndex = ctx.start.getStartIndex(); int stopIndex = ctx.stop.getStopIndex(); if (startIndex > stopIndex) { @@ -31,4 +33,9 @@ public static String getTextPreservingWhitespace(ParserRuleContext ctx) { Interval interval = new Interval(startIndex, stopIndex); return ctx.start.getTokenSource().getInputStream().getText(interval); } + + public static String getTokenTextPreservingWhitespace(ParserRuleContext ctx, TokenStream tokenStream) { + // tokenStream is required to get hidden channel token (e.g. whitespace). Unlike getTextPreservingWhitespace, this method reflects Lexer normalizeString + return tokenStream.getText(ctx.start, ctx.stop); + } } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 9e896cd6e0c..d053f6ae295 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -3114,7 +3114,6 @@ public void parse_BigLiterals() throws Exception { assertThat(ecd.getExpression()).isEqualTo("bigDecimal < 50B"); } - @Disabled("Priority : High | Failed to parse binding with ||") @Test public void parse_BindingComposite() throws Exception { final String text = "rule X when Person( $name : name == \"Bob\" || $loc : location == \"Montreal\" ) then end"; @@ -3130,7 +3129,6 @@ public void parse_BindingComposite() throws Exception { assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name == \"Bob\" || $loc : location == \"Montreal\""); } - @Disabled("Priority : High | Failed to parse binding with ||") @Test public void parse_BindingCompositeWithMethods() throws Exception { final String text = "rule X when Person( $name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\" ) then end"; From e5a0ba881924a77ed2cb7608bd29effbed4e0b92 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 19 Jul 2023 16:17:27 +0900 Subject: [PATCH 030/141] [DROOLS-7287] Failed to parse comments in RHS (#23) * [DROOLS-7287] Failed to parse comments in RHS * - add rhs string check --- .../src/main/java/org/drools/parser/DRLVisitorImpl.java | 3 ++- .../main/java/org/drools/parser/ParserStringUtils.java | 8 ++++++++ .../test/java/org/drools/parser/MiscDRLParserTest.java | 3 +-- .../parser/test_CommentLineNumbersInConsequence.drl | 4 ++-- 4 files changed, 13 insertions(+), 5 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 2a2a2088eff..7f69502301d 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -32,6 +32,7 @@ import static org.drools.parser.ParserStringUtils.getTextPreservingWhitespace; import static org.drools.parser.ParserStringUtils.getTokenTextPreservingWhitespace; import static org.drools.parser.ParserStringUtils.safeStripStringDelimiters; +import static org.drools.parser.ParserStringUtils.trimThen; import static org.drools.util.StringUtils.unescapeJava; public class DRLVisitorImpl extends DRLParserBaseVisitor { @@ -152,7 +153,7 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { if (ctx.rhs() != null) { ruleDescr.setConsequenceLocation(ctx.rhs().getStart().getLine(), ctx.rhs().getStart().getCharPositionInLine()); // location of "then" - ruleDescr.setConsequence(getTextPreservingWhitespace(ctx.rhs().consequence())); + ruleDescr.setConsequence(trimThen(getTextPreservingWhitespace(ctx.rhs()))); } return ruleDescr; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java index 0fcef4e5a10..1f84eb6f9c8 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java @@ -38,4 +38,12 @@ public static String getTokenTextPreservingWhitespace(ParserRuleContext ctx, Tok // tokenStream is required to get hidden channel token (e.g. whitespace). Unlike getTextPreservingWhitespace, this method reflects Lexer normalizeString return tokenStream.getText(ctx.start, ctx.stop); } + + public static String trimThen(String rhs) { + if (rhs.startsWith("then")) { + return rhs.substring("then".length()); + } else { + throw new DRLParserException("rhs has to start with 'then' : rhs = " + rhs); + } + } } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index d053f6ae295..ed5532ff2f9 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -901,7 +901,6 @@ public void parse_LineNumberInAST() throws Exception { assertThat(third.getLine()).isEqualTo(21); } - @Disabled("Priority : High | Failed to parse comments in RHS") @Test public void parse_LineNumberIncludingCommentsInRHS() throws Exception { PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -910,7 +909,7 @@ public void parse_LineNumberIncludingCommentsInRHS() throws Exception { assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); final String rhs = (String) ((RuleDescr) pkg.getRules().get( 0 )).getConsequence(); - String expected = "\\s*//woot$\\s*first$\\s*$\\s*//$\\s*$\\s*/\\* lala$\\s*$\\s*\\*/$\\s*second$\\s*"; + String expected = "\\s*//woot$\\s*first;$\\s*$\\s*//$\\s*$\\s*/\\* lala$\\s*$\\s*\\*/$\\s*second;$\\s*"; assertThat(Pattern.compile(expected, Pattern.DOTALL | Pattern.MULTILINE).matcher(rhs).matches()).isTrue(); } diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_CommentLineNumbersInConsequence.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_CommentLineNumbersInConsequence.drl index 0a120702c34..5ed4e1ca301 100644 --- a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_CommentLineNumbersInConsequence.drl +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_CommentLineNumbersInConsequence.drl @@ -21,12 +21,12 @@ rule simple_rule Baz() then //woot - first + first; // /* lala */ - second + second; end From 977ce8211fcf595b8552cbc088b8f0c2ce3c2bbd Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 14 Aug 2023 15:55:41 +0900 Subject: [PATCH 031/141] [DROOLS-7515] Parser : Accept plain text in RHS (#26) * [DROOLS-7515] Parser : Accept plain text in RHS * - Handle keyword token in RHS * - Removed sysout * - Revert statementKeywords. Instead, define DRL_END with newline or EOF * - fix method name --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 9 +- .../antlr4/org/drools/parser/DRLParser.g4 | 97 +------------------ .../java/org/drools/parser/DRLParserTest.java | 6 +- .../org/drools/parser/MiscDRLParserTest.java | 44 +++++++++ 4 files changed, 53 insertions(+), 103 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 60e282c49fb..0e91fb3f2e5 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -30,11 +30,11 @@ import JavaLexer; DRL_UNIT : 'unit'; DRL_FUNCTION : 'function'; DRL_GLOBAL : 'global'; +DRL_DECLARE : 'declare'; DRL_RULE : 'rule'; DRL_QUERY : 'query'; DRL_WHEN : 'when'; -DRL_THEN : 'then'; -DRL_END : 'end'; +DRL_THEN : 'then' -> pushMode(RHS); DRL_AND : 'and'; DRL_OR : 'or'; @@ -114,3 +114,8 @@ fragment DrlUnicodeEscape : '\\' 'u' HexDigit HexDigit HexDigit HexDigit ; + +mode RHS; +RHS_WS : [ \t\r\n\u000C]+ -> channel(HIDDEN); +DRL_END : 'end' [ \t]* ('\n' | '\r\n' | EOF) {setText("end");} -> popMode; +RHS_CHUNK : ~[ \t\r\n\u000C]+ ; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index be4ab9c6712..af10b445e97 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -273,7 +273,7 @@ lhsNot : DRL_NOT lhsPatternBind ; rhs : DRL_THEN consequence ; -consequence : drlRhsBlockStatement* ; +consequence : RHS_CHUNK* ; stringId : ( IDENTIFIER | DRL_STRING_LITERAL ) ; @@ -309,107 +309,12 @@ assignmentOperator : ASSIGN label : IDENTIFIER COLON ; unif : IDENTIFIER UNIFY ; -/* extending JavaParser blockStatement */ -drlRhsBlockStatement - : drlLocalVariableDeclaration SEMI - | drlRhsStatement - | localTypeDeclaration - ; - -/* extending JavaParser localVariableDeclaration */ -drlLocalVariableDeclaration - : variableModifier* (typeType drlVariableDeclarators | VAR drlIdentifier ASSIGN drlExpression) - ; - -/* extending JavaParser variableDeclarators */ -drlVariableDeclarators - : drlVariableDeclarator (COMMA drlVariableDeclarator)* - ; - -/* extending JavaParser variableDeclarator */ -drlVariableDeclarator - : drlVariableDeclaratorId (ASSIGN drlVariableInitializer)? - ; - -/* extending JavaParser variableDeclaratorId */ -drlVariableDeclaratorId - : drlIdentifier (LBRACK RBRACK)* - ; - /* extending JavaParser variableInitializer */ drlVariableInitializer : arrayInitializer | drlExpression ; - -/* extending JavaParser statement */ -drlRhsStatement - : blockLabel=block - | ASSERT drlRhsExpression (COLON drlRhsExpression)? SEMI - | IF parExpression drlRhsStatement (ELSE drlRhsStatement)? - | FOR LPAREN forControl RPAREN drlRhsStatement - | WHILE parExpression drlRhsStatement - | DO drlRhsStatement WHILE parExpression SEMI - | TRY block (catchClause+ finallyBlock? | finallyBlock) - | TRY resourceSpecification block catchClause* finallyBlock? - | SWITCH parExpression LBRACE switchBlockStatementGroup* switchLabel* RBRACE - | SYNCHRONIZED parExpression block - | RETURN drlRhsExpression? SEMI - | THROW drlRhsExpression SEMI - | BREAK drlIdentifier? SEMI - | CONTINUE drlIdentifier? SEMI - | YIELD drlRhsExpression SEMI // Java17 - | SEMI - | statementExpression=drlRhsExpression SEMI - | switchExpression SEMI? // Java17 - | identifierLabel=drlIdentifier COLON drlRhsStatement - ; - -/* extending JavaParser expression */ -drlRhsExpression - : drlPrimary - | drlRhsExpression bop=DOT - ( - drlIdentifier - | methodCall - | THIS - | NEW nonWildcardTypeArguments? innerCreator - | SUPER superSuffix - | explicitGenericInvocation - ) - | drlRhsExpression LBRACK drlRhsExpression RBRACK - | methodCall - | NEW creator - | LPAREN annotation* typeType (BITAND typeType)* RPAREN drlRhsExpression - | drlRhsExpression postfix=(INC | DEC) - | prefix=(ADD|SUB|INC|DEC) drlRhsExpression - | prefix=(TILDE|BANG) drlRhsExpression - | drlRhsExpression bop=(MUL|DIV|MOD) drlRhsExpression - | drlRhsExpression bop=(ADD|SUB) drlRhsExpression - | drlRhsExpression (LT LT | GT GT GT | GT GT) drlRhsExpression - | drlRhsExpression bop=(LE | GE | GT | LT) drlRhsExpression - | drlRhsExpression bop=INSTANCEOF (typeType | pattern) - | drlRhsExpression bop=DRL_MATCHES drlRhsExpression - | drlRhsExpression bop=(EQUAL | NOTEQUAL) drlRhsExpression - | drlRhsExpression bop=BITAND drlRhsExpression - | drlRhsExpression bop=CARET drlRhsExpression - | drlRhsExpression bop=BITOR drlRhsExpression - | drlRhsExpression bop=AND drlRhsExpression - | drlRhsExpression bop=OR drlRhsExpression - | drlRhsExpression bop=QUESTION drlRhsExpression COLON drlRhsExpression - | drlRhsExpression - bop=(ASSIGN | ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | RSHIFT_ASSIGN | URSHIFT_ASSIGN | LSHIFT_ASSIGN | MOD_ASSIGN) - drlRhsExpression - | lambdaExpression // Java8 - | switchExpression // Java17 - - // Java 8 methodReference - | drlRhsExpression COLONCOLON typeArguments? drlIdentifier - | typeType COLONCOLON (typeArguments? drlIdentifier | NEW) - | classType COLONCOLON typeArguments? NEW - ; - drlCreator : nonWildcardTypeArguments createdName classCreatorRest | createdName (drlArrayCreatorRest | classCreatorRest) diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java index 4b9497b422a..83a8b1f5d23 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java @@ -90,10 +90,6 @@ void computeTokenIndex_basicRule() { assertThat((int) computeTokenIndex(parser, 2, 1)).isEqualTo(7); assertThat((int) computeTokenIndex(parser, 2, 6)).isEqualTo(7); assertThat((int) computeTokenIndex(parser, 2, 7)).isEqualTo(8); - assertThat((int) computeTokenIndex(parser, 9, 0)).isEqualTo(80); - assertThat((int) computeTokenIndex(parser, 9, 1)).isEqualTo(81); - assertThat((int) computeTokenIndex(parser, 9, 4)).isEqualTo(82); - assertThat((int) computeTokenIndex(parser, 9, 5)).isEqualTo(82); - assertThat((int) computeTokenIndex(parser, 10, 0)).isEqualTo(82); // EOF + // Skip RHS token assertion as it is fluid part at the moment. } } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index ed5532ff2f9..dd88f613513 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -3279,4 +3279,48 @@ public void parse_WindowUsage() throws Exception { assertThat(pd.getSource().getText()).isEqualTo("Y"); } + @Test + public void endInRhs() throws Exception { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " System.out.println($s.endsWith(\"xyz\"));\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text ); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("System.out.println($s.endsWith(\"xyz\"));"); + } + + @Test + public void endTokenInRhs() throws Exception { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " int end = 10;\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text ); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int end = 10;"); + } + + @Test + public void ruleTokenInRhs() throws Exception { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " int rule = 10;\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text ); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int rule = 10;"); + } } From c346cfc0e603c07574c2da09325d00cb2b49eb32 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 24 Aug 2023 16:16:16 +0900 Subject: [PATCH 032/141] [DROOLS-7288] Failed to parse complex parentheses (#27) * [DROOLS-7288] Failed to parse complex parentheses - bump to 8.43.0.Final * additional tests --- .../antlr4/org/drools/parser/DRLParser.g4 | 14 ++- .../org/drools/parser/DRLVisitorImpl.java | 41 +++---- .../org/drools/parser/MiscDRLParserTest.java | 112 +++++++++++++++++- 3 files changed, 130 insertions(+), 37 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index af10b445e97..c150a480e4a 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -36,10 +36,15 @@ globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; ruledef : DRL_RULE name=stringId (EXTENDS stringId)? drlAnnotation* attributes? lhs rhs DRL_END ; -lhs : DRL_WHEN lhsExpression? ; -lhsExpression : lhsOr+ ; -lhsOr : LPAREN DRL_OR lhsAnd+ RPAREN | lhsAnd (DRL_OR lhsAnd)* ; -lhsAnd : LPAREN lhsAnd RPAREN | LPAREN DRL_AND lhsUnary+ RPAREN | lhsUnary (DRL_AND lhsUnary)* ; +lhs : DRL_WHEN lhsExpression* ; + +lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed + | lhsUnary #lhsUnarySingle + | LPAREN DRL_AND lhsExpression+ RPAREN #lhsAnd + | lhsExpression (DRL_AND lhsExpression)+ #lhsAnd + | LPAREN DRL_OR lhsExpression+ RPAREN #lhsOr + | lhsExpression (DRL_OR lhsExpression)+ #lhsOr + ; /* lhsUnary : ( lhsExists namedConsequence? @@ -57,6 +62,7 @@ lhsUnary : ( | lhsNot | lhsPatternBind ) ; + lhsPatternBind : label? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; /* diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 7f69502301d..22858fba9fc 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -186,17 +186,12 @@ public AttributeDescr visitAttribute(DRLParser.AttributeContext ctx) { @Override public List visitLhs(DRLParser.LhsContext ctx) { if (ctx.lhsExpression() != null) { - return visitLhsExpression(ctx.lhsExpression()); + return visitDescrChildren(ctx); } else { return new ArrayList<>(); } } - @Override - public List visitLhsExpression(DRLParser.LhsExpressionContext ctx) { - return visitDescrChildren(ctx); - } - @Override public BaseDescr visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { if (ctx.lhsPattern().size() == 1) { @@ -294,33 +289,25 @@ public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { return notDescr; } + @Override + public BaseDescr visitLhsExpressionEnclosed(DRLParser.LhsExpressionEnclosedContext ctx) { + return (BaseDescr) visit(ctx.lhsExpression()); + } + @Override public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { - if (!ctx.DRL_OR().isEmpty()) { - OrDescr orDescr = new OrDescr(); - List descrList = visitDescrChildren(ctx); - descrList.forEach(orDescr::addDescr); - return orDescr; - } else { - // No DRL_OR means only one lhsAnd - return visitLhsAnd(ctx.lhsAnd().get(0)); - } + OrDescr orDescr = new OrDescr(); + List descrList = visitDescrChildren(ctx); + descrList.forEach(orDescr::addDescr); + return orDescr; } @Override public BaseDescr visitLhsAnd(DRLParser.LhsAndContext ctx) { - if (ctx.lhsAnd() != null) { - return visitLhsAnd(ctx.lhsAnd()); - } - if (!ctx.DRL_AND().isEmpty()) { - AndDescr andDescr = new AndDescr(); - List descrList = visitDescrChildren(ctx); - descrList.forEach(andDescr::addDescr); - return andDescr; - } else { - // No DRL_AND means only one lhsUnary - return visitLhsUnary(ctx.lhsUnary().get(0)); - } + AndDescr andDescr = new AndDescr(); + List descrList = visitDescrChildren(ctx); + descrList.forEach(andDescr::addDescr); + return andDescr; } @Override diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index dd88f613513..011926dc1b3 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -1389,22 +1389,21 @@ public void parse_OrBindingWithBrackets() throws Exception { assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); } - @Disabled("Priority : High | Failed to parse complex parentheses") @Test - public void parse_BracketsPrecedence() throws Exception { + void parenthesesOrAndOr() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "brackets_precedence.drl" ); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); final AndDescr rootAnd = (AndDescr) rule.getLhs(); - assertThat(rootAnd.getDescrs().size()).isEqualTo(2); + assertThat(rootAnd.getDescrs()).hasSize(2); final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get( 0 ); - assertThat(leftOr.getDescrs().size()).isEqualTo(2); + assertThat(leftOr.getDescrs()).hasSize(2); final NotDescr not = (NotDescr) leftOr.getDescrs().get( 0 ); final PatternDescr foo1 = (PatternDescr) not.getDescrs().get( 0 ); assertThat(foo1.getObjectType()).isEqualTo("Foo"); @@ -1413,13 +1412,114 @@ public void parse_BracketsPrecedence() throws Exception { final OrDescr rightOr = (OrDescr) rootAnd.getDescrs().get( 1 ); - assertThat(rightOr.getDescrs().size()).isEqualTo(2); + assertThat(rightOr.getDescrs()).hasSize(2); final PatternDescr shoes = (PatternDescr) rightOr.getDescrs().get( 0 ); assertThat(shoes.getObjectType()).isEqualTo("Shoes"); final PatternDescr butt = (PatternDescr) rightOr.getDescrs().get( 1 ); assertThat(butt.getObjectType()).isEqualTo("Butt"); } + @Test + void parenthesesAndOrOr() { + final String drl = "rule and_or_or\n" + + " when\n" + + " (Foo(x == 1) and Bar(x == 2)) or (Foo(x == 3) or Bar(x == 4))\n" + + " then\n" + + "end"; + PackageDescr pkg = parser.parse(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final AndDescr leftAnd = (AndDescr) topOr.getDescrs().get(0); + assertThat(leftAnd.getDescrs()).hasSize(2); + final PatternDescr foo1 = (PatternDescr) leftAnd.getDescrs().get(0); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar1 = (PatternDescr) leftAnd.getDescrs().get(1); + assertThat(bar1.getObjectType()).isEqualTo("Bar"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).hasSize(2); + final PatternDescr foo2 = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar2 = (PatternDescr) rightOr.getDescrs().get(1); + assertThat(bar2.getObjectType()).isEqualTo("Bar"); + } + + @Test + void parenthesesOrAndAnd() { + final String drl = "rule or_and_and\n" + + " when\n" + + " (Foo(x == 1) or Bar(x == 2)) and (Foo(x == 3) and Bar(x == 4))\n" + + " then\n" + + "end"; + PackageDescr pkg = parser.parse(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(2); + + final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(leftOr.getDescrs()).hasSize(2); + final PatternDescr foo1 = (PatternDescr) leftOr.getDescrs().get(0); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar1 = (PatternDescr) leftOr.getDescrs().get(1); + assertThat(bar1.getObjectType()).isEqualTo("Bar"); + + final AndDescr rightAnd = (AndDescr) rootAnd.getDescrs().get(1); + assertThat(rightAnd.getDescrs()).hasSize(2); + final PatternDescr foo2 = (PatternDescr) rightAnd.getDescrs().get(0); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar2 = (PatternDescr) rightAnd.getDescrs().get(1); + assertThat(bar2.getObjectType()).isEqualTo("Bar"); + } + + @Test + void parenthesesAndOrOrOrAnd() throws Exception { + final String drl = "rule and_or_or_or_and\n" + + " when\n" + + " (Foo(x == 1) and (Bar(x == 2) or Foo(x == 3))) or (Bar(x == 4) or (Foo(x == 5) and Bar(x == 6)))\n" + + " then\n" + + "end"; + PackageDescr pkg = parser.parse(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final AndDescr leftAnd = (AndDescr) topOr.getDescrs().get(0); + assertThat(leftAnd.getDescrs()).hasSize(2); + final PatternDescr foo1 = (PatternDescr) leftAnd.getDescrs().get(0); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final OrDescr leftOr = (OrDescr) leftAnd.getDescrs().get(1); + assertThat(leftOr.getDescrs()).hasSize(2); + final PatternDescr bar1 = (PatternDescr) leftOr.getDescrs().get(0); + assertThat(bar1.getObjectType()).isEqualTo("Bar"); + final PatternDescr foo2 = (PatternDescr) leftOr.getDescrs().get(1); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).hasSize(2); + final PatternDescr bar2 = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(bar2.getObjectType()).isEqualTo("Bar"); + final AndDescr rightAnd = (AndDescr) rightOr.getDescrs().get(1); + assertThat(rightAnd.getDescrs()).hasSize(2); + final PatternDescr foo3 = (PatternDescr) rightAnd.getDescrs().get(0); + assertThat(foo3.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar3 = (PatternDescr) rightAnd.getDescrs().get(1); + assertThat(bar3.getObjectType()).isEqualTo("Bar"); + } + @Disabled("Priority : High | Implement eval") @Test public void parse_EvalMultiple() throws Exception { From baaa0c14bf0dff3ea7109e7bb28d6fb5ff2a39dc Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 20 Sep 2023 17:01:07 +0900 Subject: [PATCH 033/141] [DROOLS-7289] Implement accumulate (#28) --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 5 ++ .../antlr4/org/drools/parser/DRLParser.g4 | 47 +++++++++++- .../org/drools/parser/DRLVisitorImpl.java | 71 +++++++++++++++++-- .../org/drools/parser/MiscDRLParserTest.java | 12 +--- 4 files changed, 117 insertions(+), 18 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 0e91fb3f2e5..0eb6d961bce 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -44,6 +44,11 @@ DRL_NOT : 'not'; DRL_IN : 'in'; DRL_FROM : 'from'; DRL_MATCHES : 'matches'; +DRL_ACCUMULATE : 'accumulate' | 'acc'; +DRL_INIT : 'init'; +DRL_ACTION : 'action'; +DRL_REVERSE : 'reverse'; +DRL_RESULT : 'result'; DRL_SALIENCE : 'salience'; DRL_ENABLED : 'enabled'; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index c150a480e4a..1b96c788b3b 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -46,6 +46,11 @@ lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed | lhsExpression (DRL_OR lhsExpression)+ #lhsOr ; +// and is accepted for accumulate +lhsAndForAccumulate : lhsUnary (DRL_AND lhsUnary)+ + | LPAREN DRL_AND lhsUnary+ RPAREN + ; + /* lhsUnary : ( lhsExists namedConsequence? | lhsNot namedConsequence? @@ -61,6 +66,7 @@ lhsUnary : ( lhsExists | lhsNot | lhsPatternBind + | lhsAccumulate ) ; lhsPatternBind : label? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; @@ -257,9 +263,35 @@ mapEntry | fromWindow | fromExpression ) */ -patternSource : fromExpression ; +patternSource : fromExpression + | fromAccumulate + ; + fromExpression : conditionalOrExpression ; + +/* +fromAccumulate := ACCUMULATE LEFT_PAREN lhsAnd (COMMA|SEMICOLON) + ( INIT chunk_(_) COMMA ACTION chunk_(_) COMMA + ( REVERSE chunk_(_) COMMA)? RESULT chunk_(_) + | accumulateFunction + ) RIGHT_PAREN +*/ +fromAccumulate : DRL_ACCUMULATE LPAREN lhsAndForAccumulate (COMMA|SEMI) + ( DRL_INIT LPAREN initBlockStatements=blockStatements RPAREN COMMA DRL_ACTION LPAREN actionBlockStatements=blockStatements RPAREN COMMA ( DRL_REVERSE LPAREN reverseBlockStatements=blockStatements RPAREN COMMA)? DRL_RESULT LPAREN expression RPAREN + | accumulateFunction + ) + RPAREN (SEMI)? + ; + +blockStatements : blockStatement* ; + +/* +accumulateFunction := label? ID parameters +*/ +accumulateFunction : label? IDENTIFIER LPAREN drlExpression RPAREN; + + /* lhsExists := EXISTS ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or @@ -277,6 +309,19 @@ lhsExists : DRL_EXISTS lhsPatternBind ; */ lhsNot : DRL_NOT lhsPatternBind ; +/** + * lhsAccumulate := (ACCUMULATE|ACC) LEFT_PAREN lhsAnd (COMMA|SEMICOLON) + * accumulateFunctionBinding (COMMA accumulateFunctionBinding)* + * (SEMICOLON constraints)? + * RIGHT_PAREN SEMICOLON? + */ + +lhsAccumulate : DRL_ACCUMULATE LPAREN lhsAndForAccumulate (COMMA|SEMI) + accumulateFunction (COMMA accumulateFunction)* + (SEMI constraints)? + RPAREN (SEMI)? + ; + rhs : DRL_THEN consequence ; consequence : RHS_CHUNK* ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 22858fba9fc..e3e5a499df8 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -9,6 +9,7 @@ import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.RuleNode; +import org.drools.drl.ast.descr.AccumulateDescr; import org.drools.drl.ast.descr.AndDescr; import org.drools.drl.ast.descr.AnnotationDescr; import org.drools.drl.ast.descr.AttributeDescr; @@ -25,6 +26,7 @@ import org.drools.drl.ast.descr.OrDescr; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.PatternSourceDescr; import org.drools.drl.ast.descr.RuleDescr; import org.drools.drl.ast.descr.UnitDescr; @@ -234,17 +236,66 @@ private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindConte public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { PatternDescr patternDescr = new PatternDescr(ctx.objectType.getText()); if (ctx.patternSource() != null) { - String expression = ctx.patternSource().getText(); - FromDescr from = new FromDescr(); - from.setDataSource(new MVELExprDescr(expression)); - from.setResource(patternDescr.getResource()); - patternDescr.setSource(from); + PatternSourceDescr patternSourceDescr = (PatternSourceDescr) visitPatternSource(ctx.patternSource()); + patternSourceDescr.setResource(patternDescr.getResource()); + patternDescr.setSource(patternSourceDescr); } List constraintDescrList = visitConstraints(ctx.constraints()); constraintDescrList.forEach(patternDescr::addConstraint); return patternDescr; } + @Override + public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { + AccumulateDescr accumulateDescr = new AccumulateDescr(); + accumulateDescr.setInput(visitLhsAndForAccumulate(ctx.lhsAndForAccumulate())); + + // accumulate function + for (DRLParser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { + accumulateDescr.addFunction(visitAccumulateFunction(accumulateFunctionContext)); + } + + PatternDescr patternDescr = new PatternDescr("Object"); + patternDescr.setSource(accumulateDescr); + List constraintDescrList = visitConstraints(ctx.constraints()); + constraintDescrList.forEach(patternDescr::addConstraint); + return patternDescr; + } + + @Override + public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { + FromDescr fromDescr = new FromDescr(); + fromDescr.setDataSource(new MVELExprDescr(ctx.getText())); + return fromDescr; + } + + @Override + public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) { + AccumulateDescr accumulateDescr = new AccumulateDescr(); + accumulateDescr.setInput(visitLhsAndForAccumulate(ctx.lhsAndForAccumulate())); + if (ctx.DRL_INIT() != null) { + // inline custom accumulate + accumulateDescr.setInitCode(getTextPreservingWhitespace(ctx.initBlockStatements)); + accumulateDescr.setActionCode(getTextPreservingWhitespace(ctx.actionBlockStatements)); + if (ctx.DRL_REVERSE() != null) { + accumulateDescr.setReverseCode(getTextPreservingWhitespace(ctx.reverseBlockStatements)); + } + accumulateDescr.setResultCode(ctx.expression().getText()); + } else { + // accumulate function + accumulateDescr.addFunction(visitAccumulateFunction(ctx.accumulateFunction())); + } + return accumulateDescr; + } + + @Override + public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLParser.AccumulateFunctionContext ctx) { + String function = ctx.IDENTIFIER().getText(); + String bind = ctx.label() == null ? null : ctx.label().IDENTIFIER().getText(); + String[] params = new String[]{getTextPreservingWhitespace(ctx.drlExpression())}; + return new AccumulateDescr.AccumulateFunctionCallDescr(function, bind, false, params); + } + @Override public List visitConstraints(DRLParser.ConstraintsContext ctx) { if (ctx == null) { @@ -304,12 +355,20 @@ public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { @Override public BaseDescr visitLhsAnd(DRLParser.LhsAndContext ctx) { + return createAndDescr(visitDescrChildren(ctx)); + } + + private AndDescr createAndDescr(List descrList) { AndDescr andDescr = new AndDescr(); - List descrList = visitDescrChildren(ctx); descrList.forEach(andDescr::addDescr); return andDescr; } + @Override + public BaseDescr visitLhsAndForAccumulate(DRLParser.LhsAndForAccumulateContext ctx) { + return createAndDescr(visitDescrChildren(ctx)); + } + @Override public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { return (BaseDescr) visitChildren(ctx); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 011926dc1b3..96134e5ee28 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -305,7 +305,6 @@ void parse_fromWithInlineListMethod() { " System.err.println(\"Invalid customer id found!\"); \n" + " o.addError(\"Invalid customer id\"); \n" + "end \n"; - System.out.println(source); PackageDescr pkg = parser.parse(source); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); @@ -2011,7 +2010,6 @@ public void parse_QualifiedClassname() throws Exception { assertThat(p.getObjectType()).isEqualTo("com.cheeseco.Cheese"); } - @Disabled("Priority : High | Implement accumulate") @Test public void parse_Accumulate() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2034,7 +2032,6 @@ public void parse_Accumulate() throws Exception { assertThat(pattern.getObjectType()).isEqualTo("Person"); } - @Disabled("Priority : High | Implement accumulate") @Test public void parse_AccumulateWithBindings() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2356,7 +2353,6 @@ public void parse_Eval() throws Exception { assertThat(rule1.getLhs().getDescrs().size()).isEqualTo(1); } - @Disabled("Priority : High | Implement accumulate") @Test public void parse_AccumulateReverse() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2382,7 +2378,6 @@ public void parse_AccumulateReverse() throws Exception { assertThat(pattern.getObjectType()).isEqualTo("Person"); } - @Disabled("Priority : High | Implement accumulate") @Test public void parse_AccumulateExternalFunction() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2426,7 +2421,7 @@ public void parse_CollectWithNestedFrom() throws Exception { assertThat(people.getObjectType()).isEqualTo("People"); } - @Disabled("Priority : High | Implement accumulate") + @Disabled("Priority : High | Implement accumulate and Implement from collect") @Test public void parse_AccumulateWithNestedFrom() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2448,7 +2443,6 @@ public void parse_AccumulateWithNestedFrom() throws Exception { assertThat(people.getObjectType()).isEqualTo("People"); } - @Disabled("Priority : High | Implement accumulate") @Test public void parse_AccumulateMultipleFunctions() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2482,7 +2476,6 @@ public void parse_AccumulateMultipleFunctions() throws Exception { assertThat(pattern.getObjectType()).isEqualTo("Cheese"); } - @Disabled("Priority : High | Implement accumulate") @Test public void parse_AccumulateMnemonic() throws Exception { String drl = "package org.drools.mvel.compiler\n" + @@ -2515,7 +2508,6 @@ public void parse_AccumulateMnemonic() throws Exception { assertThat(pattern.getObjectType()).isEqualTo("Cheese"); } - @Disabled("Priority : High | Implement accumulate") @Test public void parse_AccumulateMnemonic2() throws Exception { String drl = "package org.drools.mvel.compiler\n" + @@ -2596,7 +2588,6 @@ public void parse_ImportAccumulate() throws Exception { assertThat(pattern.getObjectType()).isEqualTo("Cheese"); } - @Disabled("Priority : High | Implement accumulate") @Test public void parse_AccumulateMultipleFunctionsConstraint() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2701,7 +2692,6 @@ public void parse_RuleParseLhs3() throws Exception { } - @Disabled("Priority : High | Implement accumulate") @Test public void parse_AccumulateMultiPattern() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( From cee921d6b63213ba0770f24853e78abbc4b077c8 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 21 Sep 2023 16:12:04 +0900 Subject: [PATCH 034/141] [DROOLS-7296] Implement from entry-point (#30) --- .../src/main/antlr4/org/drools/parser/DRLLexer.g4 | 1 + .../src/main/antlr4/org/drools/parser/DRLParser.g4 | 2 ++ .../src/main/java/org/drools/parser/DRLVisitorImpl.java | 6 ++++++ .../src/test/java/org/drools/parser/MiscDRLParserTest.java | 2 -- 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 0eb6d961bce..8264c7b87e6 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -49,6 +49,7 @@ DRL_INIT : 'init'; DRL_ACTION : 'action'; DRL_REVERSE : 'reverse'; DRL_RESULT : 'result'; +DRL_ENTRY_POINT : 'entry-point'; DRL_SALIENCE : 'salience'; DRL_ENABLED : 'enabled'; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 1b96c788b3b..791ad29258b 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -265,6 +265,7 @@ mapEntry */ patternSource : fromExpression | fromAccumulate + | fromEntryPoint ; fromExpression : conditionalOrExpression ; @@ -291,6 +292,7 @@ accumulateFunction := label? ID parameters */ accumulateFunction : label? IDENTIFIER LPAREN drlExpression RPAREN; +fromEntryPoint : DRL_ENTRY_POINT stringId ; /* lhsExists := EXISTS diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index e3e5a499df8..7f4c0528e6d 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -14,6 +14,7 @@ import org.drools.drl.ast.descr.AnnotationDescr; import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.EntryPointDescr; import org.drools.drl.ast.descr.ExistsDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; import org.drools.drl.ast.descr.FromDescr; @@ -296,6 +297,11 @@ public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLPa return new AccumulateDescr.AccumulateFunctionCallDescr(function, bind, false, params); } + @Override + public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) { + return new EntryPointDescr(safeStripStringDelimiters(ctx.stringId().getText())); + } + @Override public List visitConstraints(DRLParser.ConstraintsContext ctx) { if (ctx == null) { diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 96134e5ee28..2bd999facef 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -2902,7 +2902,6 @@ public void parse_RuleWithLHSNesting() throws Exception { assertThat(g.getObjectType()).isEqualTo("G"); } - @Disabled("Priority : High | Implement from entry-point") @Test public void parse_EntryPoint() throws Exception { final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point StreamA then end"; @@ -2923,7 +2922,6 @@ public void parse_EntryPoint() throws Exception { assertThat(entry.getEntryId()).isEqualTo("StreamA"); } - @Disabled("Priority : High | Implement from entry-point") @Test public void parse_EntryPoint2() throws Exception { final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point \"StreamA\" then end"; From 2c29230e89dd43b77cbdc9ba157247fb4debeb83 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 22 Sep 2023 15:45:50 +0900 Subject: [PATCH 035/141] [DROOLS-7297] Implement import accumulate (#29) --- .../src/main/antlr4/org/drools/parser/DRLParser.g4 | 6 ++++-- .../main/java/org/drools/parser/DRLVisitorImpl.java | 13 ++++++++++++- .../java/org/drools/parser/MiscDRLParserTest.java | 1 - 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 791ad29258b..0daeb201ae1 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -28,7 +28,9 @@ packagedef : PACKAGE name=drlQualifiedName SEMI? ; unitdef : DRL_UNIT name=drlQualifiedName SEMI? ; -importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? SEMI? ; +importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? SEMI? #importStandardDef + | IMPORT DRL_ACCUMULATE drlQualifiedName IDENTIFIER SEMI? #importAccumulateDef + ; globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; @@ -47,7 +49,7 @@ lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed ; // and is accepted for accumulate -lhsAndForAccumulate : lhsUnary (DRL_AND lhsUnary)+ +lhsAndForAccumulate : lhsUnary (DRL_AND lhsUnary)* | LPAREN DRL_AND lhsUnary+ RPAREN ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 7f4c0528e6d..ff4a0f594ae 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -10,6 +10,7 @@ import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.RuleNode; import org.drools.drl.ast.descr.AccumulateDescr; +import org.drools.drl.ast.descr.AccumulateImportDescr; import org.drools.drl.ast.descr.AndDescr; import org.drools.drl.ast.descr.AnnotationDescr; import org.drools.drl.ast.descr.AttributeDescr; @@ -65,6 +66,8 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc packageDescr.addGlobal((GlobalDescr) descr); } else if (descr instanceof FunctionImportDescr) { packageDescr.addFunctionImport((FunctionImportDescr) descr); + } else if (descr instanceof AccumulateImportDescr) { + packageDescr.addAccumulateImport((AccumulateImportDescr) descr); } else if (descr instanceof ImportDescr) { packageDescr.addImport((ImportDescr) descr); } else if (descr instanceof FunctionDescr) { @@ -96,7 +99,7 @@ public GlobalDescr visitGlobaldef(DRLParser.GlobaldefContext ctx) { } @Override - public ImportDescr visitImportdef(DRLParser.ImportdefContext ctx) { + public ImportDescr visitImportStandardDef(DRLParser.ImportStandardDefContext ctx) { String target = ctx.drlQualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); if (ctx.DRL_FUNCTION() != null || ctx.STATIC() != null) { FunctionImportDescr functionImportDescr = new FunctionImportDescr(); @@ -111,6 +114,14 @@ public ImportDescr visitImportdef(DRLParser.ImportdefContext ctx) { } } + @Override + public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulateDefContext ctx) { + AccumulateImportDescr accumulateImportDescr = new AccumulateImportDescr(); + accumulateImportDescr.setTarget(ctx.drlQualifiedName().getText()); + accumulateImportDescr.setFunctionName(ctx.IDENTIFIER().getText()); + return accumulateImportDescr; + } + @Override public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { FunctionDescr functionDescr = new FunctionDescr(); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 2bd999facef..7b4074b16ec 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -2539,7 +2539,6 @@ public void parse_AccumulateMnemonic2() throws Exception { assertThat(pattern.getObjectType()).isEqualTo("Cheese"); } - @Disabled("Priority : High | Implement import accumulate") @Test public void parse_ImportAccumulate() throws Exception { String drl = "package org.drools.mvel.compiler\n" + From 757be741950575b956fd38c222d6548439603a45 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 22 Sep 2023 15:45:58 +0900 Subject: [PATCH 036/141] [DROOLS-7290] Implement BigInteger literal, BigDecimal literal (#31) --- .../src/main/antlr4/org/drools/parser/DRLLexer.g4 | 9 +++++++++ .../src/main/antlr4/org/drools/parser/DRLParser.g4 | 2 ++ .../test/java/org/drools/parser/MiscDRLParserTest.java | 7 +++---- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 8264c7b87e6..56d0ada08c4 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -85,6 +85,15 @@ DRL_STRING_LITERAL | ('\'' ( DrlEscapeSequence | ~('\\'|'\'') )* '\'') { setText( normalizeString( getText() ) ); } ; +DRL_BIG_DECIMAL_LITERAL + : ('0'..'9')+ [B] + | ('0'..'9')+ '.' ('0'..'9')+ [B] + ; + +DRL_BIG_INTEGER_LITERAL + : ('0'..'9')+ [I] + ; + ///////////////// // SYMBOLS ///////////////// diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 0daeb201ae1..d775f02b27f 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -230,6 +230,8 @@ drlPrimary drlLiteral : integerLiteral | floatLiteral + | DRL_BIG_DECIMAL_LITERAL + | DRL_BIG_INTEGER_LITERAL | CHAR_LITERAL | DRL_STRING_LITERAL | BOOL_LITERAL diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 7b4074b16ec..b678d1ccce5 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -3176,13 +3176,12 @@ public void parse_UnificationBinding() throws Exception { } - @Disabled("Priority : High | Implement BigInteger literal, BigDecimal literal") @Test - public void parse_BigLiterals() throws Exception { + public void parse_BigLiterals() { final String text = "rule X when Primitives( bigInteger == (10I), " + " bigDecimal == (10B), " + " bigInteger < 50I, " + - " bigDecimal < 50B ) then end"; + " bigDecimal < 50.2B ) then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( text ).getLhs().getDescrs().get( 0 ); @@ -3197,7 +3196,7 @@ public void parse_BigLiterals() throws Exception { assertThat(ecd.getExpression()).isEqualTo("bigInteger < 50I"); ecd = (ExprConstraintDescr) pattern.getDescrs().get( 3 ); - assertThat(ecd.getExpression()).isEqualTo("bigDecimal < 50B"); + assertThat(ecd.getExpression()).isEqualTo("bigDecimal < 50.2B"); } @Test From 1521e0548611b7c9cefca6098893ced328255918 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 22 Sep 2023 19:57:21 +0900 Subject: [PATCH 037/141] [DROOLS-7292] Implement eval (#32) --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 1 + .../antlr4/org/drools/parser/DRLParser.g4 | 21 ++++++++++++++++--- .../org/drools/parser/DRLVisitorImpl.java | 6 ++++++ .../org/drools/parser/MiscDRLParserTest.java | 2 -- .../resources/org/drools/parser/with_eval.drl | 1 + 5 files changed, 26 insertions(+), 5 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 56d0ada08c4..b03d022557c 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -50,6 +50,7 @@ DRL_ACTION : 'action'; DRL_REVERSE : 'reverse'; DRL_RESULT : 'result'; DRL_ENTRY_POINT : 'entry-point'; +DRL_EVAL : 'eval'; DRL_SALIENCE : 'salience'; DRL_ENABLED : 'enabled'; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index d775f02b27f..760c0bec2bb 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -67,8 +67,9 @@ lhsUnary : ( lhsExists namedConsequence? lhsUnary : ( lhsExists | lhsNot - | lhsPatternBind + | lhsEval | lhsAccumulate + | lhsPatternBind ) ; lhsPatternBind : label? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; @@ -139,6 +140,7 @@ drlKeywords : DRL_UNIT | DRL_FUNCTION | DRL_GLOBAL + | DRL_DECLARE | DRL_RULE | DRL_QUERY | DRL_WHEN @@ -151,6 +153,13 @@ drlKeywords | DRL_IN | DRL_FROM | DRL_MATCHES + | DRL_ACCUMULATE + | DRL_INIT + | DRL_ACTION + | DRL_REVERSE + | DRL_RESULT + | DRL_ENTRY_POINT + | DRL_EVAL | DRL_SALIENCE | DRL_ENABLED | DRL_NO_LOOP @@ -182,6 +191,7 @@ drlExpression | explicitGenericInvocation ) | drlExpression LBRACK drlExpression RBRACK + | DRL_EVAL LPAREN conditionalOrExpression RPAREN | methodCall | NEW drlCreator | LPAREN annotation* typeType (BITAND typeType)* RPAREN drlExpression @@ -267,9 +277,9 @@ mapEntry | fromWindow | fromExpression ) */ -patternSource : fromExpression - | fromAccumulate +patternSource : fromAccumulate | fromEntryPoint + | fromExpression ; fromExpression : conditionalOrExpression ; @@ -315,6 +325,11 @@ lhsExists : DRL_EXISTS lhsPatternBind ; */ lhsNot : DRL_NOT lhsPatternBind ; +/** + * lhsEval := EVAL LEFT_PAREN conditionalExpression RIGHT_PAREN + */ +lhsEval : DRL_EVAL LPAREN conditionalOrExpression RPAREN ; + /** * lhsAccumulate := (ACCUMULATE|ACC) LEFT_PAREN lhsAnd (COMMA|SEMICOLON) * accumulateFunctionBinding (COMMA accumulateFunctionBinding)* diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index ff4a0f594ae..28c299438a1 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -16,6 +16,7 @@ import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.EntryPointDescr; +import org.drools.drl.ast.descr.EvalDescr; import org.drools.drl.ast.descr.ExistsDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; import org.drools.drl.ast.descr.FromDescr; @@ -357,6 +358,11 @@ public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { return notDescr; } + @Override + public EvalDescr visitLhsEval(DRLParser.LhsEvalContext ctx) { + return new EvalDescr(getTextPreservingWhitespace(ctx.conditionalOrExpression())); + } + @Override public BaseDescr visitLhsExpressionEnclosed(DRLParser.LhsExpressionEnclosedContext ctx) { return (BaseDescr) visit(ctx.lhsExpression()); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index b678d1ccce5..75f910d3a57 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -1519,7 +1519,6 @@ void parenthesesAndOrOrOrAnd() throws Exception { assertThat(bar3.getObjectType()).isEqualTo("Bar"); } - @Disabled("Priority : High | Implement eval") @Test public void parse_EvalMultiple() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -1537,7 +1536,6 @@ public void parse_EvalMultiple() throws Exception { } - @Disabled("Priority : High | Implement eval") @Test public void parse_WithEval() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_eval.drl b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_eval.drl index b888b36ad8e..37d49e9844c 100644 --- a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_eval.drl +++ b/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_eval.drl @@ -20,4 +20,5 @@ rule simple_rule Bar() eval(abc("foo")) then + Kapow end From 670bd7c303bdedf2651ac67a9eafccea611972f4 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 25 Sep 2023 15:49:09 +0900 Subject: [PATCH 038/141] [DROOLS-7293] Implement extends (#33) --- .../src/main/antlr4/org/drools/parser/DRLParser.g4 | 2 +- .../src/main/java/org/drools/parser/DRLVisitorImpl.java | 4 ++++ .../src/test/java/org/drools/parser/MiscDRLParserTest.java | 1 - 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 760c0bec2bb..aaedc2bf7e9 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -36,7 +36,7 @@ globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; // rule := RULE stringId (EXTENDS stringId)? annotation* attributes? lhs? rhs END -ruledef : DRL_RULE name=stringId (EXTENDS stringId)? drlAnnotation* attributes? lhs rhs DRL_END ; +ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* attributes? lhs rhs DRL_END ; lhs : DRL_WHEN lhsExpression* ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 28c299438a1..cd0ca10007f 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -150,6 +150,10 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { RuleDescr ruleDescr = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); + if (ctx.EXTENDS() != null) { + ruleDescr.setParentName(safeStripStringDelimiters(ctx.parentName.getText())); + } + ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(ruleDescr::addAnnotation); if (ctx.attributes() != null) { diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 75f910d3a57..9b3ebc2744b 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -2783,7 +2783,6 @@ public void parse_RuleMetadata() throws Exception { ); } - @Disabled("Priority : High | Implement extends") @Test public void parse_RuleExtends() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( From 0592423ed8d3dd4baef700934521f492e0d67279 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 29 Sep 2023 15:53:29 +0900 Subject: [PATCH 039/141] [DROOLS-7294] Implement forall (#34) --- .../src/main/antlr4/org/drools/parser/DRLLexer.g4 | 1 + .../src/main/antlr4/org/drools/parser/DRLParser.g4 | 9 ++++++++- .../main/java/org/drools/parser/DRLVisitorImpl.java | 10 +++++++++- .../test/java/org/drools/parser/MiscDRLParserTest.java | 2 -- 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index b03d022557c..0d9a61ca919 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -51,6 +51,7 @@ DRL_REVERSE : 'reverse'; DRL_RESULT : 'result'; DRL_ENTRY_POINT : 'entry-point'; DRL_EVAL : 'eval'; +DRL_FORALL : 'forall'; DRL_SALIENCE : 'salience'; DRL_ENABLED : 'enabled'; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index aaedc2bf7e9..24f4595ce83 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -68,9 +68,10 @@ lhsUnary : ( lhsExists | lhsNot | lhsEval + | lhsForall | lhsAccumulate | lhsPatternBind - ) ; + ) SEMI? ; lhsPatternBind : label? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; @@ -330,6 +331,12 @@ lhsNot : DRL_NOT lhsPatternBind ; */ lhsEval : DRL_EVAL LPAREN conditionalOrExpression RPAREN ; +/** + * lhsForall := FORALL LEFT_PAREN lhsPatternBind+ RIGHT_PAREN + */ + +lhsForall : DRL_FORALL LPAREN lhsPatternBind+ RPAREN ; + /** * lhsAccumulate := (ACCUMULATE|ACC) LEFT_PAREN lhsAnd (COMMA|SEMICOLON) * accumulateFunctionBinding (COMMA accumulateFunctionBinding)* diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index cd0ca10007f..4a82522af1b 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -19,6 +19,7 @@ import org.drools.drl.ast.descr.EvalDescr; import org.drools.drl.ast.descr.ExistsDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.ForallDescr; import org.drools.drl.ast.descr.FromDescr; import org.drools.drl.ast.descr.FunctionDescr; import org.drools.drl.ast.descr.FunctionImportDescr; @@ -262,6 +263,13 @@ public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { return patternDescr; } + @Override + public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { + ForallDescr forallDescr = new ForallDescr(); + visitDescrChildren(ctx).forEach(forallDescr::addDescr); + return forallDescr; + } + @Override public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { AccumulateDescr accumulateDescr = new AccumulateDescr(); @@ -398,7 +406,7 @@ public BaseDescr visitLhsAndForAccumulate(DRLParser.LhsAndForAccumulateContext c @Override public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { - return (BaseDescr) visitChildren(ctx); + return visitDescrChildren(ctx).get(0); } private void populateStartEnd(BaseDescr descr, ParserRuleContext ctx) { diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 9b3ebc2744b..2528dacb5ee 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -2126,7 +2126,6 @@ public void parse_NestedCEs() throws Exception { assertThat("Cheese").isEqualTo(cheese3.getObjectType()); } - @Disabled("Priority : High | Implement forall") @Test public void parse_Forall() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2147,7 +2146,6 @@ public void parse_Forall() throws Exception { assertThat(cheese.getObjectType()).isEqualTo("Cheese"); } - @Disabled("Priority : High | Implement forall") @Test public void parse_ForallWithFrom() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( From 225f4aa472b834e5e3c706d7af84800a54ae5566 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 3 Oct 2023 18:42:33 +0900 Subject: [PATCH 040/141] [DROOLS-7298] Implement memberOf (#35) --- .../src/main/antlr4/org/drools/parser/DRLLexer.g4 | 1 + .../src/main/antlr4/org/drools/parser/DRLParser.g4 | 2 ++ .../src/test/java/org/drools/parser/MiscDRLParserTest.java | 2 -- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 0d9a61ca919..0add536a0ba 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -44,6 +44,7 @@ DRL_NOT : 'not'; DRL_IN : 'in'; DRL_FROM : 'from'; DRL_MATCHES : 'matches'; +DRL_MEMBEROF : 'memberOf'; DRL_ACCUMULATE : 'accumulate' | 'acc'; DRL_INIT : 'init'; DRL_ACTION : 'action'; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 24f4595ce83..76651552ac2 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -154,6 +154,7 @@ drlKeywords | DRL_IN | DRL_FROM | DRL_MATCHES + | DRL_MEMBEROF | DRL_ACCUMULATE | DRL_INIT | DRL_ACTION @@ -205,6 +206,7 @@ drlExpression | drlExpression bop=(LE | GE | GT | LT) drlExpression | drlExpression bop=INSTANCEOF (typeType | pattern) | drlExpression bop=DRL_MATCHES drlExpression + | drlExpression DRL_NOT? DRL_MEMBEROF drlExpression | drlExpression bop=(EQUAL | NOTEQUAL) drlExpression | drlExpression bop=BITAND drlExpression | drlExpression bop=CARET drlExpression diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 2528dacb5ee..9a92386c5a0 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -2168,7 +2168,6 @@ public void parse_ForallWithFrom() throws Exception { assertThat(((FromDescr) cheese.getSource()).getDataSource().toString()).isEqualTo("$cheesery"); } - @Disabled("Priority : High | Implement memberOf") @Test public void parse_Memberof() throws Exception { final String text = "rule X when Country( $cities : city )\nPerson( city memberOf $cities )\n then end"; @@ -2182,7 +2181,6 @@ public void parse_Memberof() throws Exception { assertThat(fieldConstr.getExpression()).isEqualTo("city memberOf $cities"); } - @Disabled("Priority : High | Implement not memberOf") @Test public void parse_NotMemberof() throws Exception { final String text = "rule X when Country( $cities : city )\nPerson( city not memberOf $cities ) then end\n"; From 1d048efda0db130e2cf35818977eb42ad73128cb Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 3 Oct 2023 18:42:46 +0900 Subject: [PATCH 041/141] [DROOLS-7300] Implement positional constraint (#36) --- .../org/drools/parser/DRLVisitorImpl.java | 37 +++++++++++++++---- .../org/drools/parser/MiscDRLParserTest.java | 3 -- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 4a82522af1b..078ec4a8698 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.TokenStream; @@ -258,11 +257,16 @@ public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { patternSourceDescr.setResource(patternDescr.getResource()); patternDescr.setSource(patternSourceDescr); } - List constraintDescrList = visitConstraints(ctx.constraints()); - constraintDescrList.forEach(patternDescr::addConstraint); + List constraintDescrList = visitConstraints(ctx.positionalConstraints(), ctx.constraints()); + constraintDescrList.forEach(descr -> addToPatternDescr(patternDescr, descr)); return patternDescr; } + private void addToPatternDescr(PatternDescr patternDescr, ExprConstraintDescr exprConstraintDescr) { + exprConstraintDescr.setResource(patternDescr.getResource()); + patternDescr.addConstraint(exprConstraintDescr); + } + @Override public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { ForallDescr forallDescr = new ForallDescr(); @@ -328,14 +332,31 @@ public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) @Override public List visitConstraints(DRLParser.ConstraintsContext ctx) { + List exprConstraintDescrList = new ArrayList<>(); + populateExprConstraintDescrList(ctx, exprConstraintDescrList); + return exprConstraintDescrList; + } + + private List visitConstraints(DRLParser.PositionalConstraintsContext positionalCtx, DRLParser.ConstraintsContext ctx) { + List exprConstraintDescrList = new ArrayList<>(); + populateExprConstraintDescrList(positionalCtx, exprConstraintDescrList); + populateExprConstraintDescrList(ctx, exprConstraintDescrList); + return exprConstraintDescrList; + } + + private void populateExprConstraintDescrList(ParserRuleContext ctx, List exprConstraintDescrList) { if (ctx == null) { - return new ArrayList<>(); + return; } List descrList = visitDescrChildren(ctx); - return descrList.stream() - .filter(ExprConstraintDescr.class::isInstance) - .map(ExprConstraintDescr.class::cast) - .collect(Collectors.toList()); + for (BaseDescr descr : descrList) { + if (descr instanceof ExprConstraintDescr) { + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) descr; + exprConstraintDescr.setType(ctx instanceof DRLParser.PositionalConstraintsContext ? ExprConstraintDescr.Type.POSITIONAL : ExprConstraintDescr.Type.NAMED); + exprConstraintDescr.setPosition(exprConstraintDescrList.size()); + exprConstraintDescrList.add(exprConstraintDescr); + } + } } @Override diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 9a92386c5a0..d38ed5bf77b 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -3015,7 +3015,6 @@ public void parse_TypeWithMetaData() throws Exception { assertThat(declarations.size()).isEqualTo(3); } - @Disabled("Priority : Mid | Implement Descr position") @Test public void parse_NullConstraints() throws Exception { final String text = "rule X when Person( name == null ) then end"; @@ -3029,7 +3028,6 @@ public void parse_NullConstraints() throws Exception { assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); } - @Disabled("Priority : High | Implement positional constraint") @Test public void parse_PositionalConstraintsOnly() throws Exception { final String text = "rule X when Person( \"Mark\", 42; ) then end"; @@ -3126,7 +3124,6 @@ public void parse_MultiValueAnnotationsBackwardCompatibility() throws Exception assertThat(ann.getValue()).isEqualTo("\"val1\", \"val2\""); } - @Disabled("Priority : High | Implement positional constraint") @Test public void parse_PositionalsAndNamedConstraints() throws Exception { final String text = "rule X when Person( \"Mark\", 42; location == \"atlanta\" ) then end"; From 5675d0f0640f3774d752f8f335c430d601f3e39e Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 13 Oct 2023 17:34:40 +0900 Subject: [PATCH 042/141] [DROOLS-7304] Implement temporal operators (#38) - Also covers [DROOLS-7303] Implement sliding window --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 20 ++++++++++++++++++- .../antlr4/org/drools/parser/DRLParser.g4 | 14 ++++++++++++- .../org/drools/parser/DRLVisitorImpl.java | 18 ++++++++++++++++- .../org/drools/parser/MiscDRLParserTest.java | 7 +------ 4 files changed, 50 insertions(+), 9 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 0add536a0ba..d200e7c6e80 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -53,7 +53,25 @@ DRL_RESULT : 'result'; DRL_ENTRY_POINT : 'entry-point'; DRL_EVAL : 'eval'; DRL_FORALL : 'forall'; - +DRL_OVER : 'over'; + +// temporal operators +DRL_AFTER : 'after'; +DRL_BEFORE : 'before'; +DRL_COINCIDES : 'coincides'; +DRL_DURING : 'during'; +DRL_INCLUDES : 'includes'; +DRL_FINISHES : 'finishes'; +DRL_FINISHED_BY : 'finishedby'; +DRL_MEETS : 'meets'; +DRL_MET_BY : 'metby'; +DRL_OVERLAPS : 'overlaps'; +DRL_OVERLAPPED_BY : 'overlappedby'; +DRL_STARTS : 'starts'; +DRL_STARTED_BY : 'startedby'; + + +// attributes DRL_SALIENCE : 'salience'; DRL_ENABLED : 'enabled'; DRL_NO_LOOP : 'no-loop'; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 76651552ac2..e531c3d91c8 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -80,7 +80,7 @@ lhsPattern : xpathPrimary (OVER patternFilter)? | ( QUESTION? qualifiedIdentifier LPAREN positionalConstraints? constraints? RPAREN (OVER patternFilter)? (FROM patternSource)? ) ; */ -lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN (DRL_FROM patternSource)? ; +lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN (DRL_OVER patternFilter)? (DRL_FROM patternSource)? ; positionalConstraints : constraint (COMMA constraint)* SEMI ; constraints : constraint (COMMA constraint)* ; constraint : ( nestedConstraint | conditionalOrExpression ) ; @@ -105,6 +105,7 @@ relationalOperator | GE | GT | LT + | temporalOperator ; /* function := FUNCTION type? ID parameters(typed) chunk_{_} */ @@ -204,6 +205,7 @@ drlExpression | drlExpression bop=(ADD|SUB) drlExpression | drlExpression (LT LT | GT GT GT | GT GT) drlExpression | drlExpression bop=(LE | GE | GT | LT) drlExpression + | drlExpression temporalOperator drlExpression | drlExpression bop=INSTANCEOF (typeType | pattern) | drlExpression bop=DRL_MATCHES drlExpression | drlExpression DRL_NOT? DRL_MEMBEROF drlExpression @@ -226,6 +228,10 @@ drlExpression | classType COLONCOLON typeArguments? NEW ; +temporalOperator : DRL_NOT? bop=(DRL_AFTER | DRL_BEFORE | DRL_COINCIDES | DRL_DURING | DRL_INCLUDES | DRL_FINISHES | DRL_FINISHED_BY | DRL_MEETS | DRL_MET_BY | DRL_OVERLAPS | DRL_OVERLAPPED_BY | DRL_STARTS | DRL_STARTED_BY) timeAmount? ; + +timeAmount : LBRACK (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL) (COMMA (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL))* RBRACK ; + /* extending JavaParser primary */ drlPrimary : LPAREN drlExpression RPAREN @@ -272,6 +278,12 @@ mapEntry : drlExpression COLON drlExpression ; +/* + patternFilter := OVER filterDef + filterDef := label ID LEFT_PAREN parameters RIGHT_PAREN +*/ +patternFilter : label IDENTIFIER LPAREN expressionList RPAREN ; + /* patternSource := FROM ( fromAccumulate diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 078ec4a8698..596e31c7e47 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.TokenStream; @@ -14,6 +15,7 @@ import org.drools.drl.ast.descr.AnnotationDescr; import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.BehaviorDescr; import org.drools.drl.ast.descr.EntryPointDescr; import org.drools.drl.ast.descr.EvalDescr; import org.drools.drl.ast.descr.ExistsDescr; @@ -42,7 +44,7 @@ public class DRLVisitorImpl extends DRLParserBaseVisitor { - private TokenStream tokenStream; + private final TokenStream tokenStream; public DRLVisitorImpl(TokenStream tokenStream) { this.tokenStream = tokenStream; @@ -252,6 +254,9 @@ private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindConte @Override public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { PatternDescr patternDescr = new PatternDescr(ctx.objectType.getText()); + if (ctx.patternFilter() != null) { + patternDescr.addBehavior(visitPatternFilter(ctx.patternFilter())); + } if (ctx.patternSource() != null) { PatternSourceDescr patternSourceDescr = (PatternSourceDescr) visitPatternSource(ctx.patternSource()); patternSourceDescr.setResource(patternDescr.getResource()); @@ -291,6 +296,17 @@ public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { return patternDescr; } + @Override + public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { + BehaviorDescr behaviorDescr = new BehaviorDescr(); + behaviorDescr.setType(ctx.label().IDENTIFIER().getText()); + behaviorDescr.setSubType(ctx.IDENTIFIER().getText()); + List drlExpressionContexts = ctx.expressionList().drlExpression(); + List parameters = drlExpressionContexts.stream().map(ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); + behaviorDescr.setParameters(parameters); + return behaviorDescr; + } + @Override public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { FromDescr fromDescr = new FromDescr(); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index d38ed5bf77b..ca78882b598 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -2713,7 +2713,6 @@ public void parse_AccumulateMultiPattern() throws Exception { assertThat(cheese.getObjectType()).isEqualTo("Cheese"); } - @Disabled("Priority : High | Implement temporal operators") @Test public void parse_PluggableOperators() throws Exception { @@ -2934,13 +2933,11 @@ public void parse_EntryPoint2() throws Exception { assertThat(entry.getEntryId()).isEqualTo("StreamA"); } - @Disabled("Priority : High | Implement sliding window") @Test public void parse_SlidingWindow() throws Exception { final String text = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end"; - PackageDescr pkg = parser.parse( - text ); + PackageDescr pkg = parser.parse( text ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = pkg.getRules().get( 0 ); @@ -3219,7 +3216,6 @@ public void parse_BindingCompositeWithMethods() throws Exception { assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\""); } - @Disabled("Priority : High | Implement temporal operators") @Test public void parse_PluggableOperators2() throws Exception { final String text = "rule \"tt\"\n" + @@ -3253,7 +3249,6 @@ public void parse_InlineEval() throws Exception { } - @Disabled("Priority : High | Implement temporal operators") @Test public void parse_InfinityLiteral() throws Exception { final String text = "rule \"infinity\"\n" + From 2b8866ecfe96bde45496140e68721a53b5714562 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 13 Oct 2023 18:25:21 +0900 Subject: [PATCH 043/141] [DROOLS-7301] Implement query (#37) - Also partially fixes [DROOLS-7302] Implement semicolon delimiter --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 3 +- .../antlr4/org/drools/parser/DRLParser.g4 | 11 +++++-- .../org/drools/parser/DRLVisitorImpl.java | 32 +++++++++++++++++++ .../org/drools/parser/MiscDRLParserTest.java | 8 +---- 4 files changed, 43 insertions(+), 11 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index d200e7c6e80..2bb35093aab 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -35,6 +35,7 @@ DRL_RULE : 'rule'; DRL_QUERY : 'query'; DRL_WHEN : 'when'; DRL_THEN : 'then' -> pushMode(RHS); +DRL_QUERY_END : 'end'; DRL_AND : 'and'; DRL_OR : 'or'; @@ -153,5 +154,5 @@ DrlUnicodeEscape mode RHS; RHS_WS : [ \t\r\n\u000C]+ -> channel(HIDDEN); -DRL_END : 'end' [ \t]* ('\n' | '\r\n' | EOF) {setText("end");} -> popMode; +DRL_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) {setText("end");} -> popMode; RHS_CHUNK : ~[ \t\r\n\u000C]+ ; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index e531c3d91c8..d418d82da95 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -19,9 +19,10 @@ compilationUnit : packagedef? unitdef? drlStatementdef* ; drlStatementdef : importdef | globaldef - | functiondef - | attributes | ruledef + | attributes + | functiondef + | querydef ; packagedef : PACKAGE name=drlQualifiedName SEMI? ; @@ -38,6 +39,10 @@ globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* attributes? lhs rhs DRL_END ; +// query := QUERY stringId parameters? annotation* lhsExpression END + +querydef : DRL_QUERY name=stringId formalParameters? drlAnnotation* lhsExpression+ DRL_QUERY_END SEMI?; + lhs : DRL_WHEN lhsExpression* ; lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed @@ -147,7 +152,7 @@ drlKeywords | DRL_QUERY | DRL_WHEN | DRL_THEN - | DRL_END + | DRL_QUERY_END | DRL_AND | DRL_OR | DRL_EXISTS diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 596e31c7e47..1d33e459754 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -32,6 +32,7 @@ import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.ast.descr.PatternDescr; import org.drools.drl.ast.descr.PatternSourceDescr; +import org.drools.drl.ast.descr.QueryDescr; import org.drools.drl.ast.descr.RuleDescr; import org.drools.drl.ast.descr.UnitDescr; @@ -85,6 +86,8 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc packageDescr.addAttribute((AttributeDescr) descr); } else if (descr instanceof RuleDescr) { packageDescr.addRule((RuleDescr) descr); + } else if (descr instanceof QueryDescr) { + packageDescr.addRule((QueryDescr) descr); } }); } @@ -186,6 +189,32 @@ private void slimLhsRootDescr(AndDescr root) { descrList.forEach(root::addOrMerge); // This slims down nested AndDescr } + @Override + public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { + QueryDescr queryDescr = new QueryDescr(safeStripStringDelimiters(ctx.name.getText())); + + DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); + if (formalParametersContext != null) { + DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); + List formalParameterContexts = formalParameterListContext.formalParameter(); + formalParameterContexts.forEach(formalParameterContext -> { + DRLParser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); + DRLParser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); + queryDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); + }); + } + + ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(queryDescr::addAnnotation); + + ctx.lhsExpression().stream() + .flatMap(lhsExpressionContext -> visitDescrChildren(lhsExpressionContext).stream()) + .forEach(descr -> queryDescr.getLhs().addDescr(descr)); + + slimLhsRootDescr(queryDescr.getLhs()); + + return queryDescr; + } + @Override public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); @@ -254,6 +283,9 @@ private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindConte @Override public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { PatternDescr patternDescr = new PatternDescr(ctx.objectType.getText()); + if (ctx.QUESTION() != null) { + patternDescr.setQuery(true); + } if (ctx.patternFilter() != null) { patternDescr.addBehavior(visitPatternFilter(ctx.patternFilter())); } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index ca78882b598..c25bb3274f6 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -913,7 +913,6 @@ public void parse_LineNumberIncludingCommentsInRHS() throws Exception { Pattern.DOTALL | Pattern.MULTILINE).matcher(rhs).matches()).isTrue(); } - @Disabled("Priority : High | Implement semicolon delimiter") @Test public void parse_LhsSemicolonDelim() throws Exception { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( @@ -1017,7 +1016,6 @@ public void parse_NotExistWithBrackets() throws Exception { assertThat(exPattern.getObjectType()).isEqualTo("Foo"); } - @Disabled("Priority : High | Implement query") @Test public void parse_SimpleQuery() throws Exception { final QueryDescr query = parseAndGetFirstQueryDescrFromFile( @@ -1057,7 +1055,6 @@ public void parse_SimpleQuery() throws Exception { assertThat(bindingDescr.getExpression()).isEqualTo("a4:a==4"); } - @Disabled("Priority : High | Implement query") @Test public void parse_QueryRuleMixed() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2313,7 +2310,7 @@ public void parse_Restrictions() throws Exception { assertThat(fieldConstr.getExpression()).isEqualTo("bar > 1 || == 1"); } - @Disabled("Priority : High | Implement semicolon delimiter") + @Disabled("Priority : High | Implement semicolon delimiter | Implement from collect") @Test public void parse_Semicolon() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -3042,7 +3039,6 @@ public void parse_PositionalConstraintsOnly() throws Exception { assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); } - @Disabled("Priority : High | Implement query") @Test public void parse_IsQuery() throws Exception { final String text = "rule X when ?person( \"Mark\", 42; ) then end"; @@ -3062,7 +3058,6 @@ public void parse_IsQuery() throws Exception { assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); } - @Disabled("Priority : Mid | Implement query with from") @Test public void parse_FromFollowedByQuery() throws Exception { // the 'from' expression requires a ";" to disambiguate the "?" @@ -3083,7 +3078,6 @@ public void parse_FromFollowedByQuery() throws Exception { } - @Disabled("Priority : Mid | Implement query with from") @Test public void parse_FromWithTernaryFollowedByQuery() throws Exception { // the 'from' expression requires a ";" to disambiguate the "?" From a8502d28fc1f915afde2f69fa3cbc8bed2383352 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 18 Oct 2023 15:42:50 +0900 Subject: [PATCH 044/141] [DROOLS-7295] Implement from collect (#39) --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 1 + .../main/antlr4/org/drools/parser/DRLParser.g4 | 17 +++++++++++------ .../java/org/drools/parser/DRLVisitorImpl.java | 14 +++++++++++--- .../org/drools/parser/MiscDRLParserTest.java | 4 ---- 4 files changed, 23 insertions(+), 13 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 2bb35093aab..35bfe12f992 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -44,6 +44,7 @@ DRL_EXISTS : 'exists'; DRL_NOT : 'not'; DRL_IN : 'in'; DRL_FROM : 'from'; +DRL_COLLECT : 'collect'; DRL_MATCHES : 'matches'; DRL_MEMBEROF : 'memberOf'; DRL_ACCUMULATE : 'accumulate' | 'acc'; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index d418d82da95..6069196f7c7 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -53,10 +53,10 @@ lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed | lhsExpression (DRL_OR lhsExpression)+ #lhsOr ; -// and is accepted for accumulate -lhsAndForAccumulate : lhsUnary (DRL_AND lhsUnary)* - | LPAREN DRL_AND lhsUnary+ RPAREN - ; +// lhsAnd is used as a label in lhsExpression rule. But some other rules also use it. +lhsAndDef : lhsUnary (DRL_AND lhsUnary)* + | LPAREN DRL_AND lhsUnary+ RPAREN + ; /* lhsUnary : ( lhsExists namedConsequence? @@ -298,6 +298,7 @@ patternFilter : label IDENTIFIER LPAREN expressionList RPAREN ; | fromExpression ) */ patternSource : fromAccumulate + | fromCollect | fromEntryPoint | fromExpression ; @@ -312,7 +313,7 @@ fromAccumulate := ACCUMULATE LEFT_PAREN lhsAnd (COMMA|SEMICOLON) | accumulateFunction ) RIGHT_PAREN */ -fromAccumulate : DRL_ACCUMULATE LPAREN lhsAndForAccumulate (COMMA|SEMI) +fromAccumulate : DRL_ACCUMULATE LPAREN lhsAndDef (COMMA|SEMI) ( DRL_INIT LPAREN initBlockStatements=blockStatements RPAREN COMMA DRL_ACTION LPAREN actionBlockStatements=blockStatements RPAREN COMMA ( DRL_REVERSE LPAREN reverseBlockStatements=blockStatements RPAREN COMMA)? DRL_RESULT LPAREN expression RPAREN | accumulateFunction ) @@ -326,6 +327,10 @@ accumulateFunction := label? ID parameters */ accumulateFunction : label? IDENTIFIER LPAREN drlExpression RPAREN; +// fromCollect := COLLECT LEFT_PAREN lhsPatternBind RIGHT_PAREN + +fromCollect : DRL_COLLECT LPAREN lhsPatternBind RPAREN ; + fromEntryPoint : DRL_ENTRY_POINT stringId ; /* @@ -363,7 +368,7 @@ lhsForall : DRL_FORALL LPAREN lhsPatternBind+ RPAREN ; * RIGHT_PAREN SEMICOLON? */ -lhsAccumulate : DRL_ACCUMULATE LPAREN lhsAndForAccumulate (COMMA|SEMI) +lhsAccumulate : DRL_ACCUMULATE LPAREN lhsAndDef (COMMA|SEMI) accumulateFunction (COMMA accumulateFunction)* (SEMI constraints)? RPAREN (SEMI)? diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 1d33e459754..783be414b49 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -16,6 +16,7 @@ import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.BehaviorDescr; +import org.drools.drl.ast.descr.CollectDescr; import org.drools.drl.ast.descr.EntryPointDescr; import org.drools.drl.ast.descr.EvalDescr; import org.drools.drl.ast.descr.ExistsDescr; @@ -314,7 +315,7 @@ public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { @Override public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { AccumulateDescr accumulateDescr = new AccumulateDescr(); - accumulateDescr.setInput(visitLhsAndForAccumulate(ctx.lhsAndForAccumulate())); + accumulateDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); // accumulate function for (DRLParser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { @@ -346,10 +347,17 @@ public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { return fromDescr; } + @Override + public CollectDescr visitFromCollect(DRLParser.FromCollectContext ctx) { + CollectDescr collectDescr = new CollectDescr(); + collectDescr.setInputPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); + return collectDescr; + } + @Override public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) { AccumulateDescr accumulateDescr = new AccumulateDescr(); - accumulateDescr.setInput(visitLhsAndForAccumulate(ctx.lhsAndForAccumulate())); + accumulateDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); if (ctx.DRL_INIT() != null) { // inline custom accumulate accumulateDescr.setInitCode(getTextPreservingWhitespace(ctx.initBlockStatements)); @@ -469,7 +477,7 @@ private AndDescr createAndDescr(List descrList) { } @Override - public BaseDescr visitLhsAndForAccumulate(DRLParser.LhsAndForAccumulateContext ctx) { + public BaseDescr visitLhsAndDef(DRLParser.LhsAndDefContext ctx) { return createAndDescr(visitDescrChildren(ctx)); } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index c25bb3274f6..93a98ed9eb1 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -2047,7 +2047,6 @@ public void parse_AccumulateWithBindings() throws Exception { assertThat(pattern.getObjectType()).isEqualTo("Person"); } - @Disabled("Priority : High | Implement from collect") @Test public void parse_Collect() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2310,7 +2309,6 @@ public void parse_Restrictions() throws Exception { assertThat(fieldConstr.getExpression()).isEqualTo("bar > 1 || == 1"); } - @Disabled("Priority : High | Implement semicolon delimiter | Implement from collect") @Test public void parse_Semicolon() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2390,7 +2388,6 @@ public void parse_AccumulateExternalFunction() throws Exception { assertThat(pattern.getObjectType()).isEqualTo("Person"); } - @Disabled("Priority : High | Implement from collect") @Test public void parse_CollectWithNestedFrom() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2412,7 +2409,6 @@ public void parse_CollectWithNestedFrom() throws Exception { assertThat(people.getObjectType()).isEqualTo("People"); } - @Disabled("Priority : High | Implement accumulate and Implement from collect") @Test public void parse_AccumulateWithNestedFrom() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( From eb8f26468f89e260b20dc813cc06fda488060f04 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 18 Oct 2023 23:04:31 +0900 Subject: [PATCH 045/141] [DROOLS-7305] Implement type declaration (#40) - also covers [DROOLS-7291] Implement entry-point declaration - also covers window declaration --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 8 +- .../antlr4/org/drools/parser/DRLParser.g4 | 67 ++++++++++++--- .../org/drools/parser/DRLVisitorImpl.java | 81 ++++++++++++++++++- .../org/drools/parser/MiscDRLParserTest.java | 4 - 4 files changed, 141 insertions(+), 19 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index 35bfe12f992..cce083ab8a2 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -35,7 +35,7 @@ DRL_RULE : 'rule'; DRL_QUERY : 'query'; DRL_WHEN : 'when'; DRL_THEN : 'then' -> pushMode(RHS); -DRL_QUERY_END : 'end'; +DRL_END : 'end'; DRL_AND : 'and'; DRL_OR : 'or'; @@ -47,7 +47,8 @@ DRL_FROM : 'from'; DRL_COLLECT : 'collect'; DRL_MATCHES : 'matches'; DRL_MEMBEROF : 'memberOf'; -DRL_ACCUMULATE : 'accumulate' | 'acc'; +DRL_ACCUMULATE : 'accumulate'; +DRL_ACC : 'acc'; DRL_INIT : 'init'; DRL_ACTION : 'action'; DRL_REVERSE : 'reverse'; @@ -72,6 +73,7 @@ DRL_OVERLAPPED_BY : 'overlappedby'; DRL_STARTS : 'starts'; DRL_STARTED_BY : 'startedby'; +DRL_WINDOW : 'window'; // attributes DRL_SALIENCE : 'salience'; @@ -155,5 +157,5 @@ DrlUnicodeEscape mode RHS; RHS_WS : [ \t\r\n\u000C]+ -> channel(HIDDEN); -DRL_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) {setText("end");} -> popMode; +DRL_RHS_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) {setText("end");} -> popMode; RHS_CHUNK : ~[ \t\r\n\u000C]+ ; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 6069196f7c7..30ba8454cc5 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -19,6 +19,7 @@ compilationUnit : packagedef? unitdef? drlStatementdef* ; drlStatementdef : importdef | globaldef + | declaredef | ruledef | attributes | functiondef @@ -29,19 +30,56 @@ packagedef : PACKAGE name=drlQualifiedName SEMI? ; unitdef : DRL_UNIT name=drlQualifiedName SEMI? ; -importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? SEMI? #importStandardDef - | IMPORT DRL_ACCUMULATE drlQualifiedName IDENTIFIER SEMI? #importAccumulateDef +importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? SEMI? #importStandardDef + | IMPORT (DRL_ACCUMULATE|DRL_ACC) drlQualifiedName IDENTIFIER SEMI? #importAccumulateDef ; globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; +/** + * declare := DECLARE + * | (ENTRY-POINT) => entryPointDeclaration + * | (WINDOW) => windowDeclaration + * | (TRAIT) => typeDeclaration (trait) + * | (ENUM) => enumDeclaration + * | typeDeclaration (class) + * END + */ + +declaredef : DRL_DECLARE ( + | entryPointDeclaration + | windowDeclaration + | typeDeclaration + ) DRL_END ; + +/* + * typeDeclaration := [TYPE] qualifiedIdentifier (EXTENDS qualifiedIdentifier)? + * annotation* + * field* + * END + */ + +typeDeclaration : name=drlQualifiedName (EXTENDS superType=drlQualifiedName)? drlAnnotation* field* ; + +// entryPointDeclaration := ENTRY-POINT stringId annotation* END + +entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* ; + +// windowDeclaration := WINDOW ID annotation* lhsPatternBind END + +windowDeclaration : DRL_WINDOW name=stringId drlAnnotation* lhsPatternBind ; + +// field := label fieldType (EQUALS_ASSIGN conditionalExpression)? annotation* SEMICOLON? + +field : label type (ASSIGN initExpr=conditionalOrExpression)? drlAnnotation* SEMI? ; + // rule := RULE stringId (EXTENDS stringId)? annotation* attributes? lhs? rhs END -ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* attributes? lhs rhs DRL_END ; +ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* attributes? lhs rhs DRL_RHS_END ; // query := QUERY stringId parameters? annotation* lhsExpression END -querydef : DRL_QUERY name=stringId formalParameters? drlAnnotation* lhsExpression+ DRL_QUERY_END SEMI?; +querydef : DRL_QUERY name=stringId formalParameters? drlAnnotation* lhsExpression+ DRL_END SEMI?; lhs : DRL_WHEN lhsExpression* ; @@ -152,7 +190,7 @@ drlKeywords | DRL_QUERY | DRL_WHEN | DRL_THEN - | DRL_QUERY_END + | DRL_END | DRL_AND | DRL_OR | DRL_EXISTS @@ -162,6 +200,7 @@ drlKeywords | DRL_MATCHES | DRL_MEMBEROF | DRL_ACCUMULATE + | DRL_ACC | DRL_INIT | DRL_ACTION | DRL_REVERSE @@ -287,7 +326,7 @@ mapEntry patternFilter := OVER filterDef filterDef := label ID LEFT_PAREN parameters RIGHT_PAREN */ -patternFilter : label IDENTIFIER LPAREN expressionList RPAREN ; +patternFilter : DRL_WINDOW COLON IDENTIFIER LPAREN expressionList RPAREN ; /* patternSource := FROM @@ -313,7 +352,7 @@ fromAccumulate := ACCUMULATE LEFT_PAREN lhsAnd (COMMA|SEMICOLON) | accumulateFunction ) RIGHT_PAREN */ -fromAccumulate : DRL_ACCUMULATE LPAREN lhsAndDef (COMMA|SEMI) +fromAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) ( DRL_INIT LPAREN initBlockStatements=blockStatements RPAREN COMMA DRL_ACTION LPAREN actionBlockStatements=blockStatements RPAREN COMMA ( DRL_REVERSE LPAREN reverseBlockStatements=blockStatements RPAREN COMMA)? DRL_RESULT LPAREN expression RPAREN | accumulateFunction ) @@ -368,7 +407,7 @@ lhsForall : DRL_FORALL LPAREN lhsPatternBind+ RPAREN ; * RIGHT_PAREN SEMICOLON? */ -lhsAccumulate : DRL_ACCUMULATE LPAREN lhsAndDef (COMMA|SEMI) +lhsAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) accumulateFunction (COMMA accumulateFunction)* (SEMI constraints)? RPAREN (SEMI)? @@ -380,7 +419,7 @@ consequence : RHS_CHUNK* ; stringId : ( IDENTIFIER | DRL_STRING_LITERAL ) ; -type : IDENTIFIER typeArguments? ( DOT IDENTIFIER typeArguments? )* (LBRACK RBRACK)* ; +type : (classOrInterfaceType | primitiveType) typeArguments? ( DOT IDENTIFIER typeArguments? )* (LBRACK RBRACK)* ; //typeArguments : LT typeArgument (COMMA typeArgument)* GT ; //typeArgument : QUESTION (( EXTENDS | SUPER ) type )? | type ; @@ -388,7 +427,15 @@ type : IDENTIFIER typeArguments? ( DOT IDENTIFIER typeArguments? )* (LBRACK RBRA drlArguments : LPAREN drlArgument (COMMA drlArgument)* RPAREN ; drlArgument : ( stringId | floatLiteral | BOOL_LITERAL | NULL_LITERAL ) ; -drlAnnotation : AT name=drlQualifiedName drlArguments? ; +drlAnnotation : AT name=drlQualifiedName (LPAREN ( drlElementValuePairs | drlElementValue )? RPAREN)? ; + +drlElementValuePairs : drlElementValuePair (COMMA drlElementValuePair)* ; +drlElementValuePair : key=drlIdentifier ASSIGN value=drlElementValue ; + +drlElementValue + : drlExpression + | drlArrayInitializer + ; attributes : attribute ( COMMA? attribute )* ; attribute : ( 'salience' DECIMAL_LITERAL ) diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 783be414b49..2a09cafd78e 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -17,6 +17,7 @@ import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.BehaviorDescr; import org.drools.drl.ast.descr.CollectDescr; +import org.drools.drl.ast.descr.EntryPointDeclarationDescr; import org.drools.drl.ast.descr.EntryPointDescr; import org.drools.drl.ast.descr.EvalDescr; import org.drools.drl.ast.descr.ExistsDescr; @@ -35,7 +36,10 @@ import org.drools.drl.ast.descr.PatternSourceDescr; import org.drools.drl.ast.descr.QueryDescr; import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.TypeDeclarationDescr; +import org.drools.drl.ast.descr.TypeFieldDescr; import org.drools.drl.ast.descr.UnitDescr; +import org.drools.drl.ast.descr.WindowDeclarationDescr; import static org.drools.parser.DRLParserHelper.getTextWithoutErrorNode; import static org.drools.parser.ParserStringUtils.getTextPreservingWhitespace; @@ -83,6 +87,12 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc functionDescr.setDialect(dialect.getValue()); } packageDescr.addFunction(functionDescr); + } else if (descr instanceof TypeDeclarationDescr) { + packageDescr.addTypeDeclaration((TypeDeclarationDescr) descr); + } else if (descr instanceof EntryPointDeclarationDescr) { + packageDescr.addEntryPointDeclaration((EntryPointDeclarationDescr) descr); + } else if (descr instanceof WindowDeclarationDescr) { + packageDescr.addWindowDeclaration((WindowDeclarationDescr) descr); } else if (descr instanceof AttributeDescr) { packageDescr.addAttribute((AttributeDescr) descr); } else if (descr instanceof RuleDescr) { @@ -152,6 +162,47 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { return functionDescr; } + @Override + public BaseDescr visitDeclaredef(DRLParser.DeclaredefContext ctx) { + return visitDescrChildren(ctx).get(0); + } + + @Override + public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContext ctx) { + TypeDeclarationDescr typeDeclarationDescr = new TypeDeclarationDescr(ctx.name.getText()); + if (ctx.EXTENDS() != null) { + typeDeclarationDescr.addSuperType(ctx.superType.getText()); + } + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(typeDeclarationDescr::addAnnotation); + ctx.field().stream() + .map(this::visitField) + .forEach(typeDeclarationDescr::addField); + return typeDeclarationDescr; + } + + @Override + public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPointDeclarationContext ctx) { + EntryPointDeclarationDescr entryPointDeclarationDescr = new EntryPointDeclarationDescr(); + entryPointDeclarationDescr.setEntryPointId(ctx.name.getText()); + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(entryPointDeclarationDescr::addAnnotation); + return entryPointDeclarationDescr; + } + + @Override + public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclarationContext ctx) { + WindowDeclarationDescr windowDeclarationDescr = new WindowDeclarationDescr(); + windowDeclarationDescr.setName(ctx.name.getText()); + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(windowDeclarationDescr::addAnnotation); + windowDeclarationDescr.setPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); + return windowDeclarationDescr; + } + @Override public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { RuleDescr ruleDescr = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); @@ -219,10 +270,36 @@ public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { @Override public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); - annotationDescr.setValue(ctx.drlArguments().drlArgument(0).getText()); + if (ctx.drlElementValue() != null) { + annotationDescr.setValue(getTextPreservingWhitespace(ctx.drlElementValue())); // single value + } else if (ctx.drlElementValuePairs() != null) { + visitDrlElementValuePairs(ctx.drlElementValuePairs(), annotationDescr); // multiple values + } return annotationDescr; } + @Override + public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { + TypeFieldDescr typeFieldDescr = new TypeFieldDescr(); + typeFieldDescr.setFieldName(ctx.label().IDENTIFIER().getText()); + typeFieldDescr.setPattern(new PatternDescr(ctx.type().getText())); + if (ctx.ASSIGN() != null) { + typeFieldDescr.setInitExpr(getTextPreservingWhitespace(ctx.initExpr)); + } + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(typeFieldDescr::addAnnotation); + return typeFieldDescr; + } + + private void visitDrlElementValuePairs(DRLParser.DrlElementValuePairsContext ctx, AnnotationDescr annotationDescr) { + ctx.drlElementValuePair().forEach(pairCtx -> { + String key = pairCtx.key.getText(); + String value = getTextPreservingWhitespace(pairCtx.value); + annotationDescr.setKeyValue(key, value); + }); + } + @Override public AttributeDescr visitAttribute(DRLParser.AttributeContext ctx) { AttributeDescr attributeDescr = new AttributeDescr(ctx.getChild(0).getText()); @@ -332,7 +409,7 @@ public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { @Override public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { BehaviorDescr behaviorDescr = new BehaviorDescr(); - behaviorDescr.setType(ctx.label().IDENTIFIER().getText()); + behaviorDescr.setType(ctx.DRL_WINDOW().getText()); behaviorDescr.setSubType(ctx.IDENTIFIER().getText()); List drlExpressionContexts = ctx.expressionList().drlExpression(); List parameters = drlExpressionContexts.stream().map(ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 93a98ed9eb1..9e6a97673ea 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -2792,7 +2792,6 @@ public void parse_RuleExtends() throws Exception { } - @Disabled("Priority : High | Implement type declaration") @Test public void parse_TypeDeclarationWithFields() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2991,7 +2990,6 @@ public void parse_RuleOldSyntax2() throws Exception { assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); } - @Disabled("Priority : High | Implement type declaration") @Test public void parse_TypeWithMetaData() throws Exception { @@ -3255,7 +3253,6 @@ public void parse_InfinityLiteral() throws Exception { } - @Disabled("Priority : High | Implement entry-point declaration") @Test public void parse_EntryPointDeclaration() throws Exception { final String text = "package org.drools\n" + @@ -3277,7 +3274,6 @@ public void parse_EntryPointDeclaration() throws Exception { assertThat(epd.getAnnotation("foo").getValue()).isEqualTo("true"); } - @Disabled("Priority : Mid | Implement sliding window declaration") @Test public void parse_WindowDeclaration() throws Exception { final String text = "package org.drools\n" + From 73faf309fc1142a2f9132ac1ae9f94dbb655bb38 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 20 Oct 2023 15:49:51 +0900 Subject: [PATCH 046/141] [DROOLS-7306] Implement unification (#41) * [DROOLS-7306] Implement unification - Also [DROOLS-7307] Parse attribute agenda-group * [DROOLS-7308] Parse attribute without value - Also [DROOLS-7309] Parse attribute with parentheses --- .../main/antlr4/org/drools/parser/DRLLexer.g4 | 2 +- .../antlr4/org/drools/parser/DRLParser.g4 | 20 +++-- .../org/drools/parser/DRLVisitorImpl.java | 84 +++++++++++++++++-- .../org/drools/parser/MiscDRLParserTest.java | 8 -- 4 files changed, 88 insertions(+), 26 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 index cce083ab8a2..8aac81873cc 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 @@ -124,7 +124,7 @@ DRL_BIG_INTEGER_LITERAL ///////////////// HASH : '#'; -UNIFY : ':=' ; +DRL_UNIFY : ':=' ; NULL_SAFE_DOT : '!.' ; QUESTION_DIV : '?/' ; diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 30ba8454cc5..80774cd08ea 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -116,7 +116,7 @@ lhsUnary : ( | lhsPatternBind ) SEMI? ; -lhsPatternBind : label? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; +lhsPatternBind : (label|unif)? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; /* lhsPattern : xpathPrimary (OVER patternFilter)? | @@ -253,6 +253,7 @@ drlExpression | drlExpression bop=INSTANCEOF (typeType | pattern) | drlExpression bop=DRL_MATCHES drlExpression | drlExpression DRL_NOT? DRL_MEMBEROF drlExpression + | drlExpression bop=DRL_UNIFY drlExpression | drlExpression bop=(EQUAL | NOTEQUAL) drlExpression | drlExpression bop=BITAND drlExpression | drlExpression bop=CARET drlExpression @@ -438,12 +439,15 @@ drlElementValue ; attributes : attribute ( COMMA? attribute )* ; -attribute : ( 'salience' DECIMAL_LITERAL ) - | ( 'enabled' | 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOL_LITERAL? - | ( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) DRL_STRING_LITERAL - | 'calendars' DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* - | 'timer' ( DECIMAL_LITERAL | TEXT ) - | 'duration' ( DECIMAL_LITERAL | TEXT ) ; +attribute : name=( 'salience' | 'enabled' ) conditionalOrExpression #expressionAttribute + | name=( 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOL_LITERAL? #booleanAttribute + | name=( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) DRL_STRING_LITERAL #stringAttribute + | name='calendars' DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* #stringListAttribute + | name='timer' ( DECIMAL_LITERAL | chunk ) #intOrChunkAttribute + | name='duration' ( DECIMAL_LITERAL | TIME_INTERVAL | LPAREN TIME_INTERVAL RPAREN ) #durationAttribute + ; + +chunk : LPAREN .+? RPAREN; assignmentOperator : ASSIGN | ADD_ASSIGN @@ -457,7 +461,7 @@ assignmentOperator : ASSIGN | LT LT ASSIGN ; label : IDENTIFIER COLON ; -unif : IDENTIFIER UNIFY ; +unif : IDENTIFIER DRL_UNIFY ; /* extending JavaParser variableInitializer */ drlVariableInitializer diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 2a09cafd78e..3ca001611de 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -40,6 +40,7 @@ import org.drools.drl.ast.descr.TypeFieldDescr; import org.drools.drl.ast.descr.UnitDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.util.StringUtils; import static org.drools.parser.DRLParserHelper.getTextWithoutErrorNode; import static org.drools.parser.ParserStringUtils.getTextPreservingWhitespace; @@ -95,10 +96,9 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc packageDescr.addWindowDeclaration((WindowDeclarationDescr) descr); } else if (descr instanceof AttributeDescr) { packageDescr.addAttribute((AttributeDescr) descr); - } else if (descr instanceof RuleDescr) { + } else if (descr instanceof RuleDescr) { // QueryDescr extends RuleDescr packageDescr.addRule((RuleDescr) descr); - } else if (descr instanceof QueryDescr) { - packageDescr.addRule((QueryDescr) descr); + packageDescr.afterRuleAdded((RuleDescr) descr); } }); } @@ -301,12 +301,75 @@ private void visitDrlElementValuePairs(DRLParser.DrlElementValuePairsContext ctx } @Override - public AttributeDescr visitAttribute(DRLParser.AttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.getChild(0).getText()); - if (ctx.getChildCount() > 1) { - // TODO : will likely split visitAttribute methods using labels (e.g. #stringAttribute) - String value = unescapeJava(safeStripStringDelimiters(ctx.getChild(1).getText())); - attributeDescr.setValue(value); + public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + attributeDescr.setValue(getTextPreservingWhitespace(ctx.conditionalOrExpression())); + attributeDescr.setType(AttributeDescr.Type.EXPRESSION); + return attributeDescr; + } + + @Override + public AttributeDescr visitBooleanAttribute(DRLParser.BooleanAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + attributeDescr.setValue(ctx.BOOL_LITERAL() != null ? ctx.BOOL_LITERAL().getText() : "true"); + attributeDescr.setType(AttributeDescr.Type.BOOLEAN); + return attributeDescr; + } + + @Override + public AttributeDescr visitStringAttribute(DRLParser.StringAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.DRL_STRING_LITERAL().getText()))); + attributeDescr.setType(AttributeDescr.Type.STRING); + return attributeDescr; + } + + @Override + public AttributeDescr visitStringListAttribute(DRLParser.StringListAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + List valueList = ctx.DRL_STRING_LITERAL().stream() + .map(ParseTree::getText) + .collect(Collectors.toList()); + attributeDescr.setValue(createStringList(valueList)); + attributeDescr.setType(AttributeDescr.Type.LIST); + return attributeDescr; + } + + private static String createStringList(List valueList) { + StringBuilder sb = new StringBuilder(); + sb.append("[ "); + for (int i = 0; i < valueList.size(); i++) { + sb.append(valueList.get(i)); + if (i < valueList.size() - 1) { + sb.append(", "); + } + } + sb.append(" ]"); + return sb.toString(); + } + + @Override + public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + if (ctx.DECIMAL_LITERAL() != null) { + attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); + attributeDescr.setType(AttributeDescr.Type.NUMBER); + } else { + attributeDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); + attributeDescr.setType(AttributeDescr.Type.EXPRESSION); + } + return attributeDescr; + } + + @Override + public AttributeDescr visitDurationAttribute(DRLParser.DurationAttributeContext ctx) { + AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + if (ctx.DECIMAL_LITERAL() != null) { + attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); + attributeDescr.setType(AttributeDescr.Type.NUMBER); + } else { + attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.TIME_INTERVAL().getText()))); + attributeDescr.setType(AttributeDescr.Type.EXPRESSION); } return attributeDescr; } @@ -338,6 +401,9 @@ private PatternDescr getSinglePatternDescr(DRLParser.LhsPatternBindContext ctx) .orElseThrow(() -> new IllegalStateException("lhsPatternBind must have at least one lhsPattern : " + ctx.getText())); if (ctx.label() != null) { patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); + } else if (ctx.unif() != null) { + patternDescr.setIdentifier(ctx.unif().IDENTIFIER().getText()); + patternDescr.setUnification(true); } return patternDescr; } diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 9e6a97673ea..50e7f82f7a1 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -1651,7 +1651,6 @@ public void parse_Comment() throws Exception { assertThat(pkg.getName()).isEqualTo("foo.bar"); } - @Disabled("Priority : High | Parse attribute without value => true") @Test public void parse_Attributes() throws Exception { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( @@ -1731,7 +1730,6 @@ public void parse_Attributes2() throws Exception { } - @Disabled("Priority : High | Parse attribute without value => true") @Test public void parse_AttributeRefract() throws Exception { final String source = "rule Test refract when Person() then end"; @@ -1751,7 +1749,6 @@ public void parse_AttributeRefract() throws Exception { } - @Disabled("Priority : High | Parse attribute with parentheses") @Test public void parse_EnabledExpression() throws Exception { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( @@ -1775,7 +1772,6 @@ public void parse_EnabledExpression() throws Exception { assertThat(at.getValue()).isEqualTo("true"); } - @Disabled("Priority : High | Parse attribute with parentheses") @Test public void parse_DurationExpression() throws Exception { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( @@ -1795,7 +1791,6 @@ public void parse_DurationExpression() throws Exception { assertThat(at.getValue()).isEqualTo("true"); } - @Disabled("Priority : Mid | Parse calendar attribute") @Test public void parse_Calendars() throws Exception { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( @@ -1815,7 +1810,6 @@ public void parse_Calendars() throws Exception { assertThat(at.getValue()).isEqualTo("true"); } - @Disabled("Priority : Mid | Parse calendar attribute") @Test public void parse_Calendars2() throws Exception { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( @@ -1905,7 +1899,6 @@ public void parse_SoundsLike() throws Exception { pat.getConstraint(); } - @Disabled("Priority : High | Parse attribute agenda-group") @Test public void parse_PackageAttributes() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -3132,7 +3125,6 @@ public void parse_PositionalsAndNamedConstraints() throws Exception { } - @Disabled("Priority : High | Implement unification") @Test public void parse_UnificationBinding() throws Exception { final String text = "rule X when $p := Person( $name := name, $loc : location ) then end"; From e56f2a76c45254559c296fcf90a13e8e3fd19e39 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 27 Oct 2023 15:53:09 +0900 Subject: [PATCH 047/141] [DROOLS-7310] parse nested parentheses (#42) * [DROOLS-7310] parse nested parentheses * - Adding code commentes and explanations - Adding more nested level tests --- .../antlr4/org/drools/parser/DRLParser.g4 | 20 ++- .../org/drools/parser/DRLVisitorImpl.java | 148 ++++++++++++++++-- .../org/drools/parser/MiscDRLParserTest.java | 85 ++++++++-- 3 files changed, 225 insertions(+), 28 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 index 80774cd08ea..933c013ee6c 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 @@ -91,8 +91,9 @@ lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed | lhsExpression (DRL_OR lhsExpression)+ #lhsOr ; -// lhsAnd is used as a label in lhsExpression rule. But some other rules also use it. -lhsAndDef : lhsUnary (DRL_AND lhsUnary)* +// 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 lhsUnary)* | LPAREN DRL_AND lhsUnary+ RPAREN ; @@ -380,7 +381,13 @@ fromEntryPoint : DRL_ENTRY_POINT stringId ; | lhsPatternBind ) */ -lhsExists : DRL_EXISTS lhsPatternBind ; +// Use lhsExpression instead of lhsOr because lhsExpression has good enough structure +lhsExists : DRL_EXISTS + ( LPAREN lhsExpression RPAREN + | lhsPatternBind + ) + ; + /* lhsNot := NOT ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or @@ -388,7 +395,12 @@ lhsExists : DRL_EXISTS lhsPatternBind ; | lhsPatternBind ) */ -lhsNot : DRL_NOT lhsPatternBind ; +// Use lhsExpression instead of lhsOr because lhsExpression has good enough structure +lhsNot : DRL_NOT + ( LPAREN lhsExpression RPAREN + | lhsPatternBind + ) + ; /** * lhsEval := EVAL LEFT_PAREN conditionalExpression RIGHT_PAREN diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 3ca001611de..8212ac32bee 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -40,7 +40,6 @@ import org.drools.drl.ast.descr.TypeFieldDescr; import org.drools.drl.ast.descr.UnitDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; -import org.drools.util.StringUtils; import static org.drools.parser.DRLParserHelper.getTextWithoutErrorNode; import static org.drools.parser.ParserStringUtils.getTextPreservingWhitespace; @@ -577,16 +576,38 @@ public String visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { @Override public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { ExistsDescr existsDescr = new ExistsDescr(); - BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); - existsDescr.addDescr(descr); + if (ctx.lhsExpression() != null) { + // exists( A() or B() ) + List baseDescrs = visitDescrChildren(ctx); + if (baseDescrs.size() == 1) { + existsDescr.addDescr(baseDescrs.get(0)); + } else { + throw new IllegalStateException("'exists()' children descr size must be 1 : " + ctx.getText()); + } + } else { + // exists A() + BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); + existsDescr.addDescr(descr); + } return existsDescr; } @Override public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { NotDescr notDescr = new NotDescr(); - BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); - notDescr.addDescr(descr); + if (ctx.lhsExpression() != null) { + // not ( A() or B() ) + List baseDescrs = visitDescrChildren(ctx); + if (baseDescrs.size() == 1) { + notDescr.addDescr(baseDescrs.get(0)); + } else { + throw new IllegalStateException("'not()' children descr size must be 1 : " + ctx.getText()); + } + } else { + // not A() + BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); + notDescr.addDescr(descr); + } return notDescr; } @@ -602,26 +623,87 @@ public BaseDescr visitLhsExpressionEnclosed(DRLParser.LhsExpressionEnclosedConte @Override public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { - OrDescr orDescr = new OrDescr(); - List descrList = visitDescrChildren(ctx); - descrList.forEach(orDescr::addDescr); - return orDescr; + // For flatten nested OrDescr logic, we call visitDescrChildrenForDescrNodePair instead of usual visitDescrChildren + List descrList = visitDescrChildrenForDescrNodePair(ctx); + if (descrList.size() == 1) { + // Avoid nested OrDescr + return descrList.get(0).getDescr(); + } else { + OrDescr orDescr = new OrDescr(); + // For example, in case of A() or B() or C(), + // Parser creates AST like this: + // lhsOr + // / \ + // A() lhsOr + // / \ + // B() C() + // So, we need to flatten it so that OrDescr has A(), B() and C() as children. + List flattenedDescrs = flattenOrDescr(descrList); + flattenedDescrs.forEach(orDescr::addDescr); + return orDescr; + } + } + + private List flattenOrDescr(List descrList) { + List flattenedDescrs = new ArrayList<>(); + for (DescrNodePair descrNodePair : descrList) { + BaseDescr descr = descrNodePair.getDescr(); + ParseTree node = descrNodePair.getNode(); // parser node corresponding to the descr + if (descr instanceof OrDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { + // sibling OrDescr should be flattened unless it's explicitly enclosed by parenthesis + flattenedDescrs.addAll(((OrDescr) descr).getDescrs()); + } else { + flattenedDescrs.add(descr); + } + } + return flattenedDescrs; } @Override public BaseDescr visitLhsAnd(DRLParser.LhsAndContext ctx) { - return createAndDescr(visitDescrChildren(ctx)); + return createAndDescr(ctx); + } + + private BaseDescr createAndDescr(ParserRuleContext ctx) { + // For flatten nested AndDescr logic, we call visitDescrChildrenForDescrNodePair instead of usual visitDescrChildren + List descrList = visitDescrChildrenForDescrNodePair(ctx); + if (descrList.size() == 1) { + // Avoid nested AndDescr + return descrList.get(0).getDescr(); + } else { + AndDescr andDescr = new AndDescr(); + // For example, in case of A() and B() and C(), + // Parser creates AST like this: + // lhsAnd + // / \ + // A() lhsAnd + // / \ + // B() C() + // So, we need to flatten it so that AndDescr has A(), B() and C() as children. + List flattenedDescrs = flattenAndDescr(descrList); + flattenedDescrs.forEach(andDescr::addDescr); + return andDescr; + } } - private AndDescr createAndDescr(List descrList) { - AndDescr andDescr = new AndDescr(); - descrList.forEach(andDescr::addDescr); - return andDescr; + private List flattenAndDescr(List descrList) { + List flattenedDescrs = new ArrayList<>(); + for (DescrNodePair descrNodePair : descrList) { + BaseDescr descr = descrNodePair.getDescr(); + ParseTree node = descrNodePair.getNode(); // parser node corresponding to the descr + if (descr instanceof AndDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { + // sibling AndDescr should be flattened unless it's explicitly enclosed by parenthesis + flattenedDescrs.addAll(((AndDescr) descr).getDescrs()); + } else { + flattenedDescrs.add(descr); + } + } + return flattenedDescrs; } @Override public BaseDescr visitLhsAndDef(DRLParser.LhsAndDefContext ctx) { - return createAndDescr(visitDescrChildren(ctx)); + return createAndDescr(ctx); } @Override @@ -650,6 +732,42 @@ private List visitDescrChildren(RuleNode node) { return aggregator; } + // This method is used when the parent descr requires children parser node information for composing the descr. + // Ideally, we should use visitDescrChildren as possible and use the returned Descr object to compose the parent descr. + // However, for example, in flatten OrDescr/AndDescr logic, + // enhancing the returned Descr object of visitLhsExpressionEnclosed() (e.g. adding 'enclosed' flag to OrDescr/AndDescr) could be intrusive just for composing the parent descr. + private List visitDescrChildrenForDescrNodePair(RuleNode node) { + List aggregator = new ArrayList<>(); + int n = node.getChildCount(); + + for (int i = 0; i < n && this.shouldVisitNextChild(node, aggregator); ++i) { + ParseTree c = node.getChild(i); + Object childResult = c.accept(this); + if (childResult instanceof BaseDescr) { + aggregator.add(new DescrNodePair((BaseDescr) childResult, c)); // pairing the returned Descr and the parser node + } + } + return aggregator; + } + + private static class DescrNodePair { + private final BaseDescr descr; // returned Descr object + private final ParseTree node; // parser node corresponding to the descr. This is used for composing the parent descr. + + private DescrNodePair(BaseDescr descr, ParseTree node) { + this.descr = descr; + this.node = node; + } + + public BaseDescr getDescr() { + return descr; + } + + public ParseTree getNode() { + return node; + } + } + // leaves of constraint concatenate return Strings private String visitConstraintChildren(ParserRuleContext ctx) { return getTokenTextPreservingWhitespace(ctx, tokenStream); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java index 50e7f82f7a1..229524867d5 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java @@ -1477,7 +1477,7 @@ void parenthesesOrAndAnd() { } @Test - void parenthesesAndOrOrOrAnd() throws Exception { + void multipleLevelNestAndOrOrOrAnd() throws Exception { final String drl = "rule and_or_or_or_and\n" + " when\n" + " (Foo(x == 1) and (Bar(x == 2) or Foo(x == 3))) or (Bar(x == 4) or (Foo(x == 5) and Bar(x == 6)))\n" + @@ -1516,6 +1516,79 @@ void parenthesesAndOrOrOrAnd() throws Exception { assertThat(bar3.getObjectType()).isEqualTo("Bar"); } + @Test + void multipleLevelNestWithThreeOrSiblings() throws Exception { + final String drl = "rule nest_or_siblings\n" + + " when\n" + + " (A() or (B() or C() or (D() and E())))\n" + + " then\n" + + "end"; + PackageDescr pkg = parser.parse(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final PatternDescr leftPattern = (PatternDescr) topOr.getDescrs().get(0); + assertThat(leftPattern.getObjectType()).isEqualTo("A"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).as("top level Or has 3 sibling children").hasSize(3); + final PatternDescr bPattern = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(bPattern.getObjectType()).isEqualTo("B"); + final PatternDescr cPattern = (PatternDescr) rightOr.getDescrs().get(1); + assertThat(cPattern.getObjectType()).isEqualTo("C"); + final AndDescr deAnd = (AndDescr) rightOr.getDescrs().get(2); + assertThat(deAnd.getDescrs()).hasSize(2); + + final PatternDescr dPattern = (PatternDescr) deAnd.getDescrs().get(0); + assertThat(dPattern.getObjectType()).isEqualTo("D"); + final PatternDescr ePattern = (PatternDescr) deAnd.getDescrs().get(1); + assertThat(ePattern.getObjectType()).isEqualTo("E"); + } + + @Test + public void existsMultipleLevelNestWithThreeOrSiblings() throws Exception { + final String drl = "rule nest_or_siblings\n" + + " when\n" + + " exists(A() or (B() or C() or (D() and E())))\n" + + " then\n" + + "end"; + PackageDescr pkg = parser.parse(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final ExistsDescr topExists = (ExistsDescr) rootAnd.getDescrs().get(0); + assertThat(topExists.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) topExists.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final PatternDescr leftPattern = (PatternDescr) topOr.getDescrs().get(0); + assertThat(leftPattern.getObjectType()).isEqualTo("A"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).hasSize(3); + final PatternDescr bPattern = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(bPattern.getObjectType()).isEqualTo("B"); + final PatternDescr cPattern = (PatternDescr) rightOr.getDescrs().get(1); + assertThat(cPattern.getObjectType()).isEqualTo("C"); + final AndDescr deAnd = (AndDescr) rightOr.getDescrs().get(2); + assertThat(deAnd.getDescrs()).hasSize(2); + + final PatternDescr dPattern = (PatternDescr) deAnd.getDescrs().get(0); + assertThat(dPattern.getObjectType()).isEqualTo("D"); + final PatternDescr ePattern = (PatternDescr) deAnd.getDescrs().get(1); + assertThat(ePattern.getObjectType()).isEqualTo("E"); + } + @Test public void parse_EvalMultiple() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -1686,7 +1759,6 @@ public void parse_Attributes() throws Exception { assertThat(at.getValue()).isEqualTo("true"); } - @Disabled("Priority : High | Parse attribute with parentheses") @Test public void parse_Attributes2() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2084,7 +2156,6 @@ public void parse_EscapedStrings() throws Exception { assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( expected); } - @Disabled("Priority : High | parse nested parentheses") @Test public void parse_NestedCEs() throws Exception { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( @@ -2835,11 +2906,9 @@ public void parse_TypeDeclarationWithFields() throws Exception { } - @Disabled("Priority : High | Failed to parse or with parentheses in LHS") @Test - public void parse_RuleWithLHSNesting() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "Rule_with_nested_LHS.drl" ); + public void parenthesesOneLevelNestWithThreeSiblings() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( "Rule_with_nested_LHS.drl" ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); @@ -2941,7 +3010,6 @@ public void parse_SlidingWindow() throws Exception { assertThat(descr.getParameters().get(0)).isEqualTo("10"); } - @Disabled("Priority : Mid | outmost parentheses") @Test public void parse_RuleOldSyntax1() throws Exception { final String source = "rule \"Test\" when ( not $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; @@ -2963,7 +3031,6 @@ public void parse_RuleOldSyntax1() throws Exception { assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); } - @Disabled("Priority : Mid | outmost parentheses") @Test public void parse_RuleOldSyntax2() throws Exception { final String source = "rule \"Test\" when ( $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; From cdd9d3c9817a8cac0236602224f657abae053187 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 17 Nov 2023 17:16:34 +0900 Subject: [PATCH 048/141] =?UTF-8?q?[DROOLS-7577]=20drools-lsp=20:=20Add=20?= =?UTF-8?q?comments=20and=20explanations=20for=20drools-p=E2=80=A6=20(#43)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [DROOLS-7577] drools-lsp : Add comments and explanations for drools-parser * removed syntax examples --- .../drools-drl10-parser/Developer_Notes.md | 38 ++++++++ .../org/drools/parser/DRLErrorListener.java | 3 + .../org/drools/parser/DRLParserError.java | 3 + .../org/drools/parser/DRLParserHelper.java | 13 +++ .../org/drools/parser/DRLParserWrapper.java | 6 ++ .../org/drools/parser/DRLVisitorImpl.java | 86 ++++++++++++++----- .../org/drools/parser/ParserStringUtils.java | 18 +++- 7 files changed, 142 insertions(+), 25 deletions(-) create mode 100644 drools-drl/drools-drl10-parser/Developer_Notes.md diff --git a/drools-drl/drools-drl10-parser/Developer_Notes.md b/drools-drl/drools-drl10-parser/Developer_Notes.md new file mode 100644 index 00000000000..c521ee6d14f --- /dev/null +++ b/drools-drl/drools-drl10-parser/Developer_Notes.md @@ -0,0 +1,38 @@ +## drools-parser + +This module is a reimplementation of the DRL (Drools Rule Language) parser based on ANTLR4. + +The current [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java) is based on ANTLR3 and contains a lot of custom modifications, which is hard to maintain. This new module should keep the separation between the parser syntax (`DRLParser.g4`) and the Descr generation (`DRLVisitorImpl.java`). + +This module started with a part of LSP to develop DRL editors, but it is not limited to that. This module will also replace DRL6Parser in the drools code base. + +### How is this developed? + +1. The starting point is [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java). While it contains lots of customizations, we can map its javadoc (e.g. `packageStatement := PACKAGE qualifiedIdentifier SEMICOLON?`) to `DRLParser.g4` (e.g. `packagedef : PACKAGE name=drlQualifiedName SEMI? ;`). +2. `DRLLexer.g4` is written to define tokens for DRL. +3. `DRLLexer.g4` imports `JavaLexer.g4` to reuse Java tokens. `DRLParser.g4` imports `JavaParser.g4` to reuse Java grammar. These Java parser files are distributed by ANTLR4 under BSD license. +4. In `DRLLexer.g4`, basically define tokens with a prefix "DRL_" to clarify they are DRL keywords. +5. In `DRLParser.g4`, define parser rules with a prefix "drl" if the rule name conflicts with `JavaParser.g4`. Sometimes we need to do that, because such a rule may contain DRL keywords. +6. (As of 2023/10/31) this parser doesn't deeply parse rule RHS (just multiple `RHS_CHUNK`s), because Drools passes RHS text to drools-compiler as-is. In case of developing DRL editors, we may need to integrate another Java LSP to support RHS code completion, etc. +7. LHS constraint (e.g. `age > 30`) is also handled as text. Further processing will be done in the later compiler phase. +8. `DRLParser` processes a DRL text and produces an AST(abstract syntax tree). Then apply `DRLVisitorImpl` to generate PackageDescr following the visitor pattern. So the main work would be implementing `DRLParser.g4` and `DRLVisitorImpl`. +9. Errors are handled by `DRLErrorListener` +10. (As of 2023/10/31) We have 2 test classes. `DRLParserTest` is a very basic test to check if the parser can parse DRL. `MiscDRLParserTest` contains various DRL syntax to check if the parser generates correct Descr objects. `MiscDRLParserTest` was ported from [RuleParserTest](https://github.com/apache/incubator-kie-drools/blob/main/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java) so that we can ensure the compatibility of generated Descr objects between the current implementation and the new one. +11. As `DRL6Parser` contains hard-coded customizations, sometimes we need to read and understand the `DRL6Parser` source codes to meet the compatibility. +12. (As of 2023/10/31) `MiscDRLParserTest` still has several test cases with `@Disabled` which are relatively lower priority or edge cases. They need to be resolved at some point in the future. To fix the issues, file a JIRA, remove the `@Disabled` annotation, and fix the implementation to pass the test case. + +### Next steps + +1. Create a feature branch in drools repo and replace `DRL6Parser` with this new parser. +2. We will detect issues in the new parser by running the existing tests in drools repo. If we find any issues, we will fix them in the new parser and add new tests to cover them. Such tests would be more or less Descr comparison tests, so we would add a new test class which is similar to `MiscDRLParserTest`. + +### Refactoring candidates +- `DRLParserHelper` and `DRLParserWrapper` have some duplicated code and purpose. We can merge them into one class. +- `MiscDRLParserTest` can be cleaner and fixed to align with SonarLint suggestions. +- Constraint related parser rules after `conditionalOrExpression` are written in antlr3 style. They could be refactored to antlr4 style (like `lhsExpression`). + +### Development tips +- IntelliJ IDEA has an ANTLR4 plugin, which "ANTLR Preview" window displays a parse tree. It is very useful to debug the parser rules. + +### Resources +[The Definitive ANTLR 4 Reference](https://pragprog.com/titles/tpantlr2/the-definitive-antlr-4-reference/) \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java index a15d12adddb..f7c6504df4c 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java @@ -7,6 +7,9 @@ import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; +/** + * Collect errors while parsing DRL + */ public class DRLErrorListener extends BaseErrorListener { private final List errors = new ArrayList<>(); diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java index 6b9fe116943..ec3e41747df 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java @@ -1,5 +1,8 @@ package org.drools.parser; +/** + * Error information while parsing DRL + */ public class DRLParserError { private int lineNumber; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index 3bd15b3f4fa..bee7a6e96d4 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -10,11 +10,18 @@ import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.PackageDescr; +/** + * Collection of static helper methods for DRLParser + */ public class DRLParserHelper { private DRLParserHelper() { } + /** + * Entry point for parsing DRL. + * Unlike DRLParserWrapper.parse(), this method does not collect errors. + */ public static PackageDescr parse(String drl) { DRLParser drlParser = createDrlParser(drl); return compilationUnitContext2PackageDescr(drlParser.compilationUnit(), drlParser.getTokenStream()); @@ -27,6 +34,9 @@ public static DRLParser createDrlParser(String drl) { return new DRLParser(commonTokenStream); } + /** + * DRLVisitorImpl visits a parse tree and creates a PackageDescr + */ public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.CompilationUnitContext ctx, TokenStream tokenStream) { DRLVisitorImpl visitor = new DRLVisitorImpl(tokenStream); Object descr = visitor.visit(ctx); @@ -37,6 +47,9 @@ 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) { for (int i = 0; i < parser.getInputStream().size(); i++) { Token token = parser.getInputStream().get(i); diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java index 06992f0440e..8f24bf1d3f4 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java @@ -10,12 +10,18 @@ import static org.drools.parser.DRLParserHelper.compilationUnitContext2PackageDescr; +/** + * Wrapper for DRLParser. Somewhat duplicated from DRLParserHelper, but this class is instantiated and holds errors. + */ public class DRLParserWrapper { private static final Logger LOGGER = LoggerFactory.getLogger(DRLParserWrapper.class); private final List errors = new ArrayList<>(); + /** + * Main entry point for parsing DRL + */ public PackageDescr parse(String drl) { DRLParser drlParser = DRLParserHelper.createDrlParser(drl); DRLErrorListener errorListener = new DRLErrorListener(); diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java index 8212ac32bee..3f920cc13a5 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java @@ -48,6 +48,12 @@ import static org.drools.parser.ParserStringUtils.trimThen; import static org.drools.util.StringUtils.unescapeJava; +/** + * Visitor implementation for DRLParser. + * 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 { private final TokenStream tokenStream; @@ -56,6 +62,9 @@ public DRLVisitorImpl(TokenStream tokenStream) { this.tokenStream = tokenStream; } + /** + * Main entry point for creating PackageDescr from a parser tree. + */ @Override public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { PackageDescr packageDescr = new PackageDescr(); @@ -67,7 +76,11 @@ public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { return packageDescr; } + /** + * Add all children Descr to PackageDescr + */ private void applyChildrenDescrs(PackageDescr packageDescr, List descrList) { + // This bunch of if-blocks will be refactored by DROOLS-7564 descrList.forEach(descr -> { if (descr instanceof UnitDescr) { packageDescr.setUnit((UnitDescr) descr); @@ -147,6 +160,8 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { functionDescr.setReturnType("void"); } functionDescr.setName(ctx.IDENTIFIER().getText()); + + // add function parameters DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); if (formalParameterListContext != null) { @@ -163,7 +178,7 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { @Override public BaseDescr visitDeclaredef(DRLParser.DeclaredefContext ctx) { - return visitDescrChildren(ctx).get(0); + return visitDescrChildren(ctx).get(0); // only one child } @Override @@ -202,6 +217,9 @@ public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclaration return windowDeclarationDescr; } + /** + * entry point for one rule + */ @Override public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { RuleDescr ruleDescr = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); @@ -228,16 +246,27 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { if (ctx.rhs() != null) { ruleDescr.setConsequenceLocation(ctx.rhs().getStart().getLine(), ctx.rhs().getStart().getCharPositionInLine()); // location of "then" - ruleDescr.setConsequence(trimThen(getTextPreservingWhitespace(ctx.rhs()))); + ruleDescr.setConsequence(trimThen(getTextPreservingWhitespace(ctx.rhs()))); // RHS is just a text } return ruleDescr; } private void slimLhsRootDescr(AndDescr root) { + // Root Descr is always AndDescr. + // For example, if there are nested AndDescr like + // AndDescr + // /\ + // P AndDescr + // /\ + // P P + // is slimmed down to + // AndDescr + // / | \ + // P P P List descrList = new ArrayList<>(root.getDescrs()); root.getDescrs().clear(); - descrList.forEach(root::addOrMerge); // This slims down nested AndDescr + descrList.forEach(root::addOrMerge); } @Override @@ -373,6 +402,9 @@ public AttributeDescr visitDurationAttribute(DRLParser.DurationAttributeContext return attributeDescr; } + /** + * entry point for LHS + */ @Override public List visitLhs(DRLParser.LhsContext ctx) { if (ctx.lhsExpression() != null) { @@ -394,10 +426,12 @@ public BaseDescr visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { } private PatternDescr getSinglePatternDescr(DRLParser.LhsPatternBindContext ctx) { - Optional optPatternDescr = visitFirstDescrChild(ctx); - PatternDescr patternDescr = optPatternDescr.filter(PatternDescr.class::isInstance) - .map(PatternDescr.class::cast) - .orElseThrow(() -> new IllegalStateException("lhsPatternBind must have at least one lhsPattern : " + ctx.getText())); + List patternDescrList = visitDescrChildren(ctx); + if (patternDescrList.isEmpty() || !(patternDescrList.get(0) instanceof PatternDescr)) { + throw new IllegalStateException("lhsPatternBind must have at least one lhsPattern : " + ctx.getText()); + } + PatternDescr patternDescr = (PatternDescr)patternDescrList.get(0); + if (ctx.label() != null) { patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); } else if (ctx.unif() != null) { @@ -423,6 +457,9 @@ private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindConte return orDescr; } + /** + * entry point for a Pattern + */ @Override public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { PatternDescr patternDescr = new PatternDescr(ctx.objectType.getText()); @@ -528,6 +565,9 @@ public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) return new EntryPointDescr(safeStripStringDelimiters(ctx.stringId().getText())); } + /** + * Collect constraints in a Pattern + */ @Override public List visitConstraints(DRLParser.ConstraintsContext ctx) { List exprConstraintDescrList = new ArrayList<>(); @@ -535,6 +575,9 @@ public List visitConstraints(DRLParser.ConstraintsContext c return exprConstraintDescrList; } + /** + * Collect constraints in a Pattern. Positional constraints comes first with semicolon. + */ private List visitConstraints(DRLParser.PositionalConstraintsContext positionalCtx, DRLParser.ConstraintsContext ctx) { List exprConstraintDescrList = new ArrayList<>(); populateExprConstraintDescrList(positionalCtx, exprConstraintDescrList); @@ -557,6 +600,9 @@ private void populateExprConstraintDescrList(ParserRuleContext ctx, List visitDescrChildren(RuleNode node) { List aggregator = new ArrayList<>(); int n = node.getChildCount(); @@ -768,21 +819,10 @@ public ParseTree getNode() { } } - // leaves of constraint concatenate return Strings + /** + * Return the text of constraint as-is + */ private String visitConstraintChildren(ParserRuleContext ctx) { return getTokenTextPreservingWhitespace(ctx, tokenStream); } - - private Optional visitFirstDescrChild(RuleNode node) { - int n = node.getChildCount(); - - for (int i = 0; i < n && this.shouldVisitNextChild(node, null); ++i) { - ParseTree c = node.getChild(i); - Object childResult = c.accept(this); - if (childResult instanceof BaseDescr) { - return Optional.of((BaseDescr) childResult); - } - } - return Optional.empty(); - } -} +} \ No newline at end of file diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java index 1f84eb6f9c8..a294bf2a923 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java @@ -5,13 +5,17 @@ import org.antlr.v4.runtime.misc.Interval; /** - * will be merged in drools-util + * Collection of String utilities used by DRLParser. + * This may be merged in drools-util */ public class ParserStringUtils { private ParserStringUtils() { } + /** + * Strip string delimiters (e.g. "foo" -> foo) + */ public static String safeStripStringDelimiters(String value) { if (value != null) { value = value.trim(); @@ -22,6 +26,9 @@ public static String safeStripStringDelimiters(String value) { return value; } + /** + * Get text from ParserRuleContext's CharStream without trimming whitespace + */ public static String getTextPreservingWhitespace(ParserRuleContext ctx) { // Using raw CharStream int startIndex = ctx.start.getStartIndex(); @@ -34,11 +41,18 @@ public static String getTextPreservingWhitespace(ParserRuleContext ctx) { return ctx.start.getTokenSource().getInputStream().getText(interval); } + /** + * Get text from ParserRuleContext's CharStream without trimming whitespace + * tokenStream is required to get hidden channel token (e.g. whitespace). + * Unlike getTextPreservingWhitespace, this method reflects Lexer normalizeString + */ public static String getTokenTextPreservingWhitespace(ParserRuleContext ctx, TokenStream tokenStream) { - // tokenStream is required to get hidden channel token (e.g. whitespace). Unlike getTextPreservingWhitespace, this method reflects Lexer normalizeString return tokenStream.getText(ctx.start, ctx.stop); } + /** + * Just remove leading "then" + */ public static String trimThen(String rhs) { if (rhs.startsWith("then")) { return rhs.substring("then".length()); From f7ae31305b016a7c881102b6b56be8c72fa8fe6b Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 5 Dec 2023 16:48:44 +0900 Subject: [PATCH 049/141] [DROOLS-7591] Experiment branch : migrate a new drools-lsp parser into drools (#44) - Add some methods to call from drools code base --- .../org/drools/parser/DRLParserHelper.java | 21 +++++++++++++++++-- .../org/drools/parser/DRLParserWrapper.java | 13 ++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java index bee7a6e96d4..bd95c3033c5 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java @@ -1,5 +1,9 @@ package org.drools.parser; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; + import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; @@ -28,8 +32,21 @@ public static PackageDescr parse(String drl) { } public static DRLParser createDrlParser(String drl) { - CharStream inputStream = CharStreams.fromString(drl); - DRLLexer drlLexer = new DRLLexer(inputStream); + CharStream charStream = CharStreams.fromString(drl); + return createDrlParser(charStream); + } + + public static DRLParser createDrlParser(InputStream is) { + try { + CharStream charStream = CharStreams.fromStream(is); + return createDrlParser(charStream); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static DRLParser createDrlParser(CharStream charStream) { + DRLLexer drlLexer = new DRLLexer(charStream); CommonTokenStream commonTokenStream = new CommonTokenStream(drlLexer); return new DRLParser(commonTokenStream); } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java index 8f24bf1d3f4..88ae36c12fe 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java @@ -1,5 +1,6 @@ package org.drools.parser; +import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -24,6 +25,18 @@ public class DRLParserWrapper { */ public PackageDescr parse(String drl) { DRLParser drlParser = DRLParserHelper.createDrlParser(drl); + return parse(drlParser); + } + + /** + * Main entry point for parsing DRL + */ + public PackageDescr parse(InputStream is) { + DRLParser drlParser = DRLParserHelper.createDrlParser(is); + return parse(drlParser); + } + + private PackageDescr parse(DRLParser drlParser) { DRLErrorListener errorListener = new DRLErrorListener(); drlParser.addErrorListener(errorListener); From b224630d5bae80681c17cc6b7ed877f478d8d0ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Mon, 15 Jan 2024 21:25:22 +0100 Subject: [PATCH 050/141] Move necessary files without any additional modifications --- .../org/drools/parser/DRL6Expressions.g4 | 836 ++++++++++++++++++ .../org/drools/parser/DRLExpressions.java | 54 ++ .../java/org/drools/parser/DrlExprParser.java | 88 ++ .../parser/DroolsParserExceptionFactory.java | 380 ++++++++ .../java/org/drools/parser/ParserHelper.java | 672 ++++++++++++++ .../org/drools/parser/DRLExprParserTest.java | 270 ++++++ 6 files changed, 2300 insertions(+) create mode 100644 drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java create mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java create mode 100644 drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 new file mode 100644 index 00000000000..b531c38feff --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 @@ -0,0 +1,836 @@ +parser grammar DRL6Expressions; + +options { + language = Java; + tokenVocab = DRL6Lexer; + superClass=DRLExpressions; +} + +@header { + package org.drools.drl.parser.lang; + + import java.util.LinkedList; + import org.drools.drl.parser.DroolsParserException; + import org.drools.drl.parser.lang.ParserHelper; + import org.drools.drl.parser.lang.DroolsParserExceptionFactory; + import org.drools.drl.parser.lang.Location; + + import org.drools.drl.ast.dsl.AnnotatedDescrBuilder; + import org.drools.drl.ast.dsl.AnnotationDescrBuilder; + + import org.drools.drl.ast.descr.AtomicExprDescr; + import org.drools.drl.ast.descr.AnnotatedBaseDescr; + import org.drools.drl.ast.descr.AnnotationDescr; + import org.drools.drl.ast.descr.BaseDescr; + import org.drools.drl.ast.descr.ConstraintConnectiveDescr; + import org.drools.drl.ast.descr.RelationalExprDescr; + import org.drools.drl.ast.descr.BindingDescr; +} + +@members { + private ParserHelper helper; + + public DRL6Expressions(TokenStream input, + RecognizerSharedState state, + ParserHelper helper ) { + this( input, + state ); + this.helper = helper; + } + + public ParserHelper getHelper() { return helper; } + public boolean hasErrors() { return helper.hasErrors(); } + public List getErrors() { return helper.getErrors(); } + public List getErrorMessages() { return helper.getErrorMessages(); } + public void enableEditorInterface() { helper.enableEditorInterface(); } + public void disableEditorInterface() { helper.disableEditorInterface(); } + public LinkedList getEditorInterface() { return helper.getEditorInterface(); } + public void reportError(RecognitionException ex) { helper.reportError( ex ); } + public void emitErrorMessage(String msg) {} + + private boolean buildDescr; + private int inMap = 0; + private int ternOp = 0; + private boolean hasBindings; + public void setBuildDescr( boolean build ) { this.buildDescr = build; } + public boolean isBuildDescr() { return this.buildDescr; } + + public void setLeftMostExpr( String value ) { helper.setLeftMostExpr( value ); } + public String getLeftMostExpr() { return helper.getLeftMostExpr(); } + + public void setHasBindings( boolean value ) { this.hasBindings = value; } + public boolean hasBindings() { return this.hasBindings; } + + private boolean isNotEOF() { + if (state.backtracking != 0){ + return false; + } + if (input.get( input.index() - 1 ).getType() == DRL6Lexer.WS){ + return true; + } + if (input.LA(-1) == DRL6Lexer.LEFT_PAREN){ + return true; + } + return input.get( input.index() ).getType() != DRL6Lexer.EOF; + } + + private boolean notStartWithNewline() { + int currentTokenIndex = input.index(); // current position in input stream + Token previousHiddenToken = input.get(currentTokenIndex - 1); + String previousHiddenTokenText = previousHiddenToken.getText(); + return !previousHiddenTokenText.contains("\n"); + } +} + +// Alter code generation so catch-clauses get replace with +// this action. +@rulecatch { +catch (RecognitionException re) { + throw re; +} +} + +// -------------------------------------------------------- +// GENERAL RULES +// -------------------------------------------------------- +literal + : STRING { helper.emit($STRING, DroolsEditorType.STRING_CONST); } + | DECIMAL { helper.emit($DECIMAL, DroolsEditorType.NUMERIC_CONST); } + | HEX { helper.emit($HEX, DroolsEditorType.NUMERIC_CONST); } + | FLOAT { helper.emit($FLOAT, DroolsEditorType.NUMERIC_CONST); } + | BOOL { helper.emit($BOOL, DroolsEditorType.BOOLEAN_CONST); } + | NULL { helper.emit($NULL, DroolsEditorType.NULL_CONST); } + | TIME_INTERVAL { helper.emit($TIME_INTERVAL, DroolsEditorType.NULL_CONST); } + | STAR { helper.emit($STAR, DroolsEditorType.NUMERIC_CONST); } // this means "infinity" in Drools + ; + +operator returns [boolean negated, String opr] +@init{ if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); helper.setHasOperator( true ); } +@after{ if( state.backtracking == 0 && input.LA( 1 ) != DRL6Lexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } } + : x=TILDE? + ( op=EQUALS { $negated = false; $opr=($x != null ? $x.text : "")+$op.text; helper.emit($op, DroolsEditorType.SYMBOL); } + | op=NOT_EQUALS { $negated = false; $opr=($x != null ? $x.text : "")+$op.text; helper.emit($op, DroolsEditorType.SYMBOL); } + | rop=relationalOp { $negated = $rop.negated; $opr=($x != null ? $x.text : "")+$rop.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 ); } +@after{ if( state.backtracking == 0 && input.LA( 1 ) != DRL6Lexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } } + : ( op=LESS_EQUALS { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | op=GREATER_EQUALS { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | op=LESS { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | op=GREATER { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | xop=complexOp { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | not_key nop=neg_operator_key { $negated = true; $opr=$nop.text;} + | cop=operator_key { $negated = false; $opr=$cop.text;} + ) + ; + +complexOp returns [String opr] + : t=TILDE e=EQUALS_ASSIGN { $opr=$t.text+$e.text; } + ; + +typeList + : type (COMMA type)* + ; + +type + : tm=typeMatch + ; + +typeMatch + : (primitiveType) => ( primitiveType ((LEFT_SQUARE RIGHT_SQUARE)=> LEFT_SQUARE RIGHT_SQUARE)* ) + | ( ID ((typeArguments)=>typeArguments)? (DOT ID ((typeArguments)=>typeArguments)? )* ((LEFT_SQUARE RIGHT_SQUARE)=> LEFT_SQUARE RIGHT_SQUARE)* ) + ; + +typeArguments + : LESS typeArgument (COMMA typeArgument)* GREATER + ; + +typeArgument + : type + | QUESTION ((extends_key | super_key) type)? + ; + +// -------------------------------------------------------- +// EXPRESSIONS +// -------------------------------------------------------- +// the following dymmy rule is to force the AT symbol to be +// included in the follow set of the expression on the DFAs +dummy + : expression ( AT | SEMICOLON | EOF | ID | RIGHT_PAREN ) ; + +dummy2 + : relationalExpression EOF; + +// top level entry point for arbitrary expression parsing +expression returns [BaseDescr result] + : left=conditionalExpression { if( buildDescr ) { $result = $left.result; } } + ((assignmentOperator) => op=assignmentOperator right=expression)? + ; + +conditionalExpression returns [BaseDescr result] + : left=conditionalOrExpression { if( buildDescr ) { $result = $left.result; } } + ternaryExpression? + ; + +ternaryExpression +@init{ ternOp++; } + : QUESTION ts=expression COLON fs=expression + ; +finally { ternOp--; } + + +fullAnnotation [AnnotatedDescrBuilder inDescrBuilder] returns [AnnotationDescr result] +@init{ String n = ""; AnnotationDescrBuilder annoBuilder = null; } + : AT name=ID { n = $name.text; } ( DOT x=ID { n += "." + $x.text; } )* + { if( buildDescr ) { + if ( inDescrBuilder == null ) { + $result = new AnnotationDescr( n ); + } else { + annoBuilder = inDescrBuilder instanceof AnnotationDescrBuilder ? + ((AnnotationDescrBuilder) inDescrBuilder).newAnnotation( n ) : inDescrBuilder.newAnnotation( n ); + $result = (AnnotationDescr) annoBuilder.getDescr(); + } + } + } + annotationArgs[result, annoBuilder] + ; + +annotationArgs [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] + : LEFT_PAREN + ( + (ID EQUALS_ASSIGN) => annotationElementValuePairs[descr, inDescrBuilder] + | value=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setValue( $value.result ); } } + )? + RIGHT_PAREN + ; + +annotationElementValuePairs [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] + : annotationElementValuePair[descr, inDescrBuilder] ( COMMA annotationElementValuePair[descr, inDescrBuilder] )* + ; + +annotationElementValuePair [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] + : key=ID EQUALS_ASSIGN val=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setKeyValue( $key.text, $val.result ); } } + ; + +annotationValue[AnnotatedDescrBuilder inDescrBuilder] returns [Object result] + : exp=expression { if ( buildDescr ) $result = $exp.text; } + | annos=annotationArray[inDescrBuilder] { if ( buildDescr ) $result = $annos.result.toArray(); } + | anno=fullAnnotation[inDescrBuilder] { if ( buildDescr ) $result = $anno.result; } + ; + +annotationArray[AnnotatedDescrBuilder inDescrBuilder] returns [java.util.List result] +@init { $result = new java.util.ArrayList();} + : LEFT_CURLY ( anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } + ( COMMA anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } )* )? + RIGHT_CURLY + ; + + + +conditionalOrExpression returns [BaseDescr result] + : left=conditionalAndExpression { if( buildDescr ) { $result = $left.result; } } + ( DOUBLE_PIPE + { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } + args=fullAnnotation[null]? right=conditionalAndExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newOr(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + if ( args != null ) { descr.addAnnotation( $args.result ); } + $result = descr; + } + } + )* + ; + +conditionalAndExpression returns [BaseDescr result] + : left=inclusiveOrExpression { if( buildDescr ) { $result = $left.result; } } + ( DOUBLE_AMPER + { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } + args=fullAnnotation[null]? right=inclusiveOrExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newAnd(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + if ( args != null ) { descr.addAnnotation( $args.result ); } + $result = descr; + } + } + )* + ; + +inclusiveOrExpression returns [BaseDescr result] + : left=exclusiveOrExpression { if( buildDescr ) { $result = $left.result; } } + ( PIPE right=exclusiveOrExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newIncOr(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + $result = descr; + } + } + )* + ; + +exclusiveOrExpression returns [BaseDescr result] + : left=andExpression { if( buildDescr ) { $result = $left.result; } } + ( XOR right=andExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newXor(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + $result = descr; + } + } + )* + ; + +andExpression returns [BaseDescr result] + : left=equalityExpression { if( buildDescr ) { $result = $left.result; } } + ( AMPER right=equalityExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newIncAnd(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + $result = descr; + } + } + )* + ; + +equalityExpression returns [BaseDescr result] + : left=instanceOfExpression { if( buildDescr ) { $result = $left.result; } } + ( ( op=EQUALS | op=NOT_EQUALS ) + { helper.setHasOperator( true ); + if( input.LA( 1 ) != DRL6Lexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + right=instanceOfExpression + { if( buildDescr ) { + $result = new RelationalExprDescr( $op.text, false, null, $left.result, $right.result ); + } + } + )* + ; + +instanceOfExpression returns [BaseDescr result] + : left=inExpression { if( buildDescr ) { $result = $left.result; } } + ( op=instanceof_key + { helper.setHasOperator( true ); + if( input.LA( 1 ) != DRL6Lexer.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) ); + } + } + )? + ; + +inExpression returns [BaseDescr result] +@init { ConstraintConnectiveDescr descr = null; BaseDescr leftDescr = null; BindingDescr binding = null; } +@after { if( binding != null && descr != null ) descr.addOrMerge( binding ); } + : left=relationalExpression + { if( buildDescr ) { $result = $left.result; } + if( $left.result instanceof BindingDescr ) { + binding = (BindingDescr)$left.result; + leftDescr = new AtomicExprDescr( binding.getExpression() ); + } else { + leftDescr = $left.result; + } + } + ((not_key in_key)=> not_key in=in_key LEFT_PAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + e1=expression + { descr = ConstraintConnectiveDescr.newAnd(); + RelationalExprDescr rel = new RelationalExprDescr( "!=", false, null, leftDescr, $e1.result ); + descr.addOrMerge( rel ); + $result = descr; + } + (COMMA e2=expression + { RelationalExprDescr rel = new RelationalExprDescr( "!=", false, null, leftDescr, $e2.result ); + descr.addOrMerge( rel ); + } + )* RIGHT_PAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } + | in=in_key LEFT_PAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + e1=expression + { descr = ConstraintConnectiveDescr.newOr(); + RelationalExprDescr rel = new RelationalExprDescr( "==", false, null, leftDescr, $e1.result ); + descr.addOrMerge( rel ); + $result = descr; + } + (COMMA e2=expression + { RelationalExprDescr rel = new RelationalExprDescr( "==", false, null, leftDescr, $e2.result ); + descr.addOrMerge( rel ); + } + )* RIGHT_PAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } + )? + ; + +relationalExpression returns [BaseDescr result] +scope { BaseDescr lsd; } +@init { $relationalExpression::lsd = null; } + : left=shiftExpression + { if( buildDescr ) { + if ( $left.result == null ) { + $result = new AtomicExprDescr( $left.text ); + } else if ( $left.result instanceof AtomicExprDescr ) { + if ( $left.text.equals(((AtomicExprDescr)$left.result).getExpression()) ) { + $result = $left.result; + } else { + $result = new AtomicExprDescr( $left.text ) ; + } + } else if ( $left.result instanceof BindingDescr ) { + if ( $left.text.equals(((BindingDescr)$left.result).getExpression()) ) { + $result = $left.result; + } else { + BindingDescr bind = (BindingDescr) $left.result; + int offset = bind.isUnification() ? 2 : 1; + String fullExpression = $left.text.substring( $left.text.indexOf( ":" ) + offset ).trim(); + $result = new BindingDescr( bind.getVariable(), bind.getExpression(), fullExpression, bind.isUnification() ); + } + } else { + $result = $left.result; + } + $relationalExpression::lsd = $result; + } + } + ( ( operator | LEFT_PAREN )=> right=orRestriction + { if( buildDescr ) { + $result = $right.result; + $relationalExpression::lsd = $result; + } + } + )* + ; + +orRestriction returns [BaseDescr result] + : left=andRestriction { if( buildDescr ) { $result = $left.result; } } + ( (DOUBLE_PIPE fullAnnotation[null]? andRestriction)=>lop=DOUBLE_PIPE args=fullAnnotation[null]? right=andRestriction + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newOr(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + if ( args != null ) { descr.addAnnotation( $args.result ); } + $result = descr; + } + } + )* EOF? + ; + +andRestriction returns [BaseDescr result] + : left=singleRestriction { if( buildDescr ) { $result = $left.result; } } + ( (DOUBLE_AMPER fullAnnotation[null]? operator)=>lop=DOUBLE_AMPER + { 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 ( args != null ) { descr.addAnnotation( $args.result ); } + $result = descr; + } + } + )* + ; + +singleRestriction returns [BaseDescr result] + : op=operator + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + ( (squareArguments shiftExpression)=> sa=squareArguments value=shiftExpression + | value=shiftExpression + ) + { if( buildDescr ) { + BaseDescr descr = ( $value.result != null && + ( (!($value.result instanceof AtomicExprDescr)) || + ($value.text.equals(((AtomicExprDescr)$value.result).getExpression())) )) ? + $value.result : + new AtomicExprDescr( $value.text ) ; + $result = new RelationalExprDescr( $op.opr, $op.negated, $sa.args, $relationalExpression::lsd, descr ); + if( $relationalExpression::lsd instanceof BindingDescr ) { + $relationalExpression::lsd = new AtomicExprDescr( ((BindingDescr)$relationalExpression::lsd).getExpression() ); + } + } + helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); + } + | LEFT_PAREN or=orRestriction RIGHT_PAREN { $result = $or.result; } + ; + + + +shiftExpression returns [BaseDescr result] + : left=additiveExpression { if( buildDescr ) { $result = $left.result; } } + ( (shiftOp)=>shiftOp additiveExpression )* + ; + +shiftOp + : ( LESS LESS + | GREATER GREATER GREATER + | GREATER GREATER ) + ; + +additiveExpression returns [BaseDescr result] + : left=multiplicativeExpression { if( buildDescr ) { $result = $left.result; } } + ( (PLUS|MINUS)=> (PLUS | MINUS) multiplicativeExpression )* + ; + +multiplicativeExpression returns [BaseDescr result] + : left=unaryExpression { if( buildDescr ) { $result = $left.result; } } + ( ( STAR | DIV | MOD ) unaryExpression )* + ; + +unaryExpression returns [BaseDescr result] + : PLUS ue=unaryExpression + { if( buildDescr ) { + $result = $ue.result; + if( $result instanceof AtomicExprDescr ) { + ((AtomicExprDescr)$result).setExpression( "+" + ((AtomicExprDescr)$result).getExpression() ); + } + } } + | MINUS ue=unaryExpression + { if( buildDescr ) { + $result = $ue.result; + if( $result instanceof AtomicExprDescr ) { + ((AtomicExprDescr)$result).setExpression( "-" + ((AtomicExprDescr)$result).getExpression() ); + } + } } + | INCR primary + | DECR primary + | left=unaryExpressionNotPlusMinus { if( buildDescr ) { $result = $left.result; } } + ; + +unaryExpressionNotPlusMinus returns [BaseDescr result] +@init { boolean isLeft = false; BindingDescr bind = null;} + : TILDE unaryExpression + | NEGATION ue=unaryExpression + { + if( buildDescr && ue != null ) { + $result = ue.negate(); + } + } + | (castExpression)=>castExpression + | (backReferenceExpression)=>backReferenceExpression + | { isLeft = helper.getLeftMostExpr() == null;} + ( ({inMap == 0 && ternOp == 0 && input.LA(2) == DRL6Lexer.COLON}? (var=ID COLON + { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($COLON, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, false); helper.setStart( bind, $var ); } } )) + | ({inMap == 0 && ternOp == 0 && input.LA(2) == DRL6Lexer.UNIFY}? (var=ID UNIFY + { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($UNIFY, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, true); helper.setStart( bind, $var ); } } )) + )? + + ( (xpathSeparator ID)=>left2=xpathPrimary { if( buildDescr ) { $result = $left2.result; } } + | left1=primary { if( buildDescr ) { $result = $left1.result; } } + ) + + ((selector)=>selector)* + { + if( buildDescr ) { + String expr = $unaryExpressionNotPlusMinus.text; + if( isLeft ) { + helper.setLeftMostExpr( expr ); + } + if( bind != null ) { + if( bind.isUnification() ) { + expr = expr.substring( expr.indexOf( ":=" ) + 2 ).trim(); + } else { + expr = expr.substring( expr.indexOf( ":" ) + 1 ).trim(); + } + bind.setExpressionAndBindingField( expr ); + helper.setEnd( bind ); + $result = bind; + } + } + } + ((INCR|DECR)=> (INCR|DECR))? + ; + +castExpression + : (LEFT_PAREN primitiveType) => LEFT_PAREN primitiveType RIGHT_PAREN expr=unaryExpression + | (LEFT_PAREN type) => LEFT_PAREN type RIGHT_PAREN unaryExpressionNotPlusMinus + ; + +backReferenceExpression + : (DOT DOT DIV) => (DOT DOT DIV)+ unaryExpressionNotPlusMinus + ; + +primitiveType + : boolean_key + | char_key + | byte_key + | short_key + | int_key + | long_key + | float_key + | double_key + ; + +xpathSeparator + : DIV + | QUESTION_DIV + ; + +xpathPrimary returns [BaseDescr result] + : xpathChunk ({notStartWithNewline()}? xpathChunk)* + ; + +xpathChunk returns [BaseDescr result] + : (xpathSeparator ID)=> xpathSeparator ID (DOT ID)* (HASH ID)? (LEFT_SQUARE xpathExpressionList RIGHT_SQUARE)? + ; + +xpathExpressionList returns [java.util.List exprs] +@init { $exprs = new java.util.ArrayList();} + : f=expression { $exprs.add( $f.text ); } + (COMMA s=expression { $exprs.add( $s.text ); })* + ; + +primary returns [BaseDescr result] + : (LEFT_PAREN)=> expr=parExpression { if( buildDescr ) { $result = $expr.result; } } + | (nonWildcardTypeArguments)=> nonWildcardTypeArguments (explicitGenericInvocationSuffix | this_key arguments) + | (literal)=> literal { if( buildDescr ) { $result = new AtomicExprDescr( $literal.text, true ); } } + //| this_key ({!helper.validateSpecialID(2)}?=> DOT ID)* ({helper.validateIdentifierSufix()}?=> identifierSuffix)? + | (super_key)=> super_key superSuffix + | (new_key)=> new_key creator + | (primitiveType)=> primitiveType (LEFT_SQUARE RIGHT_SQUARE)* DOT class_key + //| void_key DOT class_key + | (inlineMapExpression)=> inlineMapExpression + | (inlineListExpression)=> inlineListExpression + | (ID)=>i1=ID { helper.emit($i1, DroolsEditorType.IDENTIFIER); } + ( + ( (DOT ID)=>d=DOT i2=ID { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + | + ( ((DOT|NULL_SAFE_DOT) LEFT_PAREN)=>d=(DOT|NULL_SAFE_DOT) LEFT_PAREN { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($LEFT_PAREN, DroolsEditorType.SYMBOL); } + expression (COMMA { helper.emit($COMMA, DroolsEditorType.SYMBOL); } expression)* + RIGHT_PAREN { helper.emit($RIGHT_PAREN, DroolsEditorType.SYMBOL); } + ) + | + ( (HASH ID)=>h=HASH i2=ID { helper.emit($h, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + | + ( (NULL_SAFE_DOT ID)=>n=NULL_SAFE_DOT i2=ID { helper.emit($n, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + )* ((identifierSuffix)=>identifierSuffix)? + ; + +inlineListExpression + : LEFT_SQUARE expressionList? RIGHT_SQUARE + ; + +inlineMapExpression +@init{ inMap++; } + : LEFT_SQUARE mapExpressionList RIGHT_SQUARE + ; +finally { inMap--; } + +mapExpressionList + : mapEntry (COMMA mapEntry)* + ; + +mapEntry + : expression COLON expression + ; + +parExpression returns [BaseDescr result] + : LEFT_PAREN expr=expression RIGHT_PAREN + { if( buildDescr ) { + $result = $expr.result; + if( $result instanceof AtomicExprDescr ) { + ((AtomicExprDescr)$result).setExpression("(" +((AtomicExprDescr)$result).getExpression() + ")" ); + } + } + } + ; + +identifierSuffix + : (LEFT_SQUARE RIGHT_SQUARE)=>(LEFT_SQUARE { helper.emit($LEFT_SQUARE, DroolsEditorType.SYMBOL); } + RIGHT_SQUARE { helper.emit($RIGHT_SQUARE, DroolsEditorType.SYMBOL); } )+ + DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } class_key + | ((LEFT_SQUARE) => LEFT_SQUARE { helper.emit($LEFT_SQUARE, DroolsEditorType.SYMBOL); } + expression + RIGHT_SQUARE { helper.emit($RIGHT_SQUARE, DroolsEditorType.SYMBOL); } )+ // can also be matched by selector, but do here + | arguments +// | DOT class_key +// | DOT explicitGenericInvocation +// | DOT this_key +// | DOT super_key arguments +// | DOT new_key (nonWildcardTypeArguments)? innerCreator + ; + +creator + : nonWildcardTypeArguments? createdName + (arrayCreatorRest | classCreatorRest) + ; + +createdName + : ID typeArguments? + ( DOT ID typeArguments?)* + | primitiveType + ; + +innerCreator + : {!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}?=> ID classCreatorRest + ; + +arrayCreatorRest + : LEFT_SQUARE + ( RIGHT_SQUARE (LEFT_SQUARE RIGHT_SQUARE)* arrayInitializer + | expression RIGHT_SQUARE ({!helper.validateLT(2,"]")}?=>LEFT_SQUARE expression RIGHT_SQUARE)* ((LEFT_SQUARE RIGHT_SQUARE)=> LEFT_SQUARE RIGHT_SQUARE)* + ) + ; + +variableInitializer + : arrayInitializer + | expression + ; + +arrayInitializer + : LEFT_CURLY (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RIGHT_CURLY + ; + +classCreatorRest + : arguments //classBody? //sotty: restored classBody to allow for inline, anonymous classes + ; + +explicitGenericInvocation + : nonWildcardTypeArguments arguments + ; + +nonWildcardTypeArguments + : LESS typeList GREATER + ; + +explicitGenericInvocationSuffix + : super_key superSuffix + | ID arguments + ; + +selector + : (DOT super_key)=>DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } super_key superSuffix + | (DOT new_key)=>DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } new_key (nonWildcardTypeArguments)? innerCreator + | (DOT ID)=>DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } + ID { helper.emit($ID, DroolsEditorType.IDENTIFIER); } + ((LEFT_PAREN) => arguments)? + | (NULL_SAFE_DOT ID)=>NULL_SAFE_DOT { helper.emit($NULL_SAFE_DOT, DroolsEditorType.SYMBOL); } + ID { helper.emit($ID, DroolsEditorType.IDENTIFIER); } + ((LEFT_PAREN) => arguments)? + //| DOT this_key + | (LEFT_SQUARE)=>LEFT_SQUARE { helper.emit($LEFT_SQUARE, DroolsEditorType.SYMBOL); } + expression + RIGHT_SQUARE { helper.emit($RIGHT_SQUARE, DroolsEditorType.SYMBOL); } + ; + +superSuffix + : arguments + | DOT ID ((LEFT_PAREN) => arguments)? + ; + +squareArguments returns [java.util.List args] + : LEFT_SQUARE (el=expressionList { $args = $el.exprs; })? RIGHT_SQUARE + ; + +arguments + : LEFT_PAREN { helper.emit($LEFT_PAREN, DroolsEditorType.SYMBOL); } + expressionList? + RIGHT_PAREN { helper.emit($RIGHT_PAREN, DroolsEditorType.SYMBOL); } + ; + +expressionList returns [java.util.List exprs] +@init { $exprs = new java.util.ArrayList();} + : f=expression { $exprs.add( $f.text ); } + (COMMA s=expression { $exprs.add( $s.text ); })* + ; + +assignmentOperator + : EQUALS_ASSIGN + | PLUS_ASSIGN + | MINUS_ASSIGN + | MULT_ASSIGN + | DIV_ASSIGN + | AND_ASSIGN + | OR_ASSIGN + | XOR_ASSIGN + | MOD_ASSIGN + | LESS LESS EQUALS_ASSIGN + | (GREATER GREATER GREATER)=> GREATER GREATER GREATER EQUALS_ASSIGN + | (GREATER GREATER)=> GREATER GREATER EQUALS_ASSIGN + ; + +// -------------------------------------------------------- +// KEYWORDS +// -------------------------------------------------------- +extends_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.EXTENDS))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +super_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.SUPER))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +instanceof_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +boolean_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.BOOLEAN))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +char_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.CHAR))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +byte_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.BYTE))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +short_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.SHORT))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +int_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.INT))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +float_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.FLOAT))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +long_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.LONG))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +double_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.DOUBLE))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +void_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.VOID))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +this_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.THIS))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +class_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.CLASS))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +new_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.NEW))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +not_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.NOT))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +in_key + : {(helper.validateIdentifierKey(DroolsSoftKeywords.IN))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +operator_key + : {(helper.isPluggableEvaluator(false))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; + +neg_operator_key + : {(helper.isPluggableEvaluator(true))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java new file mode 100644 index 00000000000..ba811347b29 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java @@ -0,0 +1,54 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.parser; + +import java.util.LinkedList; +import java.util.List; + +import org.antlr.runtime.Parser; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.RecognizerSharedState; +import org.antlr.runtime.TokenStream; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.parser.DroolsParserException; + +public abstract class DRLExpressions extends Parser { + public DRLExpressions(TokenStream input, RecognizerSharedState state) { + super(input, state); + } + + public abstract void setBuildDescr( boolean build ); + public abstract boolean isBuildDescr(); + + public abstract void setLeftMostExpr( String value ); + public abstract String getLeftMostExpr(); + + public abstract void setHasBindings( boolean value ); + public abstract boolean hasBindings(); + + public abstract BaseDescr conditionalOrExpression() throws RecognitionException; + + public abstract ParserHelper getHelper(); + public abstract boolean hasErrors(); + public abstract List getErrors(); + public abstract List getErrorMessages(); + public abstract void enableEditorInterface(); + public abstract void disableEditorInterface(); + public abstract LinkedList getEditorInterface(); +} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java new file mode 100644 index 00000000000..7d624224cb5 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java @@ -0,0 +1,88 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.parser; + +import java.util.Collections; +import java.util.List; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.RecognizerSharedState; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.lang.ParserHelper; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * This is a helper class that provides helper methods to parse expressions + * using both the DRLExpressions parser and the DRLExprTree parser. + */ +public class DrlExprParser { + + private ParserHelper helper = null; + + private final LanguageLevelOption languageLevel; + + public DrlExprParser(LanguageLevelOption languageLevel) { + this.languageLevel = languageLevel; + } + + /** Parse an expression from text */ + public ConstraintConnectiveDescr parse( final String text ) { + ConstraintConnectiveDescr constraint = null; + try { + DRLLexer lexer = DRLFactory.getDRLLexer(new ANTLRStringStream(text), languageLevel); + CommonTokenStream input = new CommonTokenStream( lexer ); + RecognizerSharedState state = new RecognizerSharedState(); + helper = new ParserHelper( input, state, languageLevel ); + DRLExpressions parser = DRLFactory.getDRLExpressions(input, state, helper, languageLevel); + parser.setBuildDescr( true ); + parser.setLeftMostExpr( null ); // setting initial value just in case + BaseDescr expr = parser.conditionalOrExpression(); + if ( expr != null && !parser.hasErrors() ) { + constraint = ConstraintConnectiveDescr.newAnd(); + constraint.addOrMerge( expr ); + } + } catch ( RecognitionException e ) { + helper.reportError( e ); + } + return constraint; + } + + public String getLeftMostExpr() { + return helper != null ? helper.getLeftMostExpr() : null; + } + + /** + * @return true if there were parser errors. + */ + public boolean hasErrors() { + return helper != null && helper.hasErrors(); + } + + /** + * @return a list of errors found while parsing. + */ + @SuppressWarnings("unchecked") + public List getErrors() { + return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; + } + +} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java new file mode 100644 index 00000000000..f94eab73ccc --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java @@ -0,0 +1,380 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.parser; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.antlr.runtime.BitSet; +import org.antlr.runtime.EarlyExitException; +import org.antlr.runtime.FailedPredicateException; +import org.antlr.runtime.MismatchedNotSetException; +import org.antlr.runtime.MismatchedSetException; +import org.antlr.runtime.MismatchedTokenException; +import org.antlr.runtime.MismatchedTreeNodeException; +import org.antlr.runtime.NoViableAltException; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.Token; +import org.drools.drl.parser.DRLFactory; +import org.drools.drl.parser.DroolsParserException; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * Helper class that generates DroolsParserException with user friendly error + * messages. + * + * @see DroolsParserException + */ +public class DroolsParserExceptionFactory { + public final static String MISMATCHED_TOKEN_MESSAGE_COMPLETE = "Line %1$d:%2$d mismatched input '%3$s' expecting '%4$s'%5$s"; + public final static String MISMATCHED_TOKEN_MESSAGE_PART = "Line %1$d:%2$d mismatched input '%3$s'%4$s"; + public final static String MISMATCHED_TREE_NODE_MESSAGE_COMPLETE = "Line %1$d:%2$d mismatched tree node '%3$s' expecting '%4$s'%5$s"; + public final static String MISMATCHED_TREE_NODE_MESSAGE_PART = "Line %1$d:%2$d mismatched tree node '%3$s'%4$s"; + public final static String NO_VIABLE_ALT_MESSAGE = "Line %1$d:%2$d no viable alternative at input '%3$s'%4$s"; + public final static String EARLY_EXIT_MESSAGE = "Line %1$d:%2$d required (...)+ loop did not match anything at input '%3$s'%4$s"; + public final static String MISMATCHED_SET_MESSAGE = "Line %1$d:%2$d mismatched input '%3$s' expecting one of the following tokens: '%4$s'%5$s."; + public final static String MISMATCHED_NOT_SET_MESSAGE = "Line %1$d:%2$d mismatched input '%3$s' not expecting any of the following tokens: '%4$s'%5$s"; + public final static String FAILED_PREDICATE_MESSAGE = "Line %1$d:%2$d rule '%3$s' failed predicate: {%4$s}?%5$s"; + public final static String TRAILING_SEMI_COLON_NOT_ALLOWED_MESSAGE = "Line %1$d:%2$d trailing semi-colon not allowed%3$s"; + public final static String PARSER_LOCATION_MESSAGE_COMPLETE = " in %1$s %2$s"; + public final static String PARSER_LOCATION_MESSAGE_PART = " in %1$s"; + public final static String UNEXPECTED_EXCEPTION = "Line %1$d:%2$d unexpected exception at input '%3$s'. Exception: %4$s. Stack trace:\n %5$s"; + + private final Collection> paraphrases; + + // TODO: need to deal with this array + private String[] tokenNames = null; + + private final LanguageLevelOption languageLevel; + + /** + * DroolsParserErrorMessages constructor. + * + * @param tokenNames + * tokenNames generated by ANTLR + * @param paraphrases + * paraphrases parser structure + */ + public DroolsParserExceptionFactory(Collection> paraphrases, + LanguageLevelOption languageLevel) { + this.paraphrases = paraphrases; + this.languageLevel = languageLevel; + } + + /** + * This method creates a DroolsParserException for trailing semicolon + * exception, full of information. + * + * @param line + * line number + * @param column + * column position + * @param offset + * char offset + * @return DroolsParserException filled. + */ + public DroolsParserException createTrailingSemicolonException( int line, + int column, + int offset ) { + String message = String + .format( + TRAILING_SEMI_COLON_NOT_ALLOWED_MESSAGE, + line, + column, + formatParserLocation() ); + + return new DroolsParserException( "ERR 104", + message, + line, + column, + offset, + null ); + } + + /** + * This method creates a DroolsParserException full of information. + * + * @param e + * original exception + * @return DroolsParserException filled. + */ + public DroolsParserException createDroolsException( RecognitionException e ) { + List codeAndMessage = createErrorMessage( e ); + return new DroolsParserException( codeAndMessage.get( 1 ), + codeAndMessage + .get( 0 ), + e.line, + e.charPositionInLine, + e.index, + e ); + } + + /** + * This will take a RecognitionException, and create a sensible error + * message out of it + */ + private List createErrorMessage( RecognitionException e ) { + List codeAndMessage = new ArrayList<>( 2 ); + String message; + if ( e instanceof MismatchedTokenException ) { + MismatchedTokenException mte = (MismatchedTokenException) e; + String expecting = mte instanceof DroolsMismatchedTokenException ? ((DroolsMismatchedTokenException)mte).getTokenText() : getBetterToken( mte.expecting ); + if ( tokenNames != null && mte.expecting >= 0 && mte.expecting < tokenNames.length ) { + message = String + .format( + MISMATCHED_TOKEN_MESSAGE_COMPLETE, + e.line, + e.charPositionInLine, + getBetterToken( e.token ), + expecting, + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 102" ); + } else { + message = String + .format( + MISMATCHED_TOKEN_MESSAGE_PART, + e.line, + e.charPositionInLine, + getBetterToken( e.token ), + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 102" ); + } + } else if ( e instanceof MismatchedTreeNodeException ) { + MismatchedTreeNodeException mtne = (MismatchedTreeNodeException) e; + if ( mtne.expecting >= 0 && mtne.expecting < tokenNames.length ) { + message = String + .format( + MISMATCHED_TREE_NODE_MESSAGE_COMPLETE, + e.line, + e.charPositionInLine, + getBetterToken( e.token ), + getBetterToken( mtne.expecting ), + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 106" ); + } else { + message = String + .format( + MISMATCHED_TREE_NODE_MESSAGE_PART, + e.line, + e.charPositionInLine, + getBetterToken( e.token ), + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 106" ); + } + } else if ( e instanceof NoViableAltException ) { + // NoViableAltException nvae = (NoViableAltException) e; + message = String.format( + NO_VIABLE_ALT_MESSAGE, + e.line, + e.charPositionInLine, + getBetterToken( e.token ), + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 101" ); + } else if ( e instanceof EarlyExitException ) { + // EarlyExitException eee = (EarlyExitException) e; + message = String.format( + EARLY_EXIT_MESSAGE, + e.line, + e.charPositionInLine, + getBetterToken( e.token ), + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 105" ); + } else if ( e instanceof MismatchedSetException ) { + MismatchedSetException mse = (MismatchedSetException) e; + String expected = expectedTokensAsString( mse.expecting ); + message = String.format( + MISMATCHED_SET_MESSAGE, + e.line, + e.charPositionInLine, + getBetterToken( e.token ), + expected, + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 107" ); + } else if ( e instanceof DroolsMismatchedSetException ) { + DroolsMismatchedSetException mse = (DroolsMismatchedSetException) e; + String expected = Arrays.asList( mse.getTokenText() ).toString(); + message = String.format( + MISMATCHED_SET_MESSAGE, + e.line, + e.charPositionInLine, + getBetterToken( e.token ), + expected, + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 107" ); + } else if ( e instanceof MismatchedNotSetException ) { + MismatchedNotSetException mse = (MismatchedNotSetException) e; + String expected = expectedTokensAsString( mse.expecting ); + message = String.format( + MISMATCHED_NOT_SET_MESSAGE, + e.line, + e.charPositionInLine, + getBetterToken( e.token ), + expected, + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 108" ); + } else if ( e instanceof FailedPredicateException ) { + FailedPredicateException fpe = (FailedPredicateException) e; + message = String.format( + FAILED_PREDICATE_MESSAGE, + e.line, + e.charPositionInLine, + fpe.ruleName, + fpe.predicateText, + formatParserLocation() ); + codeAndMessage.add( message ); + codeAndMessage.add( "ERR 103" ); + } + if ( codeAndMessage.get( 0 ).length() == 0 ) { + codeAndMessage.add( "?????" ); + } + return codeAndMessage; + } + + public DroolsParserException createDroolsException( Exception e, + Token token ) { + StringWriter sw = new StringWriter(); + e.printStackTrace( new PrintWriter(sw) ); + return new DroolsParserException( String.format( + DroolsParserExceptionFactory.UNEXPECTED_EXCEPTION, + token.getLine(), + token.getCharPositionInLine(), + getBetterToken( token ), + e.toString(), + sw.toString() ), + e ); + + } + + private String expectedTokensAsString( BitSet set ) { + StringBuilder buf = new StringBuilder(); + buf.append( "{ " ); + int i = 0; + for ( int token : set.toArray() ) { + if ( i > 0 ) buf.append( ", " ); + buf.append( getBetterToken( token ) ); + i++; + } + buf.append( " }" ); + return buf.toString(); + } + + /** + * This will take Paraphrases stack, and create a sensible location + */ + private String formatParserLocation() { + StringBuilder sb = new StringBuilder(); + if ( paraphrases != null ) { + for ( Map map : paraphrases ) { + for ( Entry activeEntry : map.entrySet() ) { + if ( activeEntry.getValue().length() == 0 ) { + String kStr = getLocationName( activeEntry.getKey() ); + if( kStr.length() > 0 ){ + sb.append( String.format( PARSER_LOCATION_MESSAGE_PART, kStr ) ); + } + } else { + sb.append( String.format( PARSER_LOCATION_MESSAGE_COMPLETE, + getLocationName( activeEntry.getKey() ), + activeEntry.getValue() ) ); + } + } + } + } + return sb.toString(); + } + + /** + * Returns a string based on Paraphrase Type + * + * @param type + * Paraphrase Type + * @return a string representing the + */ + private String getLocationName( DroolsParaphraseTypes type ) { + switch ( type ) { + case PACKAGE : + return "package"; + case IMPORT : + return "import"; + case FUNCTION_IMPORT : + return "function import"; + case ACCUMULATE_IMPORT : + return "accumulate import"; + case GLOBAL : + return "global"; + case FUNCTION : + return "function"; + case QUERY : + return "query"; + case TEMPLATE : + return "template"; + case RULE : + return "rule"; + case RULE_ATTRIBUTE : + return "rule attribute"; + case PATTERN : + return "pattern"; + case EVAL : + return "eval"; + default : + return ""; + } + } + + /** + * Helper method that creates a user friendly token definition + * + * @param token + * token + * @return user friendly token definition + */ + private String getBetterToken( Token token ) { + if ( token == null ) { + return ""; + } + return DRLFactory.getBetterToken(token.getType(), token.getText(), languageLevel); + } + + /** + * Helper method that creates a user friendly token definition + * + * @param tokenType + * token type + * @return user friendly token definition + */ + private String getBetterToken( int tokenType ) { + return DRLFactory.getBetterToken( tokenType, null, languageLevel ); + } + + +} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java new file mode 100644 index 00000000000..94e5e2f76ce --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java @@ -0,0 +1,672 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.drools.parser; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.antlr.runtime.CommonToken; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.RecognizerSharedState; +import org.antlr.runtime.Token; +import org.antlr.runtime.TokenStream; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.dsl.AbstractClassTypeDeclarationBuilder; +import org.drools.drl.ast.dsl.AccumulateDescrBuilder; +import org.drools.drl.ast.dsl.AccumulateImportDescrBuilder; +import org.drools.drl.ast.dsl.AttributeDescrBuilder; +import org.drools.drl.ast.dsl.AttributeSupportBuilder; +import org.drools.drl.ast.dsl.BehaviorDescrBuilder; +import org.drools.drl.ast.dsl.CEDescrBuilder; +import org.drools.drl.ast.dsl.CollectDescrBuilder; +import org.drools.drl.ast.dsl.ConditionalBranchDescrBuilder; +import org.drools.drl.ast.dsl.DeclareDescrBuilder; +import org.drools.drl.ast.dsl.DescrBuilder; +import org.drools.drl.ast.dsl.DescrFactory; +import org.drools.drl.ast.dsl.EntryPointDeclarationDescrBuilder; +import org.drools.drl.ast.dsl.EnumDeclarationDescrBuilder; +import org.drools.drl.ast.dsl.EnumLiteralDescrBuilder; +import org.drools.drl.ast.dsl.EvalDescrBuilder; +import org.drools.drl.ast.dsl.FieldDescrBuilder; +import org.drools.drl.ast.dsl.ForallDescrBuilder; +import org.drools.drl.ast.dsl.FunctionDescrBuilder; +import org.drools.drl.ast.dsl.GlobalDescrBuilder; +import org.drools.drl.ast.dsl.GroupByDescrBuilder; +import org.drools.drl.ast.dsl.ImportDescrBuilder; +import org.drools.drl.ast.dsl.NamedConsequenceDescrBuilder; +import org.drools.drl.ast.dsl.PackageDescrBuilder; +import org.drools.drl.ast.dsl.PatternContainerDescrBuilder; +import org.drools.drl.ast.dsl.PatternDescrBuilder; +import org.drools.drl.ast.dsl.QueryDescrBuilder; +import org.drools.drl.ast.dsl.RuleDescrBuilder; +import org.drools.drl.ast.dsl.TypeDeclarationDescrBuilder; +import org.drools.drl.ast.dsl.UnitDescrBuilder; +import org.drools.drl.ast.dsl.WindowDeclarationDescrBuilder; +import org.drools.drl.parser.DroolsParserException; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * This is a class to hold all the helper functions/methods used + * by the DRL parser + */ +public class ParserHelper { + public final String[] statementKeywords = new String[]{ + DroolsSoftKeywords.PACKAGE, + DroolsSoftKeywords.UNIT, + DroolsSoftKeywords.IMPORT, + DroolsSoftKeywords.GLOBAL, + DroolsSoftKeywords.DECLARE, + DroolsSoftKeywords.FUNCTION, + DroolsSoftKeywords.RULE, + DroolsSoftKeywords.QUERY + }; + + public List errors = new ArrayList<>(); + public LinkedList editorInterface = null; + public boolean isEditorInterfaceEnabled = false; + private Deque> paraphrases = new ArrayDeque<>(); + + // parameters from parser + private DroolsParserExceptionFactory errorMessageFactory = null; + private TokenStream input = null; + private RecognizerSharedState state = null; + + private String leftMostExpr = null; + + // helper attribute + private boolean hasOperator = false; + + private final LanguageLevelOption languageLevel; + + public ParserHelper(TokenStream input, + RecognizerSharedState state, + LanguageLevelOption languageLevel) { + this.errorMessageFactory = new DroolsParserExceptionFactory( paraphrases, languageLevel ); + this.input = input; + this.state = state; + this.languageLevel = languageLevel; + } + + public LinkedList getEditorInterface() { + return editorInterface; + } + + public void setLeftMostExpr( String value ) { + this.leftMostExpr = value; + } + + public String getLeftMostExpr() { + return this.leftMostExpr; + } + + public void enableEditorInterface() { + isEditorInterfaceEnabled = true; + } + + public void disableEditorInterface() { + isEditorInterfaceEnabled = false; + } + + public void setHasOperator( boolean hasOperator ) { + this.hasOperator = hasOperator; + } + + public boolean getHasOperator() { + return hasOperator; + } + + public void beginSentence( DroolsSentenceType sentenceType ) { + if ( isEditorInterfaceEnabled ) { + if ( null == editorInterface ) { + editorInterface = new LinkedList<>(); + } + if (editorInterface.isEmpty()){ + DroolsSentence sentence = new DroolsSentence(); + sentence.setType( sentenceType ); + editorInterface.add( sentence ); + } + } + } + + public DroolsSentence getActiveSentence() { + return editorInterface.getLast(); + } + + public void emit( List< ? > tokens, + DroolsEditorType editorType ) { + if ( isEditorInterfaceEnabled && tokens != null ) { + for ( Object activeObject : tokens ) { + emit( (Token) activeObject, + editorType ); + } + } + } + + public void emit( Token token, + DroolsEditorType editorType ) { + if ( isEditorInterfaceEnabled && token != null && editorType != null ) { + ((DroolsToken) token).setEditorType( editorType ); + getActiveSentence().addContent( (DroolsToken) token ); + } + } + + public void emit( int activeContext ) { + if ( isEditorInterfaceEnabled ) { + getActiveSentence().addContent( activeContext ); + } + } + + public DroolsToken getLastTokenOnList( LinkedList< ? > list ) { + DroolsToken lastToken = null; + for ( Object object : list ) { + if ( object instanceof DroolsToken ) { + lastToken = (DroolsToken) object; + } + } + return lastToken; + } + + public String retrieveLT( int LTNumber ) { + if ( null == input ) return null; + if ( null == input.LT( LTNumber ) ) return null; + if ( null == input.LT( LTNumber ).getText() ) return null; + + return input.LT( LTNumber ).getText(); + } + + public boolean validateLT( int LTNumber, + String text ) { + String text2Validate = retrieveLT( LTNumber ); + return validateText( text, text2Validate ); + } + + private boolean validateText( String text, String text2Validate ) { + return text2Validate != null && text2Validate.equals( text ); + } + + public boolean isPluggableEvaluator( int offset, + boolean negated ) { + String text2Validate = retrieveLT( offset ); + return text2Validate != null && DroolsSoftKeywords.isOperator(text2Validate, negated); + } + + public boolean isPluggableEvaluator( boolean negated ) { + return isPluggableEvaluator( 1, + negated ); + } + + public boolean validateIdentifierKey( String text ) { + return validateLT( 1, + text ); + } + + public boolean validateCEKeyword( int index ) { + String text2Validate = retrieveLT( index ); + return validateText( text2Validate, + DroolsSoftKeywords.NOT ) || + validateText( text2Validate, + DroolsSoftKeywords.EXISTS ) || + validateText( text2Validate, + DroolsSoftKeywords.FORALL ) || + validateText( text2Validate, + DroolsSoftKeywords.AND ) || + validateText( text2Validate, + DroolsSoftKeywords.OR ) || + validateText( text2Validate, + DroolsSoftKeywords.COLLECT ) || + validateText( text2Validate, + DroolsSoftKeywords.FROM ) || + validateText( text2Validate, + DroolsSoftKeywords.END ) || + validateText( text2Validate, + DroolsSoftKeywords.EVAL ) || + validateText( text2Validate, + DroolsSoftKeywords.OVER ) || + validateText( text2Validate, + DroolsSoftKeywords.THEN ); + } + + public boolean validateStatement( int index ) { + boolean ret = false; + String text2Validate = retrieveLT( index ); + for ( String st : statementKeywords ) { + if ( validateText( text2Validate, + st ) ) { + ret = true; + break; + } + } + return ret || validateAttribute( index ); + } + + public boolean validateAttribute( int index ) { + String text2Validate = retrieveLT( index ); + return validateText( text2Validate, + DroolsSoftKeywords.SALIENCE ) || + validateText( text2Validate, + DroolsSoftKeywords.ENABLED ) || + (validateText( text2Validate, + DroolsSoftKeywords.NO ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.LOOP )) || + (validateText( text2Validate, + DroolsSoftKeywords.AUTO ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.FOCUS )) || + (validateText( text2Validate, + DroolsSoftKeywords.LOCK ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.ON ) && + validateLT( index + 3, + "-" ) && + validateLT( index + 4, + DroolsSoftKeywords.ACTIVE )) || + (validateText( text2Validate, + DroolsSoftKeywords.AGENDA ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.GROUP )) || + (validateText( text2Validate, + DroolsSoftKeywords.ACTIVATION ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.GROUP )) || + (validateText( text2Validate, + DroolsSoftKeywords.RULEFLOW ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.GROUP )) || + (validateText( text2Validate, + DroolsSoftKeywords.DATE ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.EFFECTIVE )) || + (validateText( text2Validate, + DroolsSoftKeywords.DATE ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.EXPIRES )) || + validateText( text2Validate, + DroolsSoftKeywords.DIALECT ) || + validateText( text2Validate, + DroolsSoftKeywords.CALENDARS ) || + validateText( text2Validate, + DroolsSoftKeywords.TIMER ) || + validateText( text2Validate, + DroolsSoftKeywords.DURATION ) || + validateText( text2Validate, + DroolsSoftKeywords.REFRACT ) || + validateText( text2Validate, + DroolsSoftKeywords.DIRECT ); + } + + public void reportError( RecognitionException ex ) { + // if we've already reported an error and have not matched a token + // yet successfully, don't report any errors. + if ( state.errorRecovery ) { + return; + } + state.errorRecovery = true; + + errors.add( errorMessageFactory.createDroolsException( ex ) ); + } + + public void reportError( Exception e ) { + try { + errors.add( errorMessageFactory.createDroolsException( e, + input.LT( 1 ) ) ); + } catch (Exception ignored) { + errors.add(new DroolsParserException( "Unexpected error: " + e.getMessage(), e )); + } + } + + /** return the raw DroolsParserException errors */ + public List getErrors() { + return errors; + } + + /** Return a list of pretty strings summarising the errors */ + public List getErrorMessages() { + List messages = new ArrayList<>( errors.size() ); + + for ( DroolsParserException activeException : errors ) { + messages.add( activeException.getMessage() ); + } + + return messages; + } + + /** return true if any parser errors were accumulated */ + public boolean hasErrors() { + return !errors.isEmpty(); + } + + /** + * Method that adds a paraphrase type into paraphrases stack. + * + * @param type + * paraphrase type + */ + public void pushParaphrases( DroolsParaphraseTypes type ) { + Map activeMap = new HashMap<>(); + activeMap.put( type, + "" ); + paraphrases.push( activeMap ); + } + + public Map popParaphrases() { + return paraphrases.pop(); + } + + /** + * Method that sets paraphrase value for a type into paraphrases stack. + * + * @param type + * paraphrase type + * @param value + * paraphrase value + */ + public void setParaphrasesValue( DroolsParaphraseTypes type, + String value ) { + paraphrases.peek().put( type, + value ); + } + + void setStart( DescrBuilder< ? , ? > db ) { + setStart( db, + input.LT( 1 ) ); + } + + void setStart( DescrBuilder< ? , ? > db, + Token first ) { + if ( db != null && first != null ) { + db.startCharacter( ((CommonToken) first).getStartIndex() ).startLocation( first.getLine(), + first.getCharPositionInLine() ); + } + } + + void setStart( BaseDescr descr, + Token first ) { + if ( descr != null && first != null ) { + descr.setLocation( first.getLine(), + first.getCharPositionInLine() ); + descr.setStartCharacter( ((CommonToken) first).getStartIndex() ); + } + } + + void setEnd( BaseDescr descr ) { + Token last = input.LT( -1 ); + if ( descr != null && last != null ) { + int endLocation = last.getText() != null ? last.getCharPositionInLine() + last.getText().length() - 1 : last.getCharPositionInLine(); + descr.setEndCharacter( ((CommonToken) last).getStopIndex() + 1 ); + descr.setEndLocation( last.getLine(), + endLocation ); + } + } + + void setEnd( DescrBuilder< ? , ? > db ) { + Token last = input.LT( -1 ); + if ( db != null && last != null ) { + int endLocation = last.getText() != null ? last.getCharPositionInLine() + last.getText().length() - 1 : last.getCharPositionInLine(); + db.endCharacter( ((CommonToken) last).getStopIndex() + 1 ).endLocation( last.getLine(), + endLocation ); + } + } + + @SuppressWarnings("unchecked") + public > T start( DescrBuilder< ? , ? > ctxBuilder, + Class clazz, + String param ) { + if ( state.backtracking == 0 ) { + if ( PackageDescrBuilder.class.isAssignableFrom( clazz ) ) { + pushParaphrases( DroolsParaphraseTypes.PACKAGE ); + beginSentence( DroolsSentenceType.PACKAGE ); + setStart( ctxBuilder ); + } else if ( ImportDescrBuilder.class.isAssignableFrom( clazz ) ) { + ImportDescrBuilder imp; + if ( validateLT( 2, + DroolsSoftKeywords.FUNCTION ) || + validateLT( 2, + DroolsSoftKeywords.STATIC ) ) { + imp = ctxBuilder == null ? + DescrFactory.newPackage().newFunctionImport() : + ((PackageDescrBuilder) ctxBuilder).newFunctionImport(); + } else { + imp = ctxBuilder == null ? + DescrFactory.newPackage().newImport() : + ((PackageDescrBuilder) ctxBuilder).newImport(); + } + pushParaphrases( DroolsParaphraseTypes.IMPORT ); + beginSentence( DroolsSentenceType.IMPORT_STATEMENT ); + setStart( imp ); + return (T) imp; + } else if ( UnitDescrBuilder.class.isAssignableFrom( clazz ) ) { + UnitDescrBuilder imp = ctxBuilder == null ? + DescrFactory.newPackage().newUnit() : + ((PackageDescrBuilder) ctxBuilder).newUnit(); + pushParaphrases( DroolsParaphraseTypes.UNIT ); + beginSentence( DroolsSentenceType.UNIT ); + setStart( imp ); + return (T) imp; + } else if ( AccumulateImportDescrBuilder.class.isAssignableFrom( clazz ) ) { + AccumulateImportDescrBuilder imp = ctxBuilder == null ? + DescrFactory.newPackage().newAccumulateImport() : + ((PackageDescrBuilder) ctxBuilder).newAccumulateImport(); + pushParaphrases( DroolsParaphraseTypes.ACCUMULATE_IMPORT ); + beginSentence( DroolsSentenceType.ACCUMULATE_IMPORT_STATEMENT ); + setStart( imp ); + return (T) imp; + } else if ( GlobalDescrBuilder.class.isAssignableFrom( clazz ) ) { + GlobalDescrBuilder global = ctxBuilder == null ? + DescrFactory.newPackage().newGlobal() : + ((PackageDescrBuilder) ctxBuilder).newGlobal(); + pushParaphrases( DroolsParaphraseTypes.GLOBAL ); + beginSentence( DroolsSentenceType.GLOBAL ); + setStart( global ); + return (T) global; + } else if ( DeclareDescrBuilder.class.isAssignableFrom( clazz ) ) { + DeclareDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare() : + ((PackageDescrBuilder) ctxBuilder).newDeclare(); + return (T) declare; + } else if ( TypeDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + TypeDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().type() : + ((DeclareDescrBuilder) ctxBuilder).type(); + pushParaphrases( DroolsParaphraseTypes.TYPE_DECLARE ); + beginSentence( DroolsSentenceType.TYPE_DECLARATION ); + setStart( declare ); + return (T) declare; + } else if ( EnumDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + EnumDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().enumerative() : + ((DeclareDescrBuilder) ctxBuilder).enumerative(); + pushParaphrases( DroolsParaphraseTypes.ENUM_DECLARE ); + beginSentence( DroolsSentenceType.ENUM_DECLARATION ); + setStart( declare ); + return (T) declare; + }else if ( EntryPointDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + EntryPointDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().entryPoint() : + ((DeclareDescrBuilder) ctxBuilder).entryPoint(); + pushParaphrases( DroolsParaphraseTypes.ENTRYPOINT_DECLARE ); + beginSentence( DroolsSentenceType.ENTRYPOINT_DECLARATION ); + setStart( declare ); + return (T) declare; + } else if ( WindowDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + WindowDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().window() : + ((DeclareDescrBuilder) ctxBuilder).window(); + pushParaphrases( DroolsParaphraseTypes.WINDOW_DECLARE ); + beginSentence( DroolsSentenceType.WINDOW_DECLARATION ); + setStart( declare ); + return (T) declare; + } else if ( FieldDescrBuilder.class.isAssignableFrom( clazz ) ) { + FieldDescrBuilder field = ((AbstractClassTypeDeclarationBuilder) ctxBuilder).newField( param ); + setStart( field ); + return (T) field; + } else if ( EnumLiteralDescrBuilder.class.isAssignableFrom( clazz ) ) { + EnumLiteralDescrBuilder literal = ((EnumDeclarationDescrBuilder) ctxBuilder).newEnumLiteral( param ); + setStart( literal ); + return (T) literal; + } else if ( FunctionDescrBuilder.class.isAssignableFrom( clazz ) ) { + FunctionDescrBuilder function; + if ( ctxBuilder == null ) { + function = DescrFactory.newPackage().newFunction(); + } else { + PackageDescrBuilder pkg = (PackageDescrBuilder) ctxBuilder; + function = pkg.newFunction().namespace( pkg.getDescr().getName() ); + AttributeDescr attribute = pkg.getDescr().getAttribute( "dialect" ); + if ( attribute != null ) { + function.dialect( attribute.getValue() ); + } + } + pushParaphrases( DroolsParaphraseTypes.FUNCTION ); + beginSentence( DroolsSentenceType.FUNCTION ); + setStart( function ); + return (T) function; + } else if ( RuleDescrBuilder.class.isAssignableFrom( clazz ) ) { + RuleDescrBuilder rule = ctxBuilder == null ? + DescrFactory.newPackage().newRule() : + ((PackageDescrBuilder) ctxBuilder).newRule(); + pushParaphrases( DroolsParaphraseTypes.RULE ); + beginSentence( DroolsSentenceType.RULE ); + setStart( rule ); + return (T) rule; + } else if ( QueryDescrBuilder.class.isAssignableFrom( clazz ) ) { + QueryDescrBuilder query = ctxBuilder == null ? + DescrFactory.newPackage().newQuery() : + ((PackageDescrBuilder) ctxBuilder).newQuery(); + pushParaphrases( DroolsParaphraseTypes.QUERY ); + beginSentence( DroolsSentenceType.QUERY ); + setStart( query ); + return (T) query; + } else if ( AttributeDescrBuilder.class.isAssignableFrom( clazz ) ) { + AttributeDescrBuilder< ? > attribute = ((AttributeSupportBuilder< ? >) ctxBuilder).attribute(param); + setStart( attribute ); + return (T) attribute; + } else if ( EvalDescrBuilder.class.isAssignableFrom( clazz ) ) { + EvalDescrBuilder< ? > eval = ((CEDescrBuilder< ? , ? >) ctxBuilder).eval(); + pushParaphrases( DroolsParaphraseTypes.EVAL ); + beginSentence( DroolsSentenceType.EVAL ); + setStart( eval ); + return (T) eval; + } else if ( ForallDescrBuilder.class.isAssignableFrom( clazz ) ) { + ForallDescrBuilder< ? > forall = ((CEDescrBuilder< ? , ? >) ctxBuilder).forall(); + setStart( forall ); + return (T) forall; + } else if ( CEDescrBuilder.class.isAssignableFrom( clazz ) ) { + setStart( ctxBuilder ); + return (T) ctxBuilder; + } else if ( PatternDescrBuilder.class.isAssignableFrom( clazz ) ) { + PatternDescrBuilder< ? > pattern = ((PatternContainerDescrBuilder< ? , ? >) ctxBuilder).pattern(); + pushParaphrases( DroolsParaphraseTypes.PATTERN ); + setStart( pattern ); + return (T) pattern; + } else if ( CollectDescrBuilder.class.isAssignableFrom( clazz ) ) { + CollectDescrBuilder< ? > collect = ((PatternDescrBuilder< ? >) ctxBuilder).from().collect(); + setStart( collect ); + return (T) collect; + } else if ( GroupByDescrBuilder.class.isAssignableFrom(clazz) ) { + // GroupBy extends Accumulate and thus need to be before it + GroupByDescrBuilder< ? > groupBy = ((PatternDescrBuilder< ? >) ctxBuilder).from().groupBy(); + setStart( groupBy ); + return (T) groupBy; + } else if ( AccumulateDescrBuilder.class.isAssignableFrom( clazz ) ) { + AccumulateDescrBuilder< ? > accumulate = ((PatternDescrBuilder< ? >) ctxBuilder).from().accumulate(); + setStart( accumulate ); + return (T) accumulate; + } else if ( BehaviorDescrBuilder.class.isAssignableFrom( clazz ) ) { + BehaviorDescrBuilder< ? > behavior = ((PatternDescrBuilder< ? >) ctxBuilder).behavior(); + setStart( behavior ); + return (T) behavior; + } else if ( NamedConsequenceDescrBuilder.class.isAssignableFrom( clazz ) ) { + NamedConsequenceDescrBuilder< ? > namedConsequence = ((CEDescrBuilder< ? , ? >) ctxBuilder).namedConsequence(); + setStart( namedConsequence ); + return (T) namedConsequence; + } else if ( ConditionalBranchDescrBuilder.class.isAssignableFrom( clazz ) ) { + ConditionalBranchDescrBuilder< ? > conditionalBranch = ((CEDescrBuilder< ? , ? >) ctxBuilder).conditionalBranch(); + setStart( conditionalBranch ); + return (T) conditionalBranch; + } + } + return null; + } + + @SuppressWarnings("unchecked") + public > T end( Class clazz, + DescrBuilder< ? , ? > builder ) { + if ( state.backtracking == 0 ) { + if ( !(FieldDescrBuilder.class.isAssignableFrom( clazz ) || + AttributeDescrBuilder.class.isAssignableFrom( clazz ) || + CEDescrBuilder.class.isAssignableFrom( clazz ) || + CollectDescrBuilder.class.isAssignableFrom( clazz ) || + AccumulateDescrBuilder.class.isAssignableFrom( clazz ) || + ForallDescrBuilder.class.isAssignableFrom( clazz ) || + BehaviorDescrBuilder.class.isAssignableFrom( clazz ) || + ConditionalBranchDescrBuilder.class.isAssignableFrom( clazz ) || + NamedConsequenceDescrBuilder.class.isAssignableFrom( clazz )) ) { + popParaphrases(); + } + + if (RuleDescrBuilder.class.isAssignableFrom(clazz)) { + RuleDescrBuilder ruleDescrBuilder = (RuleDescrBuilder)builder; + ruleDescrBuilder.end().getDescr().afterRuleAdded(ruleDescrBuilder.getDescr()); + } + + setEnd( builder ); + return (T) builder; + } + return null; + } + + public String[] getStatementKeywords() { + return statementKeywords; + } +} diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java new file mode 100644 index 00000000000..a7672090cc8 --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java @@ -0,0 +1,270 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.parser; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.drools.compiler.builder.impl.EvaluatorRegistry; +import org.drools.drl.ast.descr.AtomicExprDescr; +import org.drools.drl.ast.descr.BindingDescr; +import org.drools.drl.ast.descr.ConnectiveType; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.ast.descr.RelationalExprDescr; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * DRLExprTreeTest + */ +public class DRLExprParserTest { + + DrlExprParser parser; + + @Before + public void setUp() throws Exception { + new EvaluatorRegistry(); + this.parser = new DrlExprParser(LanguageLevelOption.DRL6); + } + + @After + public void tearDown() throws Exception { + this.parser = null; + } + + @Test + public void testSimpleExpression() throws Exception { + String source = "a > b"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + } + + @Test + public void testAndConnective() throws Exception { + String source = "a > b && 10 != 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + + expr = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("!="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("10"); + assertThat(right.getExpression()).isEqualTo("20"); + } + + @Test + public void testConnective2() throws Exception { + String source = "(a > b || 10 != 20) && someMethod(10) == 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get( 0 ); + assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); + assertThat(or.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + + expr = (RelationalExprDescr) or.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("!="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("10"); + assertThat(right.getExpression()).isEqualTo("20"); + + expr = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod(10)"); + assertThat(right.getExpression()).isEqualTo("20"); + + } + + @Test + public void testBinding() throws Exception { + String source = "$x : property"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + } + + @Test + public void testBindingConstraint() throws Exception { + String source = "$x : property > value"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + RelationalExprDescr rel = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(rel.getOperator()).isEqualTo(">"); + + BindingDescr bind = (BindingDescr) rel.getLeft(); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + + AtomicExprDescr right = (AtomicExprDescr) rel.getRight(); + assertThat(right.getExpression()).isEqualTo("value"); + } + + @Test + public void testBindingWithRestrictions() throws Exception { + String source = "$x : property > value && < 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr rel = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(rel.getOperator()).isEqualTo(">"); + + BindingDescr bind = (BindingDescr) rel.getLeft(); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + + AtomicExprDescr right = (AtomicExprDescr) rel.getRight(); + assertThat(right.getExpression()).isEqualTo("value"); + + rel = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(rel.getOperator()).isEqualTo("<"); + + AtomicExprDescr left = (AtomicExprDescr) rel.getLeft(); + assertThat(left.getExpression()).isEqualTo("property"); + + right = (AtomicExprDescr) rel.getRight(); + assertThat(right.getExpression()).isEqualTo("20"); + } + + @Test + public void testDoubleBinding() throws Exception { + String source = "$x : x.m( 1, a ) && $y : y[z].foo"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("x.m( 1, a )"); + + bind = (BindingDescr) result.getDescrs().get( 1 ); + assertThat(bind.getVariable()).isEqualTo("$y"); + assertThat(bind.getExpression()).isEqualTo("y[z].foo"); + } + + @Test + public void testDeepBinding() throws Exception { + String source = "($a : a > $b : b[10].prop || 10 != 20) && $x : someMethod(10) == 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get( 0 ); + assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); + assertThat(or.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + BindingDescr leftBind = (BindingDescr) expr.getLeft(); + BindingDescr rightBind = (BindingDescr) expr.getRight(); + assertThat(leftBind.getVariable()).isEqualTo("$a"); + assertThat(leftBind.getExpression()).isEqualTo("a"); + assertThat(rightBind.getVariable()).isEqualTo("$b"); + assertThat(rightBind.getExpression()).isEqualTo("b[10].prop"); + + expr = (RelationalExprDescr) or.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("!="); + AtomicExprDescr leftExpr = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr rightExpr = (AtomicExprDescr) expr.getRight(); + assertThat(leftExpr.getExpression()).isEqualTo("10"); + assertThat(rightExpr.getExpression()).isEqualTo("20"); + + expr = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("=="); + leftBind = (BindingDescr) expr.getLeft(); + rightExpr = (AtomicExprDescr) expr.getRight(); + assertThat(leftBind.getVariable()).isEqualTo("$x"); + assertThat(leftBind.getExpression()).isEqualTo("someMethod(10)"); + assertThat(rightExpr.getExpression()).isEqualTo("20"); + + } + + @Test(timeout = 10000L) + public void testNestedExpression() throws Exception { + // DROOLS-982 + String source = "(((((((((((((((((((((((((((((((((((((((((((((((((( a > b ))))))))))))))))))))))))))))))))))))))))))))))))))"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + } +} From e3dd6f67f7fb78bf1c5a63d44661320eaf007f59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 17 Jan 2024 16:13:35 +0100 Subject: [PATCH 051/141] Update DRL6Expressions.g4 to ANTLR 4 (#47) --- drools-drl/drools-drl10-parser/pom.xml | 9 +- .../org/drools/parser/DRL6Expressions.g4 | 366 +++++++++--------- .../org/drools/parser/DRLExpressions.java | 21 +- .../java/org/drools/parser/DrlExprParser.java | 34 +- .../parser/DroolsParserExceptionFactory.java | 170 +------- .../java/org/drools/parser/ParserHelper.java | 14 +- .../org/drools/parser/DRLExprParserTest.java | 16 +- 7 files changed, 264 insertions(+), 366 deletions(-) diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml index a3f638cc1c4..49aee297f54 100644 --- a/drools-drl/drools-drl10-parser/pom.xml +++ b/drools-drl/drools-drl10-parser/pom.xml @@ -18,12 +18,17 @@ org.drools drools-drl-ast - ${version.drools-drl-ast} + ${version.org.drools} org.drools drools-util - ${version.drools-drl-ast} + ${version.org.drools} + + + org.drools + drools-drl-parser + ${version.org.drools} diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 index b531c38feff..9b15991027c 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 @@ -1,40 +1,38 @@ parser grammar DRL6Expressions; - -options { + +options { language = Java; - tokenVocab = DRL6Lexer; + tokenVocab = DRLLexer; superClass=DRLExpressions; } - -@header { - package org.drools.drl.parser.lang; +@header { import java.util.LinkedList; import org.drools.drl.parser.DroolsParserException; - import org.drools.drl.parser.lang.ParserHelper; + import org.drools.drl.parser.lang.DroolsEditorType; import org.drools.drl.parser.lang.DroolsParserExceptionFactory; + import org.drools.drl.parser.lang.DroolsSentence; + import org.drools.drl.parser.lang.DroolsSoftKeywords; import org.drools.drl.parser.lang.Location; import org.drools.drl.ast.dsl.AnnotatedDescrBuilder; import org.drools.drl.ast.dsl.AnnotationDescrBuilder; - import org.drools.drl.ast.descr.AtomicExprDescr; import org.drools.drl.ast.descr.AnnotatedBaseDescr; import org.drools.drl.ast.descr.AnnotationDescr; + import org.drools.drl.ast.descr.AtomicExprDescr; import org.drools.drl.ast.descr.BaseDescr; + import org.drools.drl.ast.descr.BindingDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; import org.drools.drl.ast.descr.RelationalExprDescr; - import org.drools.drl.ast.descr.BindingDescr; } @members { private ParserHelper helper; public DRL6Expressions(TokenStream input, - RecognizerSharedState state, ParserHelper helper ) { - this( input, - state ); + this( input ); this.helper = helper; } @@ -61,22 +59,28 @@ options { public void setHasBindings( boolean value ) { this.hasBindings = value; } public boolean hasBindings() { return this.hasBindings; } + @Override + public final BaseDescr conditionalOrExpressionDescr() throws RecognitionException { + return conditionalOrExpression().result; + } + private boolean isNotEOF() { - if (state.backtracking != 0){ + // TODO verify that we can omit the backtracking check + /*if (state.backtracking != 0){ return false; - } - if (input.get( input.index() - 1 ).getType() == DRL6Lexer.WS){ + }*/ + if (_input.get( _input.index() - 1 ).getType() == DRLLexer.WS){ return true; } - if (input.LA(-1) == DRL6Lexer.LEFT_PAREN){ + if (_input.LA(-1) == DRLLexer.LPAREN){ return true; } - return input.get( input.index() ).getType() != DRL6Lexer.EOF; + return _input.get( _input.index() ).getType() != DRLLexer.EOF; } private boolean notStartWithNewline() { - int currentTokenIndex = input.index(); // current position in input stream - Token previousHiddenToken = input.get(currentTokenIndex - 1); + int currentTokenIndex = _input.index(); // current position in input stream + Token previousHiddenToken = _input.get(currentTokenIndex - 1); String previousHiddenTokenText = previousHiddenToken.getText(); return !previousHiddenTokenText.contains("\n"); } @@ -94,22 +98,23 @@ catch (RecognitionException re) { // GENERAL RULES // -------------------------------------------------------- literal - : STRING { helper.emit($STRING, DroolsEditorType.STRING_CONST); } - | DECIMAL { helper.emit($DECIMAL, DroolsEditorType.NUMERIC_CONST); } - | HEX { helper.emit($HEX, DroolsEditorType.NUMERIC_CONST); } - | FLOAT { helper.emit($FLOAT, DroolsEditorType.NUMERIC_CONST); } - | BOOL { helper.emit($BOOL, DroolsEditorType.BOOLEAN_CONST); } - | NULL { helper.emit($NULL, DroolsEditorType.NULL_CONST); } + : STRING_LITERAL { helper.emit($STRING_LITERAL, DroolsEditorType.STRING_CONST); } + | DECIMAL_LITERAL { helper.emit($DECIMAL_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | HEX_LITERAL { helper.emit($HEX_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | FLOAT_LITERAL { helper.emit($FLOAT_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | BOOL_LITERAL { helper.emit($BOOL_LITERAL, DroolsEditorType.BOOLEAN_CONST); } + | NULL_LITERAL { helper.emit($NULL_LITERAL, DroolsEditorType.NULL_CONST); } | TIME_INTERVAL { helper.emit($TIME_INTERVAL, DroolsEditorType.NULL_CONST); } - | STAR { helper.emit($STAR, DroolsEditorType.NUMERIC_CONST); } // this means "infinity" in Drools + | MUL { helper.emit($MUL, DroolsEditorType.NUMERIC_CONST); } // this means "infinity" in Drools ; operator returns [boolean negated, String opr] @init{ if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); helper.setHasOperator( true ); } -@after{ if( state.backtracking == 0 && input.LA( 1 ) != DRL6Lexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } } +// 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 ); } } : x=TILDE? - ( op=EQUALS { $negated = false; $opr=($x != null ? $x.text : "")+$op.text; helper.emit($op, DroolsEditorType.SYMBOL); } - | op=NOT_EQUALS { $negated = false; $opr=($x != null ? $x.text : "")+$op.text; helper.emit($op, DroolsEditorType.SYMBOL); } + ( 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); } | rop=relationalOp { $negated = $rop.negated; $opr=($x != null ? $x.text : "")+$rop.opr; } ) ; @@ -118,11 +123,12 @@ 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 ); } -@after{ if( state.backtracking == 0 && input.LA( 1 ) != DRL6Lexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } } - : ( op=LESS_EQUALS { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} - | op=GREATER_EQUALS { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} - | op=LESS { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} - | op=GREATER { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} +// 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 ); } } + : ( 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);} + | op=GT { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} | xop=complexOp { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} | not_key nop=neg_operator_key { $negated = true; $opr=$nop.text;} | cop=operator_key { $negated = false; $opr=$cop.text;} @@ -130,7 +136,7 @@ relationalOp returns [boolean negated, String opr, java.util.List params ; complexOp returns [String opr] - : t=TILDE e=EQUALS_ASSIGN { $opr=$t.text+$e.text; } + : t=TILDE e=ASSIGN { $opr=$t.text+$e.text; } ; typeList @@ -142,12 +148,12 @@ type ; typeMatch - : (primitiveType) => ( primitiveType ((LEFT_SQUARE RIGHT_SQUARE)=> LEFT_SQUARE RIGHT_SQUARE)* ) - | ( ID ((typeArguments)=>typeArguments)? (DOT ID ((typeArguments)=>typeArguments)? )* ((LEFT_SQUARE RIGHT_SQUARE)=> LEFT_SQUARE RIGHT_SQUARE)* ) + : primitiveType (LBRACK RBRACK)* + | IDENTIFIER (typeArguments)? (DOT IDENTIFIER (typeArguments)? )* (LBRACK RBRACK)* ; typeArguments - : LESS typeArgument (COMMA typeArgument)* GREATER + : LT typeArgument (COMMA typeArgument)* GT ; typeArgument @@ -161,7 +167,7 @@ typeArgument // the following dymmy rule is to force the AT symbol to be // included in the follow set of the expression on the DFAs dummy - : expression ( AT | SEMICOLON | EOF | ID | RIGHT_PAREN ) ; + : expression ( AT | SEMI | EOF | IDENTIFIER | RPAREN ) ; dummy2 : relationalExpression EOF; @@ -169,7 +175,7 @@ dummy2 // top level entry point for arbitrary expression parsing expression returns [BaseDescr result] : left=conditionalExpression { if( buildDescr ) { $result = $left.result; } } - ((assignmentOperator) => op=assignmentOperator right=expression)? + (op=assignmentOperator right=expression)? ; conditionalExpression returns [BaseDescr result] @@ -186,7 +192,7 @@ finally { ternOp--; } fullAnnotation [AnnotatedDescrBuilder inDescrBuilder] returns [AnnotationDescr result] @init{ String n = ""; AnnotationDescrBuilder annoBuilder = null; } - : AT name=ID { n = $name.text; } ( DOT x=ID { n += "." + $x.text; } )* + : AT name=IDENTIFIER { n = $name.text; } ( DOT x=IDENTIFIER { n += "." + $x.text; } )* { if( buildDescr ) { if ( inDescrBuilder == null ) { $result = new AnnotationDescr( n ); @@ -197,16 +203,16 @@ fullAnnotation [AnnotatedDescrBuilder inDescrBuilder] returns [AnnotationDescr r } } } - annotationArgs[result, annoBuilder] + annotationArgs[$result, annoBuilder] ; annotationArgs [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] - : LEFT_PAREN + : LPAREN ( - (ID EQUALS_ASSIGN) => annotationElementValuePairs[descr, inDescrBuilder] + annotationElementValuePairs[descr, inDescrBuilder] | value=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setValue( $value.result ); } } )? - RIGHT_PAREN + RPAREN ; annotationElementValuePairs [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] @@ -214,7 +220,7 @@ annotationElementValuePairs [AnnotationDescr descr, AnnotatedDescrBuilder inDesc ; annotationElementValuePair [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] - : key=ID EQUALS_ASSIGN val=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setKeyValue( $key.text, $val.result ); } } + : key=IDENTIFIER ASSIGN val=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setKeyValue( $key.text, $val.result ); } } ; annotationValue[AnnotatedDescrBuilder inDescrBuilder] returns [Object result] @@ -225,23 +231,23 @@ annotationValue[AnnotatedDescrBuilder inDescrBuilder] returns [Object result] annotationArray[AnnotatedDescrBuilder inDescrBuilder] returns [java.util.List result] @init { $result = new java.util.ArrayList();} - : LEFT_CURLY ( anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } + : LBRACE ( anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } ( COMMA anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } )* )? - RIGHT_CURLY + RBRACE ; conditionalOrExpression returns [BaseDescr result] : left=conditionalAndExpression { if( buildDescr ) { $result = $left.result; } } - ( DOUBLE_PIPE + ( OR { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } args=fullAnnotation[null]? right=conditionalAndExpression { if( buildDescr ) { ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newOr(); descr.addOrMerge( $result ); descr.addOrMerge( $right.result ); - if ( args != null ) { descr.addAnnotation( $args.result ); } + if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } $result = descr; } } @@ -250,14 +256,14 @@ conditionalOrExpression returns [BaseDescr result] conditionalAndExpression returns [BaseDescr result] : left=inclusiveOrExpression { if( buildDescr ) { $result = $left.result; } } - ( DOUBLE_AMPER + ( AND { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } args=fullAnnotation[null]? right=inclusiveOrExpression { if( buildDescr ) { ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newAnd(); descr.addOrMerge( $result ); descr.addOrMerge( $right.result ); - if ( args != null ) { descr.addAnnotation( $args.result ); } + if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } $result = descr; } } @@ -266,7 +272,7 @@ conditionalAndExpression returns [BaseDescr result] inclusiveOrExpression returns [BaseDescr result] : left=exclusiveOrExpression { if( buildDescr ) { $result = $left.result; } } - ( PIPE right=exclusiveOrExpression + ( BITOR right=exclusiveOrExpression { if( buildDescr ) { ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newIncOr(); descr.addOrMerge( $result ); @@ -279,7 +285,7 @@ inclusiveOrExpression returns [BaseDescr result] exclusiveOrExpression returns [BaseDescr result] : left=andExpression { if( buildDescr ) { $result = $left.result; } } - ( XOR right=andExpression + ( CARET right=andExpression { if( buildDescr ) { ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newXor(); descr.addOrMerge( $result ); @@ -292,7 +298,7 @@ exclusiveOrExpression returns [BaseDescr result] andExpression returns [BaseDescr result] : left=equalityExpression { if( buildDescr ) { $result = $left.result; } } - ( AMPER right=equalityExpression + ( BITAND right=equalityExpression { if( buildDescr ) { ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newIncAnd(); descr.addOrMerge( $result ); @@ -305,9 +311,9 @@ andExpression returns [BaseDescr result] equalityExpression returns [BaseDescr result] : left=instanceOfExpression { if( buildDescr ) { $result = $left.result; } } - ( ( op=EQUALS | op=NOT_EQUALS ) + ( ( op=EQUAL | op=NOTEQUAL ) { helper.setHasOperator( true ); - if( input.LA( 1 ) != DRL6Lexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + if( _input.LA( 1 ) != DRLLexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } right=instanceOfExpression { if( buildDescr ) { $result = new RelationalExprDescr( $op.text, false, null, $left.result, $right.result ); @@ -320,7 +326,7 @@ instanceOfExpression returns [BaseDescr result] : left=inExpression { if( buildDescr ) { $result = $left.result; } } ( op=instanceof_key { helper.setHasOperator( true ); - if( input.LA( 1 ) != DRL6Lexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + if( _input.LA( 1 ) != DRLLexer.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) ); @@ -341,39 +347,40 @@ inExpression returns [BaseDescr result] leftDescr = $left.result; } } - ((not_key in_key)=> not_key in=in_key LEFT_PAREN + (not_key in=in_key LPAREN { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } e1=expression { descr = ConstraintConnectiveDescr.newAnd(); - RelationalExprDescr rel = new RelationalExprDescr( "!=", false, null, leftDescr, $e1.result ); - descr.addOrMerge( rel ); + RelationalExprDescr rel1 = new RelationalExprDescr( "!=", false, null, leftDescr, $e1.result ); + descr.addOrMerge( rel1 ); $result = descr; } (COMMA e2=expression - { RelationalExprDescr rel = new RelationalExprDescr( "!=", false, null, leftDescr, $e2.result ); - descr.addOrMerge( rel ); + { RelationalExprDescr rel2 = new RelationalExprDescr( "!=", false, null, leftDescr, $e2.result ); + descr.addOrMerge( rel2 ); } - )* RIGHT_PAREN + )* RPAREN { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } - | in=in_key LEFT_PAREN + | in=in_key LPAREN { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } e1=expression { descr = ConstraintConnectiveDescr.newOr(); - RelationalExprDescr rel = new RelationalExprDescr( "==", false, null, leftDescr, $e1.result ); - descr.addOrMerge( rel ); + RelationalExprDescr rel1 = new RelationalExprDescr( "==", false, null, leftDescr, $e1.result ); + descr.addOrMerge( rel1 ); $result = descr; } (COMMA e2=expression - { RelationalExprDescr rel = new RelationalExprDescr( "==", false, null, leftDescr, $e2.result ); - descr.addOrMerge( rel ); + { RelationalExprDescr rel2 = new RelationalExprDescr( "==", false, null, leftDescr, $e2.result ); + descr.addOrMerge( rel2 ); } - )* RIGHT_PAREN + )* RPAREN { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } )? ; relationalExpression returns [BaseDescr result] -scope { BaseDescr lsd; } +locals [ BaseDescr lsd ] +// TODO access lsd directly instead of through dynamic context here @init { $relationalExpression::lsd = null; } : left=shiftExpression { if( buildDescr ) { @@ -397,12 +404,14 @@ scope { BaseDescr lsd; } } else { $result = $left.result; } + // TODO access lsd directly instead of through dynamic context here $relationalExpression::lsd = $result; } } - ( ( operator | LEFT_PAREN )=> right=orRestriction + ( right=orRestriction { if( buildDescr ) { $result = $right.result; + // TODO access lsd directly instead of through dynamic context here $relationalExpression::lsd = $result; } } @@ -411,12 +420,12 @@ scope { BaseDescr lsd; } orRestriction returns [BaseDescr result] : left=andRestriction { if( buildDescr ) { $result = $left.result; } } - ( (DOUBLE_PIPE fullAnnotation[null]? andRestriction)=>lop=DOUBLE_PIPE args=fullAnnotation[null]? right=andRestriction + ( lop=OR args=fullAnnotation[null]? right=andRestriction { if( buildDescr ) { ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newOr(); descr.addOrMerge( $result ); descr.addOrMerge( $right.result ); - if ( args != null ) { descr.addAnnotation( $args.result ); } + if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } $result = descr; } } @@ -425,14 +434,14 @@ orRestriction returns [BaseDescr result] andRestriction returns [BaseDescr result] : left=singleRestriction { if( buildDescr ) { $result = $left.result; } } - ( (DOUBLE_AMPER fullAnnotation[null]? operator)=>lop=DOUBLE_AMPER + ( 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 ( args != null ) { descr.addAnnotation( $args.result ); } + if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } $result = descr; } } @@ -442,7 +451,7 @@ andRestriction returns [BaseDescr result] singleRestriction returns [BaseDescr result] : op=operator { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } - ( (squareArguments shiftExpression)=> sa=squareArguments value=shiftExpression + ( sa=squareArguments value=shiftExpression | value=shiftExpression ) { if( buildDescr ) { @@ -451,85 +460,85 @@ singleRestriction returns [BaseDescr result] ($value.text.equals(((AtomicExprDescr)$value.result).getExpression())) )) ? $value.result : new AtomicExprDescr( $value.text ) ; - $result = new RelationalExprDescr( $op.opr, $op.negated, $sa.args, $relationalExpression::lsd, descr ); + $result = new RelationalExprDescr( $op.opr, $op.negated, $ctx.sa != null ? $sa.args : null, $relationalExpression::lsd, descr ); if( $relationalExpression::lsd instanceof BindingDescr ) { $relationalExpression::lsd = new AtomicExprDescr( ((BindingDescr)$relationalExpression::lsd).getExpression() ); } } helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } - | LEFT_PAREN or=orRestriction RIGHT_PAREN { $result = $or.result; } + | LPAREN or=orRestriction RPAREN { $result = $or.result; } ; shiftExpression returns [BaseDescr result] : left=additiveExpression { if( buildDescr ) { $result = $left.result; } } - ( (shiftOp)=>shiftOp additiveExpression )* + ( shiftOp additiveExpression )* ; shiftOp - : ( LESS LESS - | GREATER GREATER GREATER - | GREATER GREATER ) + : ( LT LT + | GT GT GT + | GT GT ) ; additiveExpression returns [BaseDescr result] : left=multiplicativeExpression { if( buildDescr ) { $result = $left.result; } } - ( (PLUS|MINUS)=> (PLUS | MINUS) multiplicativeExpression )* + ( (ADD | SUB) multiplicativeExpression )* ; multiplicativeExpression returns [BaseDescr result] : left=unaryExpression { if( buildDescr ) { $result = $left.result; } } - ( ( STAR | DIV | MOD ) unaryExpression )* + ( ( MUL | DIV | MOD ) unaryExpression )* ; unaryExpression returns [BaseDescr result] - : PLUS ue=unaryExpression + : ADD ue=unaryExpression { if( buildDescr ) { $result = $ue.result; if( $result instanceof AtomicExprDescr ) { ((AtomicExprDescr)$result).setExpression( "+" + ((AtomicExprDescr)$result).getExpression() ); } } } - | MINUS ue=unaryExpression + | SUB ue=unaryExpression { if( buildDescr ) { $result = $ue.result; if( $result instanceof AtomicExprDescr ) { ((AtomicExprDescr)$result).setExpression( "-" + ((AtomicExprDescr)$result).getExpression() ); } } } - | INCR primary - | DECR primary + | INC primary + | DEC primary | left=unaryExpressionNotPlusMinus { if( buildDescr ) { $result = $left.result; } } ; unaryExpressionNotPlusMinus returns [BaseDescr result] @init { boolean isLeft = false; BindingDescr bind = null;} : TILDE unaryExpression - | NEGATION ue=unaryExpression + | BANG ue=unaryExpression { - if( buildDescr && ue != null ) { - $result = ue.negate(); + if( buildDescr && $ue.result != null ) { + $result = $ue.result.negate(); } } - | (castExpression)=>castExpression - | (backReferenceExpression)=>backReferenceExpression + | castExpression + | backReferenceExpression | { isLeft = helper.getLeftMostExpr() == null;} - ( ({inMap == 0 && ternOp == 0 && input.LA(2) == DRL6Lexer.COLON}? (var=ID COLON + ( ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.COLON}? (var=IDENTIFIER COLON { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($COLON, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, false); helper.setStart( bind, $var ); } } )) - | ({inMap == 0 && ternOp == 0 && input.LA(2) == DRL6Lexer.UNIFY}? (var=ID UNIFY - { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($UNIFY, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, true); helper.setStart( bind, $var ); } } )) + | ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.DRL_UNIFY}? (var=IDENTIFIER DRL_UNIFY + { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($DRL_UNIFY, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, true); helper.setStart( bind, $var ); } } )) )? - ( (xpathSeparator ID)=>left2=xpathPrimary { if( buildDescr ) { $result = $left2.result; } } + ( left2=xpathPrimary { if( buildDescr ) { $result = $left2.result; } } | left1=primary { if( buildDescr ) { $result = $left1.result; } } ) - ((selector)=>selector)* + (selector)* { if( buildDescr ) { - String expr = $unaryExpressionNotPlusMinus.text; + String expr = $text; if( isLeft ) { helper.setLeftMostExpr( expr ); } @@ -545,16 +554,16 @@ unaryExpressionNotPlusMinus returns [BaseDescr result] } } } - ((INCR|DECR)=> (INCR|DECR))? + ((INC|DEC))? ; castExpression - : (LEFT_PAREN primitiveType) => LEFT_PAREN primitiveType RIGHT_PAREN expr=unaryExpression - | (LEFT_PAREN type) => LEFT_PAREN type RIGHT_PAREN unaryExpressionNotPlusMinus + : LPAREN primitiveType RPAREN expr=unaryExpression + | LPAREN type RPAREN unaryExpressionNotPlusMinus ; backReferenceExpression - : (DOT DOT DIV) => (DOT DOT DIV)+ unaryExpressionNotPlusMinus + : (DOT DOT DIV)+ unaryExpressionNotPlusMinus ; primitiveType @@ -578,7 +587,7 @@ xpathPrimary returns [BaseDescr result] ; xpathChunk returns [BaseDescr result] - : (xpathSeparator ID)=> xpathSeparator ID (DOT ID)* (HASH ID)? (LEFT_SQUARE xpathExpressionList RIGHT_SQUARE)? + : xpathSeparator IDENTIFIER (DOT IDENTIFIER)* (HASH IDENTIFIER)? (LBRACK xpathExpressionList RBRACK)? ; xpathExpressionList returns [java.util.List exprs] @@ -588,38 +597,38 @@ xpathExpressionList returns [java.util.List exprs] ; primary returns [BaseDescr result] - : (LEFT_PAREN)=> expr=parExpression { if( buildDescr ) { $result = $expr.result; } } - | (nonWildcardTypeArguments)=> nonWildcardTypeArguments (explicitGenericInvocationSuffix | this_key arguments) - | (literal)=> literal { if( buildDescr ) { $result = new AtomicExprDescr( $literal.text, true ); } } - //| this_key ({!helper.validateSpecialID(2)}?=> DOT ID)* ({helper.validateIdentifierSufix()}?=> identifierSuffix)? - | (super_key)=> super_key superSuffix - | (new_key)=> new_key creator - | (primitiveType)=> primitiveType (LEFT_SQUARE RIGHT_SQUARE)* DOT class_key + : expr=parExpression { if( buildDescr ) { $result = $expr.result; } } + | nonWildcardTypeArguments (explicitGenericInvocationSuffix | this_key arguments) + | literal { if( buildDescr ) { $result = new AtomicExprDescr( $literal.text, true ); } } + //| this_key ({!helper.validateSpecialID(2)}? DOT IDENTIFIER)* ({helper.validateIdentifierSufix()}? identifierSuffix)? + | super_key superSuffix + | new_key creator + | primitiveType (LBRACK RBRACK)* DOT class_key //| void_key DOT class_key - | (inlineMapExpression)=> inlineMapExpression - | (inlineListExpression)=> inlineListExpression - | (ID)=>i1=ID { helper.emit($i1, DroolsEditorType.IDENTIFIER); } + | inlineMapExpression + | inlineListExpression + | i1=IDENTIFIER { helper.emit($i1, DroolsEditorType.IDENTIFIER); } ( - ( (DOT ID)=>d=DOT i2=ID { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + ( d=DOT i2=IDENTIFIER { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) | - ( ((DOT|NULL_SAFE_DOT) LEFT_PAREN)=>d=(DOT|NULL_SAFE_DOT) LEFT_PAREN { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($LEFT_PAREN, DroolsEditorType.SYMBOL); } + ( d=(DOT|NULL_SAFE_DOT) LPAREN { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($LPAREN, DroolsEditorType.SYMBOL); } expression (COMMA { helper.emit($COMMA, DroolsEditorType.SYMBOL); } expression)* - RIGHT_PAREN { helper.emit($RIGHT_PAREN, DroolsEditorType.SYMBOL); } + RPAREN { helper.emit($RPAREN, DroolsEditorType.SYMBOL); } ) | - ( (HASH ID)=>h=HASH i2=ID { helper.emit($h, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + ( h=HASH i2=IDENTIFIER { helper.emit($h, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) | - ( (NULL_SAFE_DOT ID)=>n=NULL_SAFE_DOT i2=ID { helper.emit($n, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) - )* ((identifierSuffix)=>identifierSuffix)? + ( n=NULL_SAFE_DOT i2=IDENTIFIER { helper.emit($n, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + )* (identifierSuffix)? ; inlineListExpression - : LEFT_SQUARE expressionList? RIGHT_SQUARE + : LBRACK expressionList? RBRACK ; inlineMapExpression @init{ inMap++; } - : LEFT_SQUARE mapExpressionList RIGHT_SQUARE + : LBRACK mapExpressionList RBRACK ; finally { inMap--; } @@ -632,7 +641,7 @@ mapEntry ; parExpression returns [BaseDescr result] - : LEFT_PAREN expr=expression RIGHT_PAREN + : LPAREN expr=expression RPAREN { if( buildDescr ) { $result = $expr.result; if( $result instanceof AtomicExprDescr ) { @@ -643,12 +652,12 @@ parExpression returns [BaseDescr result] ; identifierSuffix - : (LEFT_SQUARE RIGHT_SQUARE)=>(LEFT_SQUARE { helper.emit($LEFT_SQUARE, DroolsEditorType.SYMBOL); } - RIGHT_SQUARE { helper.emit($RIGHT_SQUARE, DroolsEditorType.SYMBOL); } )+ + : (LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } + RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } )+ DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } class_key - | ((LEFT_SQUARE) => LEFT_SQUARE { helper.emit($LEFT_SQUARE, DroolsEditorType.SYMBOL); } + | (LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } expression - RIGHT_SQUARE { helper.emit($RIGHT_SQUARE, DroolsEditorType.SYMBOL); } )+ // can also be matched by selector, but do here + RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } )+ // can also be matched by selector, but do here | arguments // | DOT class_key // | DOT explicitGenericInvocation @@ -663,19 +672,19 @@ creator ; createdName - : ID typeArguments? - ( DOT ID typeArguments?)* + : IDENTIFIER typeArguments? + ( DOT IDENTIFIER typeArguments?)* | primitiveType ; innerCreator - : {!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}?=> ID classCreatorRest + : {!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? IDENTIFIER classCreatorRest ; arrayCreatorRest - : LEFT_SQUARE - ( RIGHT_SQUARE (LEFT_SQUARE RIGHT_SQUARE)* arrayInitializer - | expression RIGHT_SQUARE ({!helper.validateLT(2,"]")}?=>LEFT_SQUARE expression RIGHT_SQUARE)* ((LEFT_SQUARE RIGHT_SQUARE)=> LEFT_SQUARE RIGHT_SQUARE)* + : LBRACK + ( RBRACK (LBRACK RBRACK)* arrayInitializer + | expression RBRACK ({!helper.validateLT(2,"]")}? LBRACK expression RBRACK)* (LBRACK RBRACK)* ) ; @@ -685,7 +694,7 @@ variableInitializer ; arrayInitializer - : LEFT_CURLY (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RIGHT_CURLY + : LBRACE (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RBRACE ; classCreatorRest @@ -697,42 +706,45 @@ explicitGenericInvocation ; nonWildcardTypeArguments - : LESS typeList GREATER + : LT typeList GT ; explicitGenericInvocationSuffix : super_key superSuffix - | ID arguments + | IDENTIFIER arguments ; selector - : (DOT super_key)=>DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } super_key superSuffix - | (DOT new_key)=>DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } new_key (nonWildcardTypeArguments)? innerCreator - | (DOT ID)=>DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } - ID { helper.emit($ID, DroolsEditorType.IDENTIFIER); } - ((LEFT_PAREN) => arguments)? - | (NULL_SAFE_DOT ID)=>NULL_SAFE_DOT { helper.emit($NULL_SAFE_DOT, DroolsEditorType.SYMBOL); } - ID { helper.emit($ID, DroolsEditorType.IDENTIFIER); } - ((LEFT_PAREN) => arguments)? + : DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } super_key superSuffix + | DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } new_key (nonWildcardTypeArguments)? innerCreator + | DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } + IDENTIFIER { helper.emit($IDENTIFIER, DroolsEditorType.IDENTIFIER); } + (arguments)? + | NULL_SAFE_DOT { helper.emit($NULL_SAFE_DOT, DroolsEditorType.SYMBOL); } + IDENTIFIER { helper.emit($IDENTIFIER, DroolsEditorType.IDENTIFIER); } + (arguments)? //| DOT this_key - | (LEFT_SQUARE)=>LEFT_SQUARE { helper.emit($LEFT_SQUARE, DroolsEditorType.SYMBOL); } + | LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } expression - RIGHT_SQUARE { helper.emit($RIGHT_SQUARE, DroolsEditorType.SYMBOL); } + RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } ; superSuffix : arguments - | DOT ID ((LEFT_PAREN) => arguments)? + // TODO syntactic predicates in the form of `(x) => x` can be safely removed but + // there was originally `DOT ID ((LEFT_PAREN) => arguments)?`. + // Not sure if removing `(LEFT_PAREN) =>` is correct. + | DOT IDENTIFIER (arguments)? ; squareArguments returns [java.util.List args] - : LEFT_SQUARE (el=expressionList { $args = $el.exprs; })? RIGHT_SQUARE + : LBRACK (el=expressionList { $args = $el.exprs; })? RBRACK ; arguments - : LEFT_PAREN { helper.emit($LEFT_PAREN, DroolsEditorType.SYMBOL); } + : LPAREN { helper.emit($LPAREN, DroolsEditorType.SYMBOL); } expressionList? - RIGHT_PAREN { helper.emit($RIGHT_PAREN, DroolsEditorType.SYMBOL); } + RPAREN { helper.emit($RPAREN, DroolsEditorType.SYMBOL); } ; expressionList returns [java.util.List exprs] @@ -742,95 +754,95 @@ expressionList returns [java.util.List exprs] ; assignmentOperator - : EQUALS_ASSIGN - | PLUS_ASSIGN - | MINUS_ASSIGN - | MULT_ASSIGN + : ASSIGN + | ADD_ASSIGN + | SUB_ASSIGN + | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | MOD_ASSIGN - | LESS LESS EQUALS_ASSIGN - | (GREATER GREATER GREATER)=> GREATER GREATER GREATER EQUALS_ASSIGN - | (GREATER GREATER)=> GREATER GREATER EQUALS_ASSIGN + | LT LT ASSIGN + | GT GT GT ASSIGN + | GT GT ASSIGN ; // -------------------------------------------------------- // KEYWORDS // -------------------------------------------------------- extends_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.EXTENDS))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.EXTENDS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; super_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.SUPER))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.SUPER))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; instanceof_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; boolean_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.BOOLEAN))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.BOOLEAN))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; char_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.CHAR))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.CHAR))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; byte_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.BYTE))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.BYTE))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; short_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.SHORT))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.SHORT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; int_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.INT))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.INT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; float_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.FLOAT))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.FLOAT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; long_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.LONG))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.LONG))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; double_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.DOUBLE))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.DOUBLE))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; void_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.VOID))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.VOID))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; this_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.THIS))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.THIS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; class_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.CLASS))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.CLASS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; new_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.NEW))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.NEW))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; not_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.NOT))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.NOT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; in_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.IN))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.IN))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; operator_key - : {(helper.isPluggableEvaluator(false))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.isPluggableEvaluator(false))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; neg_operator_key - : {(helper.isPluggableEvaluator(true))}?=> id=ID { helper.emit($ID, DroolsEditorType.KEYWORD); } + : {(helper.isPluggableEvaluator(true))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } ; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java index ba811347b29..0109e233774 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java @@ -21,16 +21,16 @@ import java.util.LinkedList; import java.util.List; -import org.antlr.runtime.Parser; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.RecognizerSharedState; -import org.antlr.runtime.TokenStream; +import org.antlr.v4.runtime.Parser; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.TokenStream; import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.lang.DroolsSentence; public abstract class DRLExpressions extends Parser { - public DRLExpressions(TokenStream input, RecognizerSharedState state) { - super(input, state); + public DRLExpressions(TokenStream input) { + super(input); } public abstract void setBuildDescr( boolean build ); @@ -42,7 +42,14 @@ public DRLExpressions(TokenStream input, RecognizerSharedState state) { public abstract void setHasBindings( boolean value ); public abstract boolean hasBindings(); - public abstract BaseDescr conditionalOrExpression() throws RecognitionException; + /* + * This is the original method signature in drools/drools-drl/drools-drl-parser: + * public abstract BaseDescr conditionalOrExpression() throws RecognitionException; + * I changed it here because the conditionalOrExpression() method generated by ANTLR 4 from the conditionalOrExpression rule + * returns ConditionalOrExpressionContext, so it has a return type that's different from what was originally expected here. + * The Descr object is of course inside that context (go to this method's impl to see). + */ + public abstract BaseDescr conditionalOrExpressionDescr() throws RecognitionException; public abstract ParserHelper getHelper(); public abstract boolean hasErrors(); diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java index 7d624224cb5..d9c8d93bcee 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java @@ -21,13 +21,12 @@ import java.util.Collections; import java.util.List; -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.RecognizerSharedState; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; -import org.drools.drl.parser.lang.ParserHelper; +import org.drools.drl.parser.DroolsParserException; import org.kie.internal.builder.conf.LanguageLevelOption; /** @@ -45,23 +44,22 @@ public DrlExprParser(LanguageLevelOption languageLevel) { } /** Parse an expression from text */ - public ConstraintConnectiveDescr parse( final String text ) { + public ConstraintConnectiveDescr parse(final String text) { ConstraintConnectiveDescr constraint = null; try { - DRLLexer lexer = DRLFactory.getDRLLexer(new ANTLRStringStream(text), languageLevel); - CommonTokenStream input = new CommonTokenStream( lexer ); - RecognizerSharedState state = new RecognizerSharedState(); - helper = new ParserHelper( input, state, languageLevel ); - DRLExpressions parser = DRLFactory.getDRLExpressions(input, state, helper, languageLevel); - parser.setBuildDescr( true ); - parser.setLeftMostExpr( null ); // setting initial value just in case - BaseDescr expr = parser.conditionalOrExpression(); - if ( expr != null && !parser.hasErrors() ) { + DRLLexer lexer = new DRLLexer(CharStreams.fromString(text)); + CommonTokenStream input = new CommonTokenStream(lexer); + helper = new ParserHelper(input, null, languageLevel); + DRLExpressions parser = new DRL6Expressions(input, helper); + 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 ); + constraint.addOrMerge(expr); } - } catch ( RecognitionException e ) { - helper.reportError( e ); + } catch (RecognitionException e) { + helper.reportError(e); } return constraint; } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java index f94eab73ccc..e184dfe9e37 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java @@ -21,24 +21,18 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import org.antlr.runtime.BitSet; -import org.antlr.runtime.EarlyExitException; -import org.antlr.runtime.FailedPredicateException; -import org.antlr.runtime.MismatchedNotSetException; -import org.antlr.runtime.MismatchedSetException; -import org.antlr.runtime.MismatchedTokenException; -import org.antlr.runtime.MismatchedTreeNodeException; -import org.antlr.runtime.NoViableAltException; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.Token; +import org.antlr.v4.runtime.FailedPredicateException; +import org.antlr.v4.runtime.NoViableAltException; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Token; import org.drools.drl.parser.DRLFactory; import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.lang.DroolsParaphraseTypes; import org.kie.internal.builder.conf.LanguageLevelOption; /** @@ -48,14 +42,7 @@ * @see DroolsParserException */ public class DroolsParserExceptionFactory { - public final static String MISMATCHED_TOKEN_MESSAGE_COMPLETE = "Line %1$d:%2$d mismatched input '%3$s' expecting '%4$s'%5$s"; - public final static String MISMATCHED_TOKEN_MESSAGE_PART = "Line %1$d:%2$d mismatched input '%3$s'%4$s"; - public final static String MISMATCHED_TREE_NODE_MESSAGE_COMPLETE = "Line %1$d:%2$d mismatched tree node '%3$s' expecting '%4$s'%5$s"; - public final static String MISMATCHED_TREE_NODE_MESSAGE_PART = "Line %1$d:%2$d mismatched tree node '%3$s'%4$s"; public final static String NO_VIABLE_ALT_MESSAGE = "Line %1$d:%2$d no viable alternative at input '%3$s'%4$s"; - public final static String EARLY_EXIT_MESSAGE = "Line %1$d:%2$d required (...)+ loop did not match anything at input '%3$s'%4$s"; - public final static String MISMATCHED_SET_MESSAGE = "Line %1$d:%2$d mismatched input '%3$s' expecting one of the following tokens: '%4$s'%5$s."; - public final static String MISMATCHED_NOT_SET_MESSAGE = "Line %1$d:%2$d mismatched input '%3$s' not expecting any of the following tokens: '%4$s'%5$s"; public final static String FAILED_PREDICATE_MESSAGE = "Line %1$d:%2$d rule '%3$s' failed predicate: {%4$s}?%5$s"; public final static String TRAILING_SEMI_COLON_NOT_ALLOWED_MESSAGE = "Line %1$d:%2$d trailing semi-colon not allowed%3$s"; public final static String PARSER_LOCATION_MESSAGE_COMPLETE = " in %1$s %2$s"; @@ -125,9 +112,10 @@ public DroolsParserException createDroolsException( RecognitionException e ) { return new DroolsParserException( codeAndMessage.get( 1 ), codeAndMessage .get( 0 ), - e.line, - e.charPositionInLine, - e.index, + // TODO verify this is correct + e.getOffendingToken().getLine(), + e.getOffendingToken().getCharPositionInLine(), + e.getOffendingToken().getStartIndex(), e ); } @@ -138,119 +126,27 @@ public DroolsParserException createDroolsException( RecognitionException e ) { private List createErrorMessage( RecognitionException e ) { List codeAndMessage = new ArrayList<>( 2 ); String message; - if ( e instanceof MismatchedTokenException ) { - MismatchedTokenException mte = (MismatchedTokenException) e; - String expecting = mte instanceof DroolsMismatchedTokenException ? ((DroolsMismatchedTokenException)mte).getTokenText() : getBetterToken( mte.expecting ); - if ( tokenNames != null && mte.expecting >= 0 && mte.expecting < tokenNames.length ) { - message = String - .format( - MISMATCHED_TOKEN_MESSAGE_COMPLETE, - e.line, - e.charPositionInLine, - getBetterToken( e.token ), - expecting, - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 102" ); - } else { - message = String - .format( - MISMATCHED_TOKEN_MESSAGE_PART, - e.line, - e.charPositionInLine, - getBetterToken( e.token ), - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 102" ); - } - } else if ( e instanceof MismatchedTreeNodeException ) { - MismatchedTreeNodeException mtne = (MismatchedTreeNodeException) e; - if ( mtne.expecting >= 0 && mtne.expecting < tokenNames.length ) { - message = String - .format( - MISMATCHED_TREE_NODE_MESSAGE_COMPLETE, - e.line, - e.charPositionInLine, - getBetterToken( e.token ), - getBetterToken( mtne.expecting ), - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 106" ); - } else { - message = String - .format( - MISMATCHED_TREE_NODE_MESSAGE_PART, - e.line, - e.charPositionInLine, - getBetterToken( e.token ), - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 106" ); - } - } else if ( e instanceof NoViableAltException ) { + if ( e instanceof NoViableAltException ) { // NoViableAltException nvae = (NoViableAltException) e; message = String.format( NO_VIABLE_ALT_MESSAGE, - e.line, - e.charPositionInLine, - getBetterToken( e.token ), + // TODO verify this is correct + e.getOffendingToken().getLine(), + e.getOffendingToken().getCharPositionInLine(), + getBetterToken( e.getOffendingToken() ), formatParserLocation() ); codeAndMessage.add( message ); codeAndMessage.add( "ERR 101" ); - } else if ( e instanceof EarlyExitException ) { - // EarlyExitException eee = (EarlyExitException) e; - message = String.format( - EARLY_EXIT_MESSAGE, - e.line, - e.charPositionInLine, - getBetterToken( e.token ), - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 105" ); - } else if ( e instanceof MismatchedSetException ) { - MismatchedSetException mse = (MismatchedSetException) e; - String expected = expectedTokensAsString( mse.expecting ); - message = String.format( - MISMATCHED_SET_MESSAGE, - e.line, - e.charPositionInLine, - getBetterToken( e.token ), - expected, - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 107" ); - } else if ( e instanceof DroolsMismatchedSetException ) { - DroolsMismatchedSetException mse = (DroolsMismatchedSetException) e; - String expected = Arrays.asList( mse.getTokenText() ).toString(); - message = String.format( - MISMATCHED_SET_MESSAGE, - e.line, - e.charPositionInLine, - getBetterToken( e.token ), - expected, - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 107" ); - } else if ( e instanceof MismatchedNotSetException ) { - MismatchedNotSetException mse = (MismatchedNotSetException) e; - String expected = expectedTokensAsString( mse.expecting ); - message = String.format( - MISMATCHED_NOT_SET_MESSAGE, - e.line, - e.charPositionInLine, - getBetterToken( e.token ), - expected, - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 108" ); } else if ( e instanceof FailedPredicateException ) { FailedPredicateException fpe = (FailedPredicateException) e; + String ruleName = fpe.getRecognizer().getRuleNames()[fpe.getRuleIndex()]; message = String.format( FAILED_PREDICATE_MESSAGE, - e.line, - e.charPositionInLine, - fpe.ruleName, - fpe.predicateText, + // TODO verify this is correct + e.getOffendingToken().getLine(), + e.getOffendingToken().getCharPositionInLine(), + ruleName, + fpe.getPredicate(), formatParserLocation() ); codeAndMessage.add( message ); codeAndMessage.add( "ERR 103" ); @@ -276,19 +172,6 @@ public DroolsParserException createDroolsException( Exception e, } - private String expectedTokensAsString( BitSet set ) { - StringBuilder buf = new StringBuilder(); - buf.append( "{ " ); - int i = 0; - for ( int token : set.toArray() ) { - if ( i > 0 ) buf.append( ", " ); - buf.append( getBetterToken( token ) ); - i++; - } - buf.append( " }" ); - return buf.toString(); - } - /** * This will take Paraphrases stack, and create a sensible location */ @@ -364,17 +247,4 @@ private String getBetterToken( Token token ) { } return DRLFactory.getBetterToken(token.getType(), token.getText(), languageLevel); } - - /** - * Helper method that creates a user friendly token definition - * - * @param tokenType - * token type - * @return user friendly token definition - */ - private String getBetterToken( int tokenType ) { - return DRLFactory.getBetterToken( tokenType, null, languageLevel ); - } - - } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java index 94e5e2f76ce..66d6bea4d6b 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java +++ b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java @@ -39,11 +39,11 @@ import java.util.List; import java.util.Map; -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.RecognitionException; +import org.antlr.v4.runtime.CommonToken; import org.antlr.runtime.RecognizerSharedState; -import org.antlr.runtime.Token; -import org.antlr.runtime.TokenStream; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.TokenStream; import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.dsl.AbstractClassTypeDeclarationBuilder; @@ -78,6 +78,12 @@ import org.drools.drl.ast.dsl.UnitDescrBuilder; import org.drools.drl.ast.dsl.WindowDeclarationDescrBuilder; import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.lang.DroolsEditorType; +import org.drools.drl.parser.lang.DroolsParaphraseTypes; +import org.drools.drl.parser.lang.DroolsSentence; +import org.drools.drl.parser.lang.DroolsSentenceType; +import org.drools.drl.parser.lang.DroolsSoftKeywords; +import org.drools.drl.parser.lang.DroolsToken; import org.kie.internal.builder.conf.LanguageLevelOption; /** diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java index a7672090cc8..f233439f360 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java @@ -20,15 +20,15 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.drools.compiler.builder.impl.EvaluatorRegistry; import org.drools.drl.ast.descr.AtomicExprDescr; import org.drools.drl.ast.descr.BindingDescr; import org.drools.drl.ast.descr.ConnectiveType; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; import org.drools.drl.ast.descr.RelationalExprDescr; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.kie.internal.builder.conf.LanguageLevelOption; /** @@ -38,13 +38,12 @@ public class DRLExprParserTest { DrlExprParser parser; - @Before + @BeforeEach public void setUp() throws Exception { - new EvaluatorRegistry(); this.parser = new DrlExprParser(LanguageLevelOption.DRL6); } - @After + @AfterEach public void tearDown() throws Exception { this.parser = null; } @@ -248,7 +247,8 @@ public void testDeepBinding() throws Exception { } - @Test(timeout = 10000L) + @Test + @Timeout(10000L) public void testNestedExpression() throws Exception { // DROOLS-982 String source = "(((((((((((((((((((((((((((((((((((((((((((((((((( a > b ))))))))))))))))))))))))))))))))))))))))))))))))))"; From d2885a519e1b3fdc9cd93fbb0abcf85661d0f759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 7 Feb 2024 08:38:40 +0100 Subject: [PATCH 052/141] Add DescrDumperTest and fix the expression parser grammar (#48) * Add DescrDumperTest * Fix it --- drools-drl/drools-drl10-parser/pom.xml | 12 + .../org/drools/parser/DRL6Expressions.g4 | 11 +- .../org/drools/parser/DescrDumperTest.java | 367 ++++++++++++++++++ 3 files changed, 384 insertions(+), 6 deletions(-) create mode 100644 drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DescrDumperTest.java diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml index 49aee297f54..57ed8f85ca5 100644 --- a/drools-drl/drools-drl10-parser/pom.xml +++ b/drools-drl/drools-drl10-parser/pom.xml @@ -75,6 +75,18 @@ ${version.ch.qos.logback} test + + org.drools + drools-compiler + ${version.org.drools} + test + + + org.drools + drools-mvel + ${version.org.drools} + test + diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 index 9b15991027c..ef6e0982672 100644 --- a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 +++ b/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 @@ -99,6 +99,7 @@ catch (RecognitionException re) { // -------------------------------------------------------- literal : STRING_LITERAL { helper.emit($STRING_LITERAL, DroolsEditorType.STRING_CONST); } + | DRL_STRING_LITERAL { helper.emit($DRL_STRING_LITERAL, DroolsEditorType.STRING_CONST); } | DECIMAL_LITERAL { helper.emit($DECIMAL_LITERAL, DroolsEditorType.NUMERIC_CONST); } | HEX_LITERAL { helper.emit($HEX_LITERAL, DroolsEditorType.NUMERIC_CONST); } | FLOAT_LITERAL { helper.emit($FLOAT_LITERAL, DroolsEditorType.NUMERIC_CONST); } @@ -731,9 +732,6 @@ selector superSuffix : arguments - // TODO syntactic predicates in the form of `(x) => x` can be safely removed but - // there was originally `DOT ID ((LEFT_PAREN) => arguments)?`. - // Not sure if removing `(LEFT_PAREN) =>` is correct. | DOT IDENTIFIER (arguments)? ; @@ -832,15 +830,16 @@ new_key ; not_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.NOT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.NOT))}? id=DRL_NOT { helper.emit($id, DroolsEditorType.KEYWORD); } ; in_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.IN))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.IN))}? id=DRL_IN { helper.emit($id, DroolsEditorType.KEYWORD); } ; operator_key - : {(helper.isPluggableEvaluator(false))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + // TODO get rid of the DRL_MATCHES token or introduce DRL_CONTAINS etc. for consistency. + : {(helper.isPluggableEvaluator(false))}? id=(IDENTIFIER|DRL_MATCHES) { helper.emit($id, DroolsEditorType.KEYWORD); } ; neg_operator_key diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DescrDumperTest.java b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DescrDumperTest.java new file mode 100644 index 00000000000..d0a18797c1e --- /dev/null +++ b/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DescrDumperTest.java @@ -0,0 +1,367 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.parser; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.drools.compiler.lang.DescrDumper; +import org.drools.compiler.lang.DumperContext; +import org.drools.drl.ast.descr.AtomicExprDescr; +import org.drools.drl.ast.descr.BindingDescr; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +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; + +public class DescrDumperTest { + + private DescrDumper dumper; + + @BeforeEach + public void setUp() throws Exception { + // configure operators + new SetEvaluatorsDefinition(); + new MatchesEvaluatorsDefinition(); + + dumper = new DescrDumper(); + } + + @Test + public void testDump() throws Exception { + String input = "price > 10 && < 20 || == $val || == 30"; + String expected = "( price > 10 && price < 20 || price == $val || price == 30 )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpMatches() throws Exception { + String input = "type.toString matches \"something\\swith\\tsingle escapes\""; + String expected = "type.toString ~= \"something\\swith\\tsingle escapes\""; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpMatches2() throws Exception { + String input = "type.toString matches 'something\\swith\\tsingle escapes'"; + String expected = "type.toString ~= \"something\\swith\\tsingle escapes\""; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpMatches3() throws Exception { + String input = "this[\"content\"] matches \"hello ;=\""; + String expected = "this[\"content\"] ~= \"hello ;=\""; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpContains() throws Exception { + String input = "list contains \"b\""; + String expected = "list contains \"b\""; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpContains2() throws Exception { + String input = "list not contains \"b\""; + String expected = "!( list contains \"b\" )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpExcludes() throws Exception { + String input = "list excludes \"b\""; + String expected = "!( list contains \"b\" )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpExcludes2() throws Exception { + String input = "list not excludes \"b\""; + String expected = "list contains \"b\""; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test @Disabled + public void testDumpWithDateAttr() throws Exception { + String input = "son.birthDate == \"01-jan-2000\""; + String expected = "son.birthDate == org.drools.util.DateUtils.parseDate( \"01-jan-2000\" )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpComplex() throws Exception { + String input = "a ( > 60 && < 70 ) || ( > 50 && < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\""; + String expected = "( ( a > 60 && a < 70 || a > 50 && a < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\" )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpBindings() throws Exception { + String input = "$x : property > value"; + String expected = "property > value"; + + ConstraintConnectiveDescr descr = parse( input ); + DumperContext ctx = new DumperContext(); + String result = dumper.dump( descr, + ctx ); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings().size()).isEqualTo(1); + BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + } + + @Test + public void testDumpBindings2() throws Exception { + String input = "( $a : a > $b : b[10].prop || 10 != 20 ) && $x : someMethod(10) == 20"; + String expected = "( a > b[10].prop || 10 != 20 ) && someMethod(10) == 20"; + + ConstraintConnectiveDescr descr = parse( input ); + DumperContext ctx = new DumperContext(); + String result = dumper.dump( descr, + ctx ); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings().size()).isEqualTo(3); + BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$a"); + assertThat(bind.getExpression()).isEqualTo("a"); + bind = ctx.getBindings().get( 1 ); + assertThat(bind.getVariable()).isEqualTo("$b"); + assertThat(bind.getExpression()).isEqualTo("b[10].prop"); + bind = ctx.getBindings().get( 2 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("someMethod(10)"); + } + + @Test + public void testDumpBindings3() throws Exception { + String input = "( $a : a > $b : b[10].prop || 10 != 20 ) && $x : someMethod(10)"; + String expected = "( a > b[10].prop || 10 != 20 )"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpBindings4() throws Exception { + String input = "( $a : a > $b : b[10].prop || $x : someMethod(10) ) && 10 != 20"; + String expected = "( a > b[10].prop ) && 10 != 20"; + + ConstraintConnectiveDescr descr = parse( input ); + String result = dumper.dump( descr ); + + assertThat(result).isEqualTo(expected); + } + + @Test + public void testDumpBindingsWithRestriction() throws Exception { + String input = "$x : age > 10 && < 20 || > 30"; + String expected = "( age > 10 && age < 20 || age > 30 )"; + + ConstraintConnectiveDescr descr = parse( input ); + DumperContext ctx = new DumperContext(); + String result = dumper.dump( descr, + ctx ); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings().size()).isEqualTo(1); + BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("age"); + } + + @Test + public void testDumpBindingsComplexOp() throws Exception { + String input = "$x : age in (10, 20, $someVal)"; + String expected = "( age == 10 || age == 20 || age == $someVal )"; + + ConstraintConnectiveDescr descr = parse( input ); + DumperContext ctx = new DumperContext(); + String result = dumper.dump( descr, + ctx ); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings().size()).isEqualTo(1); + BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("age"); + } + + @Test + public void testDumpBindingsComplexOp2() throws Exception { + String input = "$x : age not in (10, 20, $someVal)"; + String expected = "age != 10 && age != 20 && age != $someVal"; + + ConstraintConnectiveDescr descr = parse( input ); + DumperContext ctx = new DumperContext(); + String result = dumper.dump( descr, + ctx ); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings().size()).isEqualTo(1); + BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("age"); + } + + @Test + public void testProcessInlineCast() throws Exception { + String expr = "field1#Class.field2"; + String expectedInstanceof = "field1 instanceof Class"; + String expectedcasted = "((Class)field1).field2"; + AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); + ccd.addDescr( atomicExpr ); + String[] instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null); + assertThat(ccd.getDescrs().size()).isEqualTo(2); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedInstanceof); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedcasted); + + expr = "field1#Class1.field2#Class2.field3"; + String expectedInstanceof1 = "field1 instanceof Class1"; + String expectedInstanceof2 = "((Class1)field1).field2 instanceof Class2"; + expectedcasted = "((Class2)((Class1)field1).field2).field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr( ); + instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedInstanceof1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedInstanceof2); + assertThat(instanceofAndCastedExpr[1]).isEqualTo(expectedcasted); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedcasted); + } + + @Test + public void testProcessNullSafeDereferencing() throws Exception { + String expr = "field1!.field2"; + String expectedNullCheck = "field1 != null"; + String expectedExpr = "field1.field2"; + AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); + String[] nullCheckAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedNullCheck); + assertThat(nullCheckAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + + expr = "field1!.field2!.field3"; + String expectedNullCheck1 = "field1 != null"; + String expectedNullCheck2 = "field1.field2 != null"; + expectedExpr = "field1.field2.field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr( ); + nullCheckAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedNullCheck1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedNullCheck2); + assertThat(nullCheckAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + } + + @Test + public void testProcessImplicitConstraints() throws Exception { + String expr = "field1#Class!.field2"; + String expectedConstraints = "field1 instanceof Class"; + String expectedExpr = "((Class)field1).field2"; + AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); + String[] constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints); + assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + + expr = "field1!.field2#Class.field3"; + String expectedConstraints1 = "field1 != null"; + String expectedConstraints2 = "field1.field2 instanceof Class"; + expectedExpr = "((Class)field1.field2).field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr( ); + constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedConstraints2); + assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + + expr = "field1#Class.field2!.field3"; + expectedConstraints1 = "field1 instanceof Class"; + expectedConstraints2 = "((Class)field1).field2 != null"; + expectedExpr = "((Class)field1).field2.field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr( ); + constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedConstraints2); + assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + } + + public ConstraintConnectiveDescr parse( final String constraint ) { + DrlExprParser parser = new DrlExprParser(LanguageLevelOption.DRL6); + ConstraintConnectiveDescr result = parser.parse( constraint ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + return result; + } + +} From 81a0cc2d39be52ea63bff85a1b72eb522e965a94 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 9 Feb 2024 17:50:54 +0900 Subject: [PATCH 053/141] [DROOLS-7591] Experiment branch : migrate a new drools-lsp parser into drools - New parser is migrated in drools-drl/drools-drl-parser with org.drools.drl10.parser package - To enable the new parser, run `mvn test -PDRL10` - At the moment, we get lots of test failures especially in drools-model/drools-model-codegen and drools-test-coverage/test-compiler-integration --- bom/drools-bom/pom.xml | 18 +++ ...nowledgeBuilderRulesConfigurationImpl.java | 1 - .../org/drools/compiler/lang/DescrDumper.java | 3 +- .../compiler/rule/builder/PatternBuilder.java | 3 +- .../rule/builder/QueryElementBuilder.java | 5 +- drools-drl/drools-drl-parser-tests/pom.xml | 81 ++++++++++++ .../drl10}/parser/DRLExprParserTest.java | 5 +- .../drools/drl10}/parser/DRLParserTest.java | 8 +- .../drools/drl10}/parser/DescrDumperTest.java | 5 +- .../drl10}/parser/MiscDRLParserTest.java | 3 +- .../src/test/resources/logback-test.xml | 0 .../drl10}/parser/Rule_with_Extends.drl | 0 .../drl10}/parser/Rule_with_Metadata.drl | 0 .../drl10}/parser/Rule_with_nested_LHS.drl | 0 .../org/drools/drl10}/parser/accumulate.drl | 0 .../parser/accumulateExternalFunction.drl | 0 .../parser/accumulateMultipleFunctions.drl | 0 .../accumulateMultipleFunctionsConstraint.drl | 0 .../drl10}/parser/accumulateReverse.drl | 0 .../parser/accumulate_multi_pattern.drl | 0 .../parser/accumulate_with_bindings.drl | 0 .../parser/accumulate_with_nested_from.drl | 0 .../drl10}/parser/almost_empty_rule.drl | 0 .../org/drools/drl10}/parser/and_or_rule.drl | 0 .../org/drools/drl10}/parser/autofocus.drl | 0 .../drools/drl10}/parser/basic_binding.drl | 0 .../org/drools/drl10}/parser/bindings.drl | 0 .../drl10}/parser/brackets_precedence.drl | 0 .../org/drools/drl10}/parser/collect.drl | 0 .../parser/collect_with_nested_from.drl | 0 .../org/drools/drl10}/parser/comment.drl | 0 .../org/drools/drl10}/parser/complex.dsl | 0 .../parser/declaration-in-consequence.drl | 0 .../parser/declare_type_with_fields.drl | 0 .../org/drools/drl10}/parser/empty_rule.drl | 0 .../org/drools/drl10}/parser/enumeration.drl | 0 .../drl10}/parser/eol_funny_business.drl | 0 .../drools/drl10}/parser/escaped-string.drl | 0 .../drools/drl10}/parser/eval_multiple.drl | 0 .../org/drools/drl10}/parser/eval_parsing.drl | 0 .../drl10}/parser/eval_with_newline.drl | 0 .../parser/expander_multiple_constraints.dslr | 0 .../expander_multiple_constraints_flush.dslr | 0 .../drl10}/parser/expander_spread_lines.dslr | 0 .../drl10}/parser/extra_lhs_newline.drl | 0 .../org/drools/drl10}/parser/forall.drl | 0 .../drools/drl10}/parser/forallwithfrom.drl | 0 .../org/drools/drl10}/parser/from.drl | 0 .../drools/drl10}/parser/function_arrays.drl | 0 .../org/drools/drl10}/parser/functions.drl | 0 .../org/drools/drl10}/parser/globals.drl | 0 .../drools/drl10}/parser/in_operator_test.drl | 0 .../drl10}/parser/lhs_semicolon_delim.drl | 0 .../parser/literal_bool_and_negative.drl | 0 .../drl10}/parser/multiple_constraints.dsl | 0 .../drools/drl10}/parser/multiple_rules.drl | 0 .../parser/nested_conditional_elements.drl | 0 .../org/drools/drl10}/parser/no-loop.drl | 0 .../drl10}/parser/not_exist_with_brackets.drl | 0 .../drl10}/parser/not_with_constraint.drl | 0 .../drl10}/parser/notin_operator_test.drl | 0 .../org/drools/drl10}/parser/or_binding.drl | 0 .../drl10}/parser/or_binding_complex.drl | 0 .../parser/or_binding_with_brackets.drl | 0 .../org/drools/drl10}/parser/or_ce.drl | 0 .../org/drools/drl10}/parser/or_nesting.drl | 0 .../drl10}/parser/package_attributes.drl | 0 .../drl10}/parser/pluggable_operators.drl | 0 .../drl10}/parser/qualified_classname.drl | 0 .../drools/drl10}/parser/query_and_rule.drl | 0 .../drl10}/parser/quoted_string_name_rule.drl | 0 .../drl10}/parser/restrictions_test.drl | 0 .../drools/drl10}/parser/rule_attributes.drl | 0 .../drools/drl10}/parser/rule_attributes2.drl | 0 .../drl10}/parser/rule_attributes_alt.drl | 0 .../parser/rule_calendars_attribute.drl | 0 .../parser/rule_calendars_attribute2.drl | 0 .../parser/rule_duration_expression.drl | 0 .../drl10}/parser/rule_enabled_expression.drl | 0 .../parser/rule_names_number_prefix.drl | 0 .../org/drools/drl10}/parser/rule_not.drl | 0 .../drools/drl10}/parser/ruleflowgroup.drl | 0 .../org/drools/drl10}/parser/semicolon.drl | 0 .../org/drools/drl10}/parser/simple_query.drl | 0 .../org/drools/drl10}/parser/simple_rule.drl | 0 .../drl10}/parser/soundslike_operator.drl | 0 .../drl10}/parser/statement_ordering_1.drl | 0 .../drl10}/parser/ternary_expression.drl | 0 .../test_CommentLineNumbersInConsequence.drl | 0 .../test_ComplexChainedCallWithFrom.drl | 0 .../drl10}/parser/test_EmptyPattern.drl | 0 .../drools/drl10}/parser/test_EndPosition.drl | 0 .../drl10}/parser/test_FunctionImport.drl | 0 .../parser/test_SimpleAccessorArgWithFrom.drl | 0 .../parser/test_SimpleAccessorWithFrom.drl | 0 .../test_SimpleFunctionCallWithFrom.drl | 0 .../parser/test_SimpleMethodCallWithFrom.drl | 0 .../drools/drl10}/parser/type_with_meta.drl | 0 .../org/drools/drl10}/parser/with_eval.drl | 0 .../drools/drl10}/parser/with_predicate.drl | 0 .../org/drools/drl10}/parser/with_retval.drl | 0 drools-drl/drools-drl-parser/pom.xml | 45 +++++++ .../drools/drl10}/parser/DRL6Expressions.g4 | 0 .../org/drools/drl10}/parser/DRLLexer.g4 | 0 .../org/drools/drl10}/parser/DRLParser.g4 | 0 .../org/drools/drl10}/parser/JavaLexer.g4 | 0 .../org/drools/drl10}/parser/JavaParser.g4 | 0 .../org/drools/drl/parser/DRLFactory.java | 3 + .../org/drools/drl/parser/Drl6ExprParser.java | 90 ++++++++++++++ .../org/drools/drl/parser/DrlExprParser.java | 56 +-------- .../drl/parser/DrlExprParserFactory.java | 20 +++ .../java/org/drools/drl/parser/DrlParser.java | 35 +++++- .../drools/drl/parser/lang/DRL10Lexer.java | 46 +++++++ .../drools/drl10/parser/DRLErrorListener.java | 49 ++++++++ .../drools/drl10}/parser/DRLExpressions.java | 2 +- .../drools/drl10}/parser/DRLParserError.java | 20 ++- .../drl10/parser/DRLParserException.java | 30 +++++ .../drools/drl10}/parser/DRLParserHelper.java | 20 ++- .../drl10}/parser/DRLParserWrapper.java | 22 +++- .../drools/drl10}/parser/DRLVisitorImpl.java | 31 +++-- .../drools/drl10/parser}/Developer_Notes.md | 0 .../drools/drl10/parser/Drl10ExprParser.java} | 9 +- .../parser/DroolsParserExceptionFactory.java | 2 +- .../drools/drl10}/parser/ParserHelper.java | 4 +- .../drl10}/parser/ParserStringUtils.java | 20 ++- drools-drl/drools-drl10-parser/.gitignore | 18 --- drools-drl/drools-drl10-parser/pom.xml | 115 ------------------ .../org/drools/parser/DRLErrorListener.java | 31 ----- .../org/drools/parser/DRLParserException.java | 12 -- drools-drl/pom.xml | 1 + .../test-compiler-integration/pom.xml | 21 ++++ .../mvel/compiler/lang/DRLExprParserTest.java | 3 +- .../mvel/compiler/lang/DescrDumperTest.java | 3 +- .../mvel/integrationtests/AlphaNodeTest.java | 4 +- .../visitor/ExprConstraintDescrVisitor.java | 3 +- .../builder/conf/LanguageLevelOption.java | 2 +- pom.xml | 22 ++++ 137 files changed, 602 insertions(+), 269 deletions(-) create mode 100644 drools-drl/drools-drl-parser-tests/pom.xml rename drools-drl/{drools-drl10-parser/src/test/java/org/drools => drools-drl-parser-tests/src/test/java/org/drools/drl10}/parser/DRLExprParserTest.java (98%) rename drools-drl/{drools-drl10-parser/src/test/java/org/drools => drools-drl-parser-tests/src/test/java/org/drools/drl10}/parser/DRLParserTest.java (94%) rename drools-drl/{drools-drl10-parser/src/test/java/org/drools => drools-drl-parser-tests/src/test/java/org/drools/drl10}/parser/DescrDumperTest.java (99%) rename drools-drl/{drools-drl10-parser/src/test/java/org/drools => drools-drl-parser-tests/src/test/java/org/drools/drl10}/parser/MiscDRLParserTest.java (99%) rename drools-drl/{drools-drl10-parser => drools-drl-parser-tests}/src/test/resources/logback-test.xml (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/Rule_with_Extends.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/Rule_with_Metadata.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/Rule_with_nested_LHS.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/accumulate.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/accumulateExternalFunction.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/accumulateMultipleFunctions.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/accumulateMultipleFunctionsConstraint.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/accumulateReverse.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/accumulate_multi_pattern.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/accumulate_with_bindings.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/accumulate_with_nested_from.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/almost_empty_rule.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/and_or_rule.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/autofocus.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/basic_binding.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/bindings.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/brackets_precedence.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/collect.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/collect_with_nested_from.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/comment.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/complex.dsl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/declaration-in-consequence.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/declare_type_with_fields.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/empty_rule.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/enumeration.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/eol_funny_business.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/escaped-string.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/eval_multiple.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/eval_parsing.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/eval_with_newline.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/expander_multiple_constraints.dslr (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/expander_multiple_constraints_flush.dslr (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/expander_spread_lines.dslr (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/extra_lhs_newline.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/forall.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/forallwithfrom.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/from.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/function_arrays.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/functions.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/globals.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/in_operator_test.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/lhs_semicolon_delim.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/literal_bool_and_negative.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/multiple_constraints.dsl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/multiple_rules.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/nested_conditional_elements.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/no-loop.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/not_exist_with_brackets.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/not_with_constraint.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/notin_operator_test.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/or_binding.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/or_binding_complex.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/or_binding_with_brackets.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/or_ce.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/or_nesting.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/package_attributes.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/pluggable_operators.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/qualified_classname.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/query_and_rule.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/quoted_string_name_rule.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/restrictions_test.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/rule_attributes.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/rule_attributes2.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/rule_attributes_alt.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/rule_calendars_attribute.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/rule_calendars_attribute2.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/rule_duration_expression.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/rule_enabled_expression.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/rule_names_number_prefix.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/rule_not.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/ruleflowgroup.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/semicolon.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/simple_query.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/simple_rule.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/soundslike_operator.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/statement_ordering_1.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/ternary_expression.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/test_CommentLineNumbersInConsequence.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/test_ComplexChainedCallWithFrom.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/test_EmptyPattern.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/test_EndPosition.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/test_FunctionImport.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/test_SimpleAccessorArgWithFrom.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/test_SimpleAccessorWithFrom.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/test_SimpleFunctionCallWithFrom.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/test_SimpleMethodCallWithFrom.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/type_with_meta.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/with_eval.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/with_predicate.drl (100%) rename drools-drl/{drools-drl10-parser/src/test/resources/org/drools => drools-drl-parser-tests/src/test/resources/org/drools/drl10}/parser/with_retval.drl (100%) rename drools-drl/{drools-drl10-parser/src/main/antlr4/org/drools => drools-drl-parser/src/main/antlr4/org/drools/drl10}/parser/DRL6Expressions.g4 (100%) rename drools-drl/{drools-drl10-parser/src/main/antlr4/org/drools => drools-drl-parser/src/main/antlr4/org/drools/drl10}/parser/DRLLexer.g4 (100%) rename drools-drl/{drools-drl10-parser/src/main/antlr4/org/drools => drools-drl-parser/src/main/antlr4/org/drools/drl10}/parser/DRLParser.g4 (100%) rename drools-drl/{drools-drl10-parser/src/main/antlr4/org/drools => drools-drl-parser/src/main/antlr4/org/drools/drl10}/parser/JavaLexer.g4 (100%) rename drools-drl/{drools-drl10-parser/src/main/antlr4/org/drools => drools-drl-parser/src/main/antlr4/org/drools/drl10}/parser/JavaParser.g4 (100%) create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java rename drools-drl/{drools-drl10-parser/src/main/java/org/drools => drools-drl-parser/src/main/java/org/drools/drl10}/parser/DRLExpressions.java (98%) rename drools-drl/{drools-drl10-parser/src/main/java/org/drools => drools-drl-parser/src/main/java/org/drools/drl10}/parser/DRLParserError.java (58%) create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java rename drools-drl/{drools-drl10-parser/src/main/java/org/drools => drools-drl-parser/src/main/java/org/drools/drl10}/parser/DRLParserHelper.java (82%) rename drools-drl/{drools-drl10-parser/src/main/java/org/drools => drools-drl-parser/src/main/java/org/drools/drl10}/parser/DRLParserWrapper.java (66%) rename drools-drl/{drools-drl10-parser/src/main/java/org/drools => drools-drl-parser/src/main/java/org/drools/drl10}/parser/DRLVisitorImpl.java (96%) rename drools-drl/{drools-drl10-parser => drools-drl-parser/src/main/java/org/drools/drl10/parser}/Developer_Notes.md (100%) rename drools-drl/{drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java => drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java} (93%) rename drools-drl/{drools-drl10-parser/src/main/java/org/drools => drools-drl-parser/src/main/java/org/drools/drl10}/parser/DroolsParserExceptionFactory.java (99%) rename drools-drl/{drools-drl10-parser/src/main/java/org/drools => drools-drl-parser/src/main/java/org/drools/drl10}/parser/ParserHelper.java (99%) rename drools-drl/{drools-drl10-parser/src/main/java/org/drools => drools-drl-parser/src/main/java/org/drools/drl10}/parser/ParserStringUtils.java (70%) delete mode 100644 drools-drl/drools-drl10-parser/.gitignore delete mode 100644 drools-drl/drools-drl10-parser/pom.xml delete mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java delete mode 100644 drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserException.java diff --git a/bom/drools-bom/pom.xml b/bom/drools-bom/pom.xml index 55081e52f90..ff4d590700f 100644 --- a/bom/drools-bom/pom.xml +++ b/bom/drools-bom/pom.xml @@ -786,6 +786,24 @@ test-jar test + + org.drools + drools-drl10-parser + ${project.version} + + + org.drools + drools-drl10-parser + ${project.version} + sources + + + org.drools + drools-drl10-parser + ${project.version} + test-jar + test + org.drools drools-compiler diff --git a/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java b/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java index 0c90262aa28..48e3e4971f1 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java @@ -127,7 +127,6 @@ public KnowledgeBuilderRulesConfigurationImpl(CompositeConfiguration + + + + 4.0.0 + + org.drools + drools-drl + 999-SNAPSHOT + + + org.drools + drools-drl-parser-tests + + Drools :: DRL :: Parser :: Tests + + + org.drools.drl.parser.tests + + + + + + org.assertj + assertj-core + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + ch.qos.logback + logback-classic + test + + + + org.drools + drools-drl-parser + test + + + org.drools + drools-compiler + test + + + org.drools + drools-mvel + test + + + + diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java similarity index 98% rename from drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java rename to drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java index f233439f360..1f27a9c861e 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLExprParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.parser; +package org.drools.drl10.parser; import static org.assertj.core.api.Assertions.assertThat; @@ -25,6 +25,7 @@ import org.drools.drl.ast.descr.ConnectiveType; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; import org.drools.drl.ast.descr.RelationalExprDescr; +import org.drools.drl.parser.DrlExprParser; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,7 +41,7 @@ public class DRLExprParserTest { @BeforeEach public void setUp() throws Exception { - this.parser = new DrlExprParser(LanguageLevelOption.DRL6); + this.parser = new Drl10ExprParser(LanguageLevelOption.DRL6); } @AfterEach diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java similarity index 94% rename from drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java rename to drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java index 83a8b1f5d23..35c4638ebc1 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java @@ -1,4 +1,4 @@ -package org.drools.parser; +package org.drools.drl10.parser; import java.util.List; @@ -13,9 +13,9 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.drools.parser.DRLParserHelper.computeTokenIndex; -import static org.drools.parser.DRLParserHelper.createDrlParser; -import static org.drools.parser.DRLParserHelper.parse; +import static org.drools.drl10.parser.DRLParserHelper.computeTokenIndex; +import static org.drools.drl10.parser.DRLParserHelper.createDrlParser; +import static org.drools.drl10.parser.DRLParserHelper.parse; class DRLParserTest { diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DescrDumperTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java similarity index 99% rename from drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DescrDumperTest.java rename to drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java index d0a18797c1e..d98ec8ec895 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/DescrDumperTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.parser; +package org.drools.drl10.parser; import static org.assertj.core.api.Assertions.assertThat; @@ -25,6 +25,7 @@ import org.drools.drl.ast.descr.AtomicExprDescr; import org.drools.drl.ast.descr.BindingDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.DrlExprParser; import org.drools.mvel.evaluators.MatchesEvaluatorsDefinition; import org.drools.mvel.evaluators.SetEvaluatorsDefinition; import org.junit.jupiter.api.BeforeEach; @@ -357,7 +358,7 @@ public void testProcessImplicitConstraints() throws Exception { } public ConstraintConnectiveDescr parse( final String constraint ) { - DrlExprParser parser = new DrlExprParser(LanguageLevelOption.DRL6); + DrlExprParser parser = new Drl10ExprParser(LanguageLevelOption.DRL6); ConstraintConnectiveDescr result = parser.parse( constraint ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); diff --git a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java similarity index 99% rename from drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java rename to drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java index 229524867d5..6353be53ac7 100644 --- a/drools-drl/drools-drl10-parser/src/test/java/org/drools/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java @@ -1,4 +1,4 @@ -package org.drools.parser; +package org.drools.drl10.parser; import java.io.BufferedReader; import java.io.IOException; @@ -39,6 +39,7 @@ import org.drools.drl.ast.descr.TypeDeclarationDescr; import org.drools.drl.ast.descr.TypeFieldDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl10.parser.DRLParserWrapper; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; diff --git a/drools-drl/drools-drl10-parser/src/test/resources/logback-test.xml b/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/logback-test.xml rename to drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Extends.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Extends.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Metadata.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_Metadata.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_nested_LHS.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/Rule_with_nested_LHS.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateExternalFunction.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateExternalFunction.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctions.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctionsConstraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateMultipleFunctionsConstraint.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateReverse.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulateReverse.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_multi_pattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_multi_pattern.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_bindings.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/accumulate_with_nested_from.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/almost_empty_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/almost_empty_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/and_or_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/and_or_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/autofocus.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/autofocus.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/basic_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/basic_binding.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/bindings.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/brackets_precedence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/brackets_precedence.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/collect_with_nested_from.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/comment.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/comment.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/complex.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/complex.dsl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declaration-in-consequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declaration-in-consequence.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declare_type_with_fields.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declare_type_with_fields.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/declare_type_with_fields.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declare_type_with_fields.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/empty_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/empty_rule.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/empty_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/empty_rule.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/enumeration.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/enumeration.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/enumeration.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/enumeration.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eol_funny_business.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eol_funny_business.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eol_funny_business.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eol_funny_business.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/escaped-string.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/escaped-string.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/escaped-string.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/escaped-string.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_multiple.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_multiple.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_multiple.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_multiple.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_parsing.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_parsing.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_parsing.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_parsing.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_with_newline.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_with_newline.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/eval_with_newline.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_with_newline.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints.dslr b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints.dslr similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints.dslr rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints.dslr diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints_flush.dslr b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints_flush.dslr similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_multiple_constraints_flush.dslr rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints_flush.dslr diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_spread_lines.dslr b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_spread_lines.dslr similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/expander_spread_lines.dslr rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_spread_lines.dslr diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/extra_lhs_newline.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/extra_lhs_newline.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/extra_lhs_newline.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/extra_lhs_newline.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forall.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forall.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forall.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forall.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forallwithfrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/forallwithfrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/from.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/function_arrays.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/function_arrays.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/functions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/functions.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/globals.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/globals.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/in_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/in_operator_test.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/lhs_semicolon_delim.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/lhs_semicolon_delim.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/literal_bool_and_negative.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/literal_bool_and_negative.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_constraints.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_constraints.dsl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_rules.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/multiple_rules.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/nested_conditional_elements.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/nested_conditional_elements.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/no-loop.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/no-loop.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_exist_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_exist_with_brackets.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_with_constraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/not_with_constraint.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/notin_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/notin_operator_test.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_complex.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_complex.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_binding_with_brackets.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_ce.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_ce.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_nesting.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/or_nesting.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/package_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/package_attributes.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/pluggable_operators.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/pluggable_operators.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/qualified_classname.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/qualified_classname.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/query_and_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/query_and_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/quoted_string_name_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/quoted_string_name_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/restrictions_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/restrictions_test.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes2.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes_alt.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_attributes_alt.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_calendars_attribute2.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_duration_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_duration_expression.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_enabled_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_enabled_expression.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_names_number_prefix.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_names_number_prefix.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_not.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/rule_not.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/ruleflowgroup.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/ruleflowgroup.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/semicolon.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/semicolon.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_query.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_query.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/simple_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/soundslike_operator.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/soundslike_operator.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/statement_ordering_1.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/statement_ordering_1.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/ternary_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/ternary_expression.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_CommentLineNumbersInConsequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_CommentLineNumbersInConsequence.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_ComplexChainedCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_ComplexChainedCallWithFrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EmptyPattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EmptyPattern.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EndPosition.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_EndPosition.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_FunctionImport.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_FunctionImport.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorArgWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorArgWithFrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleAccessorWithFrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleFunctionCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleFunctionCallWithFrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleMethodCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/test_SimpleMethodCallWithFrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/type_with_meta.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/type_with_meta.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_eval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_eval.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_predicate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_predicate.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl diff --git a/drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_retval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl similarity index 100% rename from drools-drl/drools-drl10-parser/src/test/resources/org/drools/parser/with_retval.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl diff --git a/drools-drl/drools-drl-parser/pom.xml b/drools-drl/drools-drl-parser/pom.xml index 545625e5ad4..0eeb7871009 100644 --- a/drools-drl/drools-drl-parser/pom.xml +++ b/drools-drl/drools-drl-parser/pom.xml @@ -66,7 +66,32 @@ org.antlr antlr-runtime + + org.antlr + antlr4-runtime + + + + org.assertj + assertj-core + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + ch.qos.logback + logback-classic + test + @@ -101,6 +126,26 @@ + + + + org.antlr + antlr4-maven-plugin + ${version.org.antlr4} + + + + antlr4 + + + true + false + src/main/antlr4/org/drools/drl10/parser/ + + + + + diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 similarity index 100% rename from drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRL6Expressions.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 similarity index 100% rename from drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLLexer.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 similarity index 100% rename from drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/DRLParser.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 similarity index 100% rename from drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaLexer.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 diff --git a/drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 similarity index 100% rename from drools-drl/drools-drl10-parser/src/main/antlr4/org/drools/parser/JavaParser.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java index 15bf0addf05..71b23c2fdd3 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java @@ -25,6 +25,7 @@ import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognizerSharedState; import org.antlr.runtime.TokenStream; +import org.drools.drl.parser.lang.DRL10Lexer; import org.drools.drl.parser.lang.DRL5Expressions; import org.drools.drl.parser.lang.DRL5Lexer; import org.drools.drl.parser.lang.DRL5Parser; @@ -113,6 +114,8 @@ public static DRLLexer getDRLLexer(CharStream input, LanguageLevelOption languag case DRL6: case DRL6_STRICT: return new DRL6Lexer(input); + case DRL10: + return new DRL10Lexer(); } throw new RuntimeException("Unknown language level"); } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java new file mode 100644 index 00000000000..9fb0186afb7 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java @@ -0,0 +1,90 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser; + +import java.util.Collections; +import java.util.List; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.RecognizerSharedState; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.lang.DRLExpressions; +import org.drools.drl.parser.lang.DRLLexer; +import org.drools.drl.parser.lang.ParserHelper; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * This is a helper class that provides helper methods to parse expressions + * using both the DRLExpressions parser and the DRLExprTree parser. + */ +public class Drl6ExprParser implements DrlExprParser { + + private ParserHelper helper = null; + + private final LanguageLevelOption languageLevel; + + public Drl6ExprParser(LanguageLevelOption languageLevel) { + this.languageLevel = languageLevel; + } + + /** Parse an expression from text */ + public ConstraintConnectiveDescr parse( final String text ) { + ConstraintConnectiveDescr constraint = null; + try { + DRLLexer lexer = DRLFactory.getDRLLexer(new ANTLRStringStream(text), languageLevel); + CommonTokenStream input = new CommonTokenStream( lexer ); + RecognizerSharedState state = new RecognizerSharedState(); + helper = new ParserHelper( input, state, languageLevel ); + DRLExpressions parser = DRLFactory.getDRLExpressions(input, state, helper, languageLevel); + parser.setBuildDescr( true ); + parser.setLeftMostExpr( null ); // setting initial value just in case + BaseDescr expr = parser.conditionalOrExpression(); + if ( expr != null && !parser.hasErrors() ) { + constraint = ConstraintConnectiveDescr.newAnd(); + constraint.addOrMerge( expr ); + } + } catch ( RecognitionException e ) { + helper.reportError( e ); + } + return constraint; + } + + public String getLeftMostExpr() { + return helper != null ? helper.getLeftMostExpr() : null; + } + + /** + * @return true if there were parser errors. + */ + public boolean hasErrors() { + return helper != null && helper.hasErrors(); + } + + /** + * @return a list of errors found while parsing. + */ + @SuppressWarnings("unchecked") + public List getErrors() { + return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; + } + +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java index 60c61ac248d..0702a1d1461 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java @@ -18,73 +18,29 @@ */ package org.drools.drl.parser; -import java.util.Collections; import java.util.List; -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.RecognizerSharedState; -import org.drools.drl.parser.lang.DRLExpressions; -import org.drools.drl.parser.lang.DRLLexer; -import org.drools.drl.parser.lang.ParserHelper; -import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; -import org.kie.internal.builder.conf.LanguageLevelOption; /** * This is a helper class that provides helper methods to parse expressions * using both the DRLExpressions parser and the DRLExprTree parser. */ -public class DrlExprParser { - - private ParserHelper helper = null; - - private final LanguageLevelOption languageLevel; - - public DrlExprParser(LanguageLevelOption languageLevel) { - this.languageLevel = languageLevel; - } +public interface DrlExprParser { /** Parse an expression from text */ - public ConstraintConnectiveDescr parse( final String text ) { - ConstraintConnectiveDescr constraint = null; - try { - DRLLexer lexer = DRLFactory.getDRLLexer(new ANTLRStringStream(text), languageLevel); - CommonTokenStream input = new CommonTokenStream( lexer ); - RecognizerSharedState state = new RecognizerSharedState(); - helper = new ParserHelper( input, state, languageLevel ); - DRLExpressions parser = DRLFactory.getDRLExpressions(input, state, helper, languageLevel); - parser.setBuildDescr( true ); - parser.setLeftMostExpr( null ); // setting initial value just in case - BaseDescr expr = parser.conditionalOrExpression(); - if ( expr != null && !parser.hasErrors() ) { - constraint = ConstraintConnectiveDescr.newAnd(); - constraint.addOrMerge( expr ); - } - } catch ( RecognitionException e ) { - helper.reportError( e ); - } - return constraint; - } - - public String getLeftMostExpr() { - return helper != null ? helper.getLeftMostExpr() : null; - } + ConstraintConnectiveDescr parse( final String text ); + + String getLeftMostExpr(); /** * @return true if there were parser errors. */ - public boolean hasErrors() { - return helper != null && helper.hasErrors(); - } + boolean hasErrors(); /** * @return a list of errors found while parsing. */ @SuppressWarnings("unchecked") - public List getErrors() { - return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; - } - + List getErrors(); } 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 new file mode 100644 index 00000000000..9ee116faf37 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java @@ -0,0 +1,20 @@ +package org.drools.drl.parser; + +import org.drools.drl10.parser.Drl10ExprParser; +import org.kie.internal.builder.conf.LanguageLevelOption; + +public class DrlExprParserFactory { + + public static DrlExprParser getDrlExrParser(LanguageLevelOption languageLevel) { + switch (languageLevel) { + case DRL5: + case DRL6: + case DRL6_STRICT: + 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 7b852c8dce3..d6ee0c042bb 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 @@ -18,6 +18,8 @@ */ package org.drools.drl.parser; +import org.drools.drl10.parser.DRLParserError; +import org.drools.drl10.parser.DRLParserWrapper; import org.drools.io.InternalResource; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.parser.lang.DRLLexer; @@ -164,10 +166,35 @@ public PackageDescr parse(final boolean isEditor, final InputStream is) throws DroolsParserException, IOException { this.resource = resource; String encoding = resource instanceof InternalResource ? ((InternalResource) resource).getEncoding() : null; - - lexer = DRLFactory.buildLexer(is, encoding, languageLevel); - DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); - return compile(isEditor, parser); + System.out.println("### parse : languageLevel = " + languageLevel); + if (languageLevel == LanguageLevelOption.DRL10) { + // new parser based on antlr4 + try { + DRLParserWrapper parser = new DRLParserWrapper(); + PackageDescr packageDescr = parser.parse(is); + for (final DRLParserError drlParserError : parser.getErrors()) { + final ParserError err = new ParserError(resource, + drlParserError.getMessage(), + drlParserError.getLineNumber(), + drlParserError.getColumn()); + this.results.add(err); + } + return !this.hasErrors() ? packageDescr : null; + } catch (Exception e) { + LOG.error("Exception", e); + final ParserError err = new ParserError(resource, + GENERIC_ERROR_MESSAGE + e.toString() + "\n" + Arrays.toString(e.getStackTrace()), + -1, + 0); + this.results.add(err); + throw new DroolsParserException(GENERIC_ERROR_MESSAGE + e.getMessage(), e); + } + } else { + // old parsers based on antlr3 + lexer = DRLFactory.buildLexer(is, encoding, languageLevel); + DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); + return compile(isEditor, parser); + } } /** diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java new file mode 100644 index 00000000000..ae8d3d6d4d3 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java @@ -0,0 +1,46 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.lang; + +import java.util.List; + +import org.antlr.runtime.Token; +import org.drools.drl.parser.DroolsParserException; + +/** + * No implementation because everything is handled by DRL10Parser + */ +public class DRL10Lexer implements DRLLexer { + + @Override + public String getSourceName() { + return null; + } + + @Override + public Token nextToken() { + return null; + } + + @Override + public List getErrors() { + return null; + } + +} \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java new file mode 100644 index 00000000000..0e5b5985b6c --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java @@ -0,0 +1,49 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +import java.util.ArrayList; +import java.util.List; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; + +/** + * Collect errors while parsing DRL + */ +public class DRLErrorListener extends BaseErrorListener { + + private final List errors = new ArrayList<>(); + + public List getErrors() { + return errors; + } + + @Override + public void syntaxError(Recognizer recognizer, + Object offendingSymbol, + int line, + int charPositionInLine, + String msg, + RecognitionException e) { + + errors.add(new DRLParserError(line, charPositionInLine, msg)); + } +} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java similarity index 98% rename from drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java index 0109e233774..e7aa8102c48 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLExpressions.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.parser; +package org.drools.drl10.parser; import java.util.LinkedList; import java.util.List; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java similarity index 58% rename from drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java index ec3e41747df..4b893e11e46 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserError.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java @@ -1,4 +1,22 @@ -package org.drools.parser; +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; /** * Error information while parsing DRL diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java new file mode 100644 index 00000000000..833d1aa8df0 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; + +public class DRLParserException extends RuntimeException { + + public DRLParserException() { + super(); + } + + public DRLParserException(String message) { + super(message); + } +} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java similarity index 82% rename from drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java index bd95c3033c5..f4436bf44b0 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java @@ -1,4 +1,22 @@ -package org.drools.parser; +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; import java.io.IOException; import java.io.InputStream; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java similarity index 66% rename from drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java index 88ae36c12fe..914255e1375 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserWrapper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java @@ -1,4 +1,22 @@ -package org.drools.parser; +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; import java.io.InputStream; import java.util.ArrayList; @@ -9,7 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.drools.parser.DRLParserHelper.compilationUnitContext2PackageDescr; +import static org.drools.drl10.parser.DRLParserHelper.compilationUnitContext2PackageDescr; /** * Wrapper for DRLParser. Somewhat duplicated from DRLParserHelper, but this class is instantiated and holds errors. diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java similarity index 96% rename from drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java index 3f920cc13a5..a977fee9882 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java @@ -1,8 +1,25 @@ -package org.drools.parser; +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; import java.util.ArrayList; import java.util.List; -import java.util.Optional; import java.util.stream.Collectors; import org.antlr.v4.runtime.ParserRuleContext; @@ -41,11 +58,11 @@ import org.drools.drl.ast.descr.UnitDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; -import static org.drools.parser.DRLParserHelper.getTextWithoutErrorNode; -import static org.drools.parser.ParserStringUtils.getTextPreservingWhitespace; -import static org.drools.parser.ParserStringUtils.getTokenTextPreservingWhitespace; -import static org.drools.parser.ParserStringUtils.safeStripStringDelimiters; -import static org.drools.parser.ParserStringUtils.trimThen; +import static org.drools.drl10.parser.DRLParserHelper.getTextWithoutErrorNode; +import static org.drools.drl10.parser.ParserStringUtils.getTextPreservingWhitespace; +import static org.drools.drl10.parser.ParserStringUtils.getTokenTextPreservingWhitespace; +import static org.drools.drl10.parser.ParserStringUtils.safeStripStringDelimiters; +import static org.drools.drl10.parser.ParserStringUtils.trimThen; import static org.drools.util.StringUtils.unescapeJava; /** diff --git a/drools-drl/drools-drl10-parser/Developer_Notes.md b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md similarity index 100% rename from drools-drl/drools-drl10-parser/Developer_Notes.md rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java similarity index 93% rename from drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java index d9c8d93bcee..19ec4735363 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DrlExprParser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java @@ -16,16 +16,17 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.parser; +package org.drools.drl10.parser; import java.util.Collections; import java.util.List; -import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.RecognitionException; import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.DrlExprParser; import org.drools.drl.parser.DroolsParserException; import org.kie.internal.builder.conf.LanguageLevelOption; @@ -33,13 +34,13 @@ * This is a helper class that provides helper methods to parse expressions * using both the DRLExpressions parser and the DRLExprTree parser. */ -public class DrlExprParser { +public class Drl10ExprParser implements DrlExprParser { private ParserHelper helper = null; private final LanguageLevelOption languageLevel; - public DrlExprParser(LanguageLevelOption languageLevel) { + public Drl10ExprParser(LanguageLevelOption languageLevel) { this.languageLevel = languageLevel; } diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java similarity index 99% rename from drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java index e184dfe9e37..abf586c55d0 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DroolsParserExceptionFactory.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.parser; +package org.drools.drl10.parser; import java.io.PrintWriter; import java.io.StringWriter; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java similarity index 99% rename from drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java index 66d6bea4d6b..f729115b7ca 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserHelper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java @@ -29,7 +29,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.drools.parser; +package org.drools.drl10.parser; import java.util.ArrayDeque; import java.util.ArrayList; @@ -39,8 +39,8 @@ import java.util.List; import java.util.Map; -import org.antlr.v4.runtime.CommonToken; import org.antlr.runtime.RecognizerSharedState; +import org.antlr.v4.runtime.CommonToken; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java similarity index 70% rename from drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java index a294bf2a923..ef22da2dce3 100644 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/ParserStringUtils.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java @@ -1,4 +1,22 @@ -package org.drools.parser; +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl10.parser; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.TokenStream; diff --git a/drools-drl/drools-drl10-parser/.gitignore b/drools-drl/drools-drl10-parser/.gitignore deleted file mode 100644 index 6fc57b48ec6..00000000000 --- a/drools-drl/drools-drl10-parser/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -target/ -gen/ -local/ - -# Eclipse, Netbeans and IntelliJ files -.* -!.gitignore -!.github -nbproject -*.ipr -*.iws -*.iml - -# generated files -dependency-reduced-pom.xml - -#CI -!.ci diff --git a/drools-drl/drools-drl10-parser/pom.xml b/drools-drl/drools-drl10-parser/pom.xml deleted file mode 100644 index 57ed8f85ca5..00000000000 --- a/drools-drl/drools-drl10-parser/pom.xml +++ /dev/null @@ -1,115 +0,0 @@ - - - - 4.0.0 - - - org.drools - drools-lsp - 1.0.0-SNAPSHOT - - - drools-parser - - Drools :: Parser - - - - org.drools - drools-drl-ast - ${version.org.drools} - - - org.drools - drools-util - ${version.org.drools} - - - org.drools - drools-drl-parser - ${version.org.drools} - - - - - org.antlr - antlr4-runtime - ${version.org.antlr4} - - - org.antlr - antlr4 - ${version.org.antlr4} - test - - - org.glassfish - javax.json - - - - - - - org.assertj - assertj-core - ${version.org.assertj} - test - - - org.junit.jupiter - junit-jupiter-api - ${version.org.junit} - test - - - org.junit.jupiter - junit-jupiter-engine - ${version.org.junit} - test - - - ch.qos.logback - logback-classic - ${version.ch.qos.logback} - test - - - org.drools - drools-compiler - ${version.org.drools} - test - - - org.drools - drools-mvel - ${version.org.drools} - test - - - - - - - org.antlr - antlr4-maven-plugin - ${version.org.antlr4} - - - - antlr4 - - - true - false - src/main/antlr4/org/drools/parser/ - - - - - - - - - diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java deleted file mode 100644 index f7c6504df4c..00000000000 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLErrorListener.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.drools.parser; - -import java.util.ArrayList; -import java.util.List; - -import org.antlr.v4.runtime.BaseErrorListener; -import org.antlr.v4.runtime.RecognitionException; -import org.antlr.v4.runtime.Recognizer; - -/** - * Collect errors while parsing DRL - */ -public class DRLErrorListener extends BaseErrorListener { - - private final List errors = new ArrayList<>(); - - public List getErrors() { - return errors; - } - - @Override - public void syntaxError(Recognizer recognizer, - Object offendingSymbol, - int line, - int charPositionInLine, - String msg, - RecognitionException e) { - - errors.add(new DRLParserError(line, charPositionInLine, msg)); - } -} diff --git a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserException.java b/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserException.java deleted file mode 100644 index 6bc5812a78f..00000000000 --- a/drools-drl/drools-drl10-parser/src/main/java/org/drools/parser/DRLParserException.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.drools.parser; - -public class DRLParserException extends RuntimeException { - - public DRLParserException() { - super(); - } - - public DRLParserException(String message) { - super(message); - } -} diff --git a/drools-drl/pom.xml b/drools-drl/pom.xml index 91f12f3d758..2fb61bb3006 100644 --- a/drools-drl/pom.xml +++ b/drools-drl/pom.xml @@ -39,6 +39,7 @@ drools-drl-ast drools-drl-extensions drools-drl-parser + drools-drl-parser-tests diff --git a/drools-test-coverage/test-compiler-integration/pom.xml b/drools-test-coverage/test-compiler-integration/pom.xml index 6ccf1cbdc67..93df94a6d58 100644 --- a/drools-test-coverage/test-compiler-integration/pom.xml +++ b/drools-test-coverage/test-compiler-integration/pom.xml @@ -178,6 +178,27 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java index 08eeb33edae..c7357aad4de 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java @@ -25,6 +25,7 @@ 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.junit.After; import org.junit.Before; import org.junit.Test; @@ -42,7 +43,7 @@ public class DRLExprParserTest { @Before public void setUp() throws Exception { new EvaluatorRegistry(); - this.parser = new DrlExprParser(LanguageLevelOption.DRL6); + this.parser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL6); } @After diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java index 649b43c37fe..5eb52e62830 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java @@ -24,6 +24,7 @@ import org.drools.drl.ast.descr.AtomicExprDescr; import org.drools.drl.ast.descr.BindingDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.DrlExprParserFactory; import org.drools.mvel.evaluators.MatchesEvaluatorsDefinition; import org.drools.mvel.evaluators.SetEvaluatorsDefinition; import org.junit.Before; @@ -358,7 +359,7 @@ public void testProcessImplicitConstraints() throws Exception { } public ConstraintConnectiveDescr parse( final String constraint ) { - DrlExprParser parser = new DrlExprParser(LanguageLevelOption.DRL6); + DrlExprParser parser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL6); ConstraintConnectiveDescr result = parser.parse( constraint ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java index d4089c34601..71642c17289 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java @@ -48,6 +48,8 @@ public static Collection getParameters() { @Test public void testAlpha() { + + String str = "import " + Person.class.getCanonicalName() + "\n" + "rule R1 when\n" + @@ -195,7 +197,7 @@ public void testBetaModifyWithAlpha() { " $p : Person(name == \"Mario\")\n" + " $s : String(this == $p.name)\n" + "then\n" + - " modify($p) { setName(\"Mark\") }" + + " modify($p) { setName(\"Mark\") }\n" + "end\n" + "rule R2 when\n" + " $p : Person(name == \"Mark\")\n" + diff --git a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java index ba67c653c3e..6e6ef96a82a 100644 --- a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java +++ b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java @@ -20,6 +20,7 @@ import java.util.List; +import org.drools.drl.parser.DrlExprParserFactory; import org.drools.drl.parser.impl.Operator; import org.drools.drl.parser.DrlExprParser; import org.drools.drl.ast.descr.AtomicExprDescr; @@ -57,7 +58,7 @@ public ExprConstraintDescrVisitor(Pattern pattern, VerifierData data, OrderNumbe public void visit(ExprConstraintDescr descr) { - DrlExprParser drlExprParser = new DrlExprParser(LanguageLevelOption.DRL5); + DrlExprParser drlExprParser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL5); ConstraintConnectiveDescr constraintConnectiveDescr = drlExprParser.parse(descr.getExpression()); visit(constraintConnectiveDescr.getDescrs()); 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; diff --git a/pom.xml b/pom.xml index 5fae74ed325..40f4d9d7240 100644 --- a/pom.xml +++ b/pom.xml @@ -310,6 +310,28 @@ + + + DRL10 + + + DRL10 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + DRL10 + + + + + + From 39f4d6411d6315514502b47e9e27203f8a95ca48 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 13 Feb 2024 15:10:28 +0900 Subject: [PATCH 054/141] - License header - Revert an inappropriate test edit - Removed unnecessary profile - Clarify unsupported methods - Removed unnecessary bom dependency --- bom/drools-bom/pom.xml | 18 ------------ .../drools/drl10/parser/Rule_with_Extends.drl | 26 +++++++++-------- .../drl10/parser/Rule_with_Metadata.drl | 26 +++++++++-------- .../drl10/parser/Rule_with_nested_LHS.drl | 26 +++++++++-------- .../org/drools/drl10/parser/accumulate.drl | 26 +++++++++-------- .../parser/accumulateExternalFunction.drl | 26 +++++++++-------- .../parser/accumulateMultipleFunctions.drl | 26 +++++++++-------- .../accumulateMultipleFunctionsConstraint.drl | 26 +++++++++-------- .../drools/drl10/parser/accumulateReverse.drl | 26 +++++++++-------- .../drl10/parser/accumulate_multi_pattern.drl | 26 +++++++++-------- .../drl10/parser/accumulate_with_bindings.drl | 26 +++++++++-------- .../parser/accumulate_with_nested_from.drl | 26 +++++++++-------- .../drools/drl10/parser/almost_empty_rule.drl | 26 +++++++++-------- .../org/drools/drl10/parser/and_or_rule.drl | 26 +++++++++-------- .../org/drools/drl10/parser/autofocus.drl | 26 +++++++++-------- .../org/drools/drl10/parser/basic_binding.drl | 26 +++++++++-------- .../org/drools/drl10/parser/bindings.drl | 26 +++++++++-------- .../drl10/parser/brackets_precedence.drl | 26 +++++++++-------- .../org/drools/drl10/parser/collect.drl | 26 +++++++++-------- .../drl10/parser/collect_with_nested_from.drl | 26 +++++++++-------- .../org/drools/drl10/parser/comment.drl | 26 +++++++++-------- .../parser/declaration-in-consequence.drl | 26 +++++++++-------- .../drl10/parser/declare_type_with_fields.drl | 26 +++++++++-------- .../org/drools/drl10/parser/empty_rule.drl | 26 +++++++++-------- .../org/drools/drl10/parser/enumeration.drl | 26 +++++++++-------- .../drl10/parser/eol_funny_business.drl | 26 +++++++++-------- .../drools/drl10/parser/escaped-string.drl | 26 +++++++++-------- .../org/drools/drl10/parser/eval_multiple.drl | 26 +++++++++-------- .../org/drools/drl10/parser/eval_parsing.drl | 26 +++++++++-------- .../drools/drl10/parser/eval_with_newline.drl | 26 +++++++++-------- .../drools/drl10/parser/extra_lhs_newline.drl | 26 +++++++++-------- .../org/drools/drl10/parser/forall.drl | 26 +++++++++-------- .../drools/drl10/parser/forallwithfrom.drl | 26 +++++++++-------- .../org/drools/drl10/parser/from.drl | 26 +++++++++-------- .../drools/drl10/parser/function_arrays.drl | 26 +++++++++-------- .../org/drools/drl10/parser/functions.drl | 26 +++++++++-------- .../org/drools/drl10/parser/globals.drl | 26 +++++++++-------- .../drools/drl10/parser/in_operator_test.drl | 26 +++++++++-------- .../drl10/parser/lhs_semicolon_delim.drl | 26 +++++++++-------- .../parser/literal_bool_and_negative.drl | 26 +++++++++-------- .../drools/drl10/parser/multiple_rules.drl | 26 +++++++++-------- .../parser/nested_conditional_elements.drl | 26 +++++++++-------- .../org/drools/drl10/parser/no-loop.drl | 26 +++++++++-------- .../drl10/parser/not_exist_with_brackets.drl | 26 +++++++++-------- .../drl10/parser/not_with_constraint.drl | 26 +++++++++-------- .../drl10/parser/notin_operator_test.drl | 26 +++++++++-------- .../org/drools/drl10/parser/or_binding.drl | 26 +++++++++-------- .../drl10/parser/or_binding_complex.drl | 26 +++++++++-------- .../drl10/parser/or_binding_with_brackets.drl | 26 +++++++++-------- .../org/drools/drl10/parser/or_ce.drl | 26 +++++++++-------- .../org/drools/drl10/parser/or_nesting.drl | 26 +++++++++-------- .../drl10/parser/package_attributes.drl | 26 +++++++++-------- .../drl10/parser/pluggable_operators.drl | 26 +++++++++-------- .../drl10/parser/qualified_classname.drl | 26 +++++++++-------- .../drools/drl10/parser/query_and_rule.drl | 26 +++++++++-------- .../drl10/parser/quoted_string_name_rule.drl | 26 +++++++++-------- .../drools/drl10/parser/restrictions_test.drl | 26 +++++++++-------- .../drools/drl10/parser/rule_attributes.drl | 26 +++++++++-------- .../drools/drl10/parser/rule_attributes2.drl | 26 +++++++++-------- .../drl10/parser/rule_attributes_alt.drl | 26 +++++++++-------- .../drl10/parser/rule_calendars_attribute.drl | 26 +++++++++-------- .../parser/rule_calendars_attribute2.drl | 26 +++++++++-------- .../drl10/parser/rule_duration_expression.drl | 26 +++++++++-------- .../drl10/parser/rule_enabled_expression.drl | 26 +++++++++-------- .../drl10/parser/rule_names_number_prefix.drl | 26 +++++++++-------- .../org/drools/drl10/parser/rule_not.drl | 26 +++++++++-------- .../org/drools/drl10/parser/ruleflowgroup.drl | 26 +++++++++-------- .../org/drools/drl10/parser/semicolon.drl | 26 +++++++++-------- .../org/drools/drl10/parser/simple_query.drl | 26 +++++++++-------- .../org/drools/drl10/parser/simple_rule.drl | 28 +++++++++---------- .../drl10/parser/soundslike_operator.drl | 26 +++++++++-------- .../drl10/parser/statement_ordering_1.drl | 26 +++++++++-------- .../drl10/parser/ternary_expression.drl | 26 +++++++++-------- .../test_CommentLineNumbersInConsequence.drl | 26 +++++++++-------- .../test_ComplexChainedCallWithFrom.drl | 26 +++++++++-------- .../drools/drl10/parser/test_EmptyPattern.drl | 26 +++++++++-------- .../drools/drl10/parser/test_EndPosition.drl | 26 +++++++++-------- .../drl10/parser/test_FunctionImport.drl | 26 +++++++++-------- .../parser/test_SimpleAccessorArgWithFrom.drl | 26 +++++++++-------- .../parser/test_SimpleAccessorWithFrom.drl | 26 +++++++++-------- .../test_SimpleFunctionCallWithFrom.drl | 26 +++++++++-------- .../parser/test_SimpleMethodCallWithFrom.drl | 26 +++++++++-------- .../drools/drl10/parser/type_with_meta.drl | 26 +++++++++-------- .../org/drools/drl10/parser/with_eval.drl | 26 +++++++++-------- .../drools/drl10/parser/with_predicate.drl | 26 +++++++++-------- .../org/drools/drl10/parser/with_retval.drl | 26 +++++++++-------- .../drools/drl/parser/lang/DRL10Lexer.java | 6 ++-- .../test-compiler-integration/pom.xml | 21 -------------- .../mvel/integrationtests/AlphaNodeTest.java | 2 +- 89 files changed, 1194 insertions(+), 1065 deletions(-) diff --git a/bom/drools-bom/pom.xml b/bom/drools-bom/pom.xml index ff4d590700f..55081e52f90 100644 --- a/bom/drools-bom/pom.xml +++ b/bom/drools-bom/pom.xml @@ -786,24 +786,6 @@ test-jar test - - org.drools - drools-drl10-parser - ${project.version} - - - org.drools - drools-drl10-parser - ${project.version} - sources - - - org.drools - drools-drl10-parser - ${project.version} - test-jar - test - org.drools drools-compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl index f80499fb3aa..74cff04d3c1 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl index 9af877c9df0..122634a9b26 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl index 02202de44e1..c009e6ec210 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl index be01b70b8a6..7f3f4ce75f9 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "AccumulateParserTest" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl index e6d7e40d5f3..43ee672e90b 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "AccumulateReverseParserTest" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl index 7a9d52d3e61..0557d308f43 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl index 1c828960220..9c146f05edb 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl index c81cca42267..76872623dda 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "AccumulateReverseParserTest" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl index f0efaae91b7..8d3f6828f50 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "AccumulateMultiPatternParserTest" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl index 5623f98cd2d..75d70816931 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "AccumulateParserTest" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl index aa3487820bc..3696836b1f2 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "AccumulateParserTest" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl index 149bd5b49a7..5155aa035de 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule almost_empty diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl index 3cc58efd0e2..e81b1d4a18f 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ import org.drools.compiler.Person diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl index d968e700c7f..48fa4c52a19 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule rule1 diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl index d6cdfb3ee3f..7c48ee595b5 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler.test; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl index c80fd4da819..6aabea7bd1b 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler.test; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl index d4e5f449bd4..8259a28773c 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl index 0305d1e85da..839e2c6c19e 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "CollectParserTest" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl index 3b57fd222f5..146b9e46c6a 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "CollectParserTest" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl index a786bfb9607..e46ecbe4601 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ //this starts with a comment package foo.bar diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl index f21bba25dfe..836a53dcd57 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declare_type_with_fields.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declare_type_with_fields.drl index ead6a91080e..3a770907d17 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declare_type_with_fields.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declare_type_with_fields.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ declare SomeFact name : String diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/empty_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/empty_rule.drl index 406037fbbd2..f1b6ac3ef6d 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/empty_rule.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/empty_rule.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule empty diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/enumeration.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/enumeration.drl index c60f47f139e..aad8c1122de 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/enumeration.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/enumeration.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eol_funny_business.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eol_funny_business.drl index 8a618729357..5df49bf1c70 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eol_funny_business.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eol_funny_business.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package test.dialect.rule.end.mine; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/escaped-string.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/escaped-string.drl index e9ccb4759a3..8daef0059fd 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/escaped-string.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/escaped-string.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "test_Quotes" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_multiple.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_multiple.drl index f1eb801e325..34b030897bb 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_multiple.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_multiple.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_parsing.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_parsing.drl index bf545890f57..f0106675491 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_parsing.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_parsing.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.mvel.compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_with_newline.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_with_newline.drl index 93648e357da..78f3c4e1d1e 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_with_newline.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_with_newline.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/extra_lhs_newline.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/extra_lhs_newline.drl index 1434c800cec..76c2c044131 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/extra_lhs_newline.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/extra_lhs_newline.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "another test" diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forall.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forall.drl index 9fe9d276517..b7077e2665e 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forall.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forall.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "ForallParserTest" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl index 578329f1437..d387cf9c647 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "ForallParserTest" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl index 5c3f9e9775f..47f918be139 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule using_from when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl index 3c8f7370cf7..98df27bf96a 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package foo diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl index 82df0791678..2a543650f58 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ import java.lang.String diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl index bc352c77f4b..ed6d45ff31f 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. + * http://www.apache.org/licenses/LICENSE-2.0 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler.test; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl index 7a84ed571b2..54f5225c3e8 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ //testing 'in' operator diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl index 88c0961377f..3d4d2df7c75 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl index ce6ee78c0c6..a1d01a65573 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ //check that it can handle true/false literals, and //negative numbers diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl index cdfa359765f..067e55fdb9d 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler.test; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl index fc7b1ed00a9..0b11f17c562 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "test nested CEs" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl index 57e70c2d0de..768fa8775c8 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule rule1 diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl index ff8ae8c50ea..8ec3fd4f86e 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package HR1 diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl index 0efd3eb6ebb..573fe4808d6 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler.test; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl index 3cb202cd7a0..a2eae254405 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ //testing not 'in' operator diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl index e8c78d9e687..87907a60b7a 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ import org.drools.compiler.Person diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl index 01331cc0d5c..2090d8f8565 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl index 02c2a320a55..a96bae49029 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl index fb74e43f789..3e576f091a8 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl index 3da6c4811cc..ecf9ddb2338 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ import org.drools.compiler.Person diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl index 477ca8aa608..156f5c58f6d 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package com.foo; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl index 6b287929946..59c31d2c8e7 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl index 131da29239d..9347834bbbb 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler.test; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl index 621e1509833..e9b9be3edd2 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package foo diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl index 2f28213ddb9..9eda0358e56 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "quoted string name" when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl index 8a6d403cf30..edf674db5ed 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ //this is for showing off all the new multi restriction stuff diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl index 9ac9870bf8b..faf0d0c3351 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl index 66d83801ca1..cece840aa59 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package foo.bar diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl index c60c76513af..fafc7032171 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl index 0bc1aca9a38..2605f494aa9 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl index 3950f6643e7..31040f9e95f 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl index e3dadd58cf2..c0ca3ba4430 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl index dd90e32fdbe..12550c159c7 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl index 981bfb446b1..cd14e5699a6 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule "1. Do Stuff!" diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl index e2cfc444e8d..96a2448ca41 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl index d7cc0487c18..8b48eea0fe9 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule rule1 diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl index d81c66b398f..7d25f230e25 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.mvel.compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl index 66e65f33968..2532abc0b6c 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl index 7f6a6c4b6a4..afc7e6480b0 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl @@ -1,19 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - - + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule when foo3 : Bar(a==3) diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl index 587b1baa3c6..0b6c21d5bc4 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package nesting; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl index 120e884ea76..4b0b93995d1 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package com.foo; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl index 568b5fc744b..23013d6b5d2 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package foo diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl index 5ed4e1ca301..7c7df07bd51 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package la diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl index f8029cd9026..4c50536c900 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule blah when diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl index 0c70f0ce121..de85f100561 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler.test; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl index e74a5d098b6..f867e69fe2d 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl index a548a7b4c2c..1b56f045643 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package HR1 diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl index 40289b97d4b..2bf358046e0 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule blah diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl index 375fe578fe4..da376e84385 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule blah diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl index 8729e98d029..af156c5ea1c 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule blah diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl index 8c6b5be3be4..a8e32df1d53 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule blah diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl index 64e8eb999bd..708bd667b0a 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ package org.drools.compiler diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl index 37d49e9844c..c2e0145747d 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl index 8198cc0bfa9..41ff2715d8a 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl index 2dc779a1cce..8db9671fee7 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl @@ -1,17 +1,19 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ rule simple_rule diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java index ae8d3d6d4d3..15f6157bd3e 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java @@ -30,17 +30,17 @@ public class DRL10Lexer implements DRLLexer { @Override public String getSourceName() { - return null; + throw new UnsupportedOperationException("This method should not be called"); } @Override public Token nextToken() { - return null; + throw new UnsupportedOperationException("This method should not be called"); } @Override public List getErrors() { - return null; + throw new UnsupportedOperationException("This method should not be called"); } } \ No newline at end of file diff --git a/drools-test-coverage/test-compiler-integration/pom.xml b/drools-test-coverage/test-compiler-integration/pom.xml index 93df94a6d58..6ccf1cbdc67 100644 --- a/drools-test-coverage/test-compiler-integration/pom.xml +++ b/drools-test-coverage/test-compiler-integration/pom.xml @@ -178,27 +178,6 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java index 71642c17289..6d14f2355c6 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java @@ -197,7 +197,7 @@ public void testBetaModifyWithAlpha() { " $p : Person(name == \"Mario\")\n" + " $s : String(this == $p.name)\n" + "then\n" + - " modify($p) { setName(\"Mark\") }\n" + + " modify($p) { setName(\"Mark\") }" + "end\n" + "rule R2 when\n" + " $p : Person(name == \"Mark\")\n" + From 35f8ed8c0240df15253296c9cbba49a998ea5e8c Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 20 Feb 2024 16:48:54 +0900 Subject: [PATCH 055/141] =?UTF-8?q?[incubator-kie-drools#5681]=20Experimen?= =?UTF-8?q?t:=20New=20DRL=20Parser=20:=20Test=20failure=E2=80=A6=20(#5693)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools#5681] Experiment: New DRL Parser : Test failure : Unknown language level - Revert the introduction of LanguageLevelOption.DRL10. Use DRL6 as usual. Instead, intorduced system property "drools.drl.antlr4.parser.enabled" for parser impl switch - Use a package name 'antlr4' instead of 'drl10' for the new parser separation * - Enable the new parser by default so that CI can run - Also suppress some GHAs which don't run with a feature branch --- .github/workflows/pr-downstream.yml | 1 + .../parser/antlr4}/DRLExprParserTest.java | 4 +- .../parser/antlr4}/DRLParserTest.java | 8 +- .../parser/antlr4}/DescrDumperTest.java | 4 +- .../parser/antlr4}/MiscDRLParserTest.java | 4 +- .../parser/antlr4}/Rule_with_Extends.drl | 0 .../parser/antlr4}/Rule_with_Metadata.drl | 0 .../parser/antlr4}/Rule_with_nested_LHS.drl | 0 .../parser/antlr4}/accumulate.drl | 0 .../antlr4}/accumulateExternalFunction.drl | 0 .../antlr4}/accumulateMultipleFunctions.drl | 0 .../accumulateMultipleFunctionsConstraint.drl | 0 .../parser/antlr4}/accumulateReverse.drl | 0 .../antlr4}/accumulate_multi_pattern.drl | 0 .../antlr4}/accumulate_with_bindings.drl | 0 .../antlr4}/accumulate_with_nested_from.drl | 0 .../parser/antlr4}/almost_empty_rule.drl | 0 .../parser/antlr4}/and_or_rule.drl | 0 .../parser/antlr4}/autofocus.drl | 0 .../parser/antlr4}/basic_binding.drl | 0 .../parser => drl/parser/antlr4}/bindings.drl | 0 .../parser/antlr4}/brackets_precedence.drl | 0 .../parser => drl/parser/antlr4}/collect.drl | 0 .../antlr4}/collect_with_nested_from.drl | 0 .../parser => drl/parser/antlr4}/comment.drl | 0 .../parser => drl/parser/antlr4}/complex.dsl | 0 .../antlr4}/declaration-in-consequence.drl | 0 .../antlr4}/declare_type_with_fields.drl | 0 .../parser/antlr4}/empty_rule.drl | 0 .../parser/antlr4}/enumeration.drl | 0 .../parser/antlr4}/eol_funny_business.drl | 0 .../parser/antlr4}/escaped-string.drl | 0 .../parser/antlr4}/eval_multiple.drl | 0 .../parser/antlr4}/eval_parsing.drl | 0 .../parser/antlr4}/eval_with_newline.drl | 0 .../expander_multiple_constraints.dslr | 0 .../expander_multiple_constraints_flush.dslr | 0 .../parser/antlr4}/expander_spread_lines.dslr | 0 .../parser/antlr4}/extra_lhs_newline.drl | 0 .../parser => drl/parser/antlr4}/forall.drl | 0 .../parser/antlr4}/forallwithfrom.drl | 0 .../parser => drl/parser/antlr4}/from.drl | 0 .../parser/antlr4}/function_arrays.drl | 0 .../parser/antlr4}/functions.drl | 0 .../parser => drl/parser/antlr4}/globals.drl | 0 .../parser/antlr4}/in_operator_test.drl | 0 .../parser/antlr4}/lhs_semicolon_delim.drl | 0 .../antlr4}/literal_bool_and_negative.drl | 0 .../parser/antlr4}/multiple_constraints.dsl | 0 .../parser/antlr4}/multiple_rules.drl | 0 .../antlr4}/nested_conditional_elements.drl | 0 .../parser => drl/parser/antlr4}/no-loop.drl | 0 .../antlr4}/not_exist_with_brackets.drl | 0 .../parser/antlr4}/not_with_constraint.drl | 0 .../parser/antlr4}/notin_operator_test.drl | 0 .../parser/antlr4}/or_binding.drl | 0 .../parser/antlr4}/or_binding_complex.drl | 0 .../antlr4}/or_binding_with_brackets.drl | 0 .../parser => drl/parser/antlr4}/or_ce.drl | 0 .../parser/antlr4}/or_nesting.drl | 0 .../parser/antlr4}/package_attributes.drl | 0 .../parser/antlr4}/pluggable_operators.drl | 0 .../parser/antlr4}/qualified_classname.drl | 0 .../parser/antlr4}/query_and_rule.drl | 0 .../antlr4}/quoted_string_name_rule.drl | 0 .../parser/antlr4}/restrictions_test.drl | 0 .../parser/antlr4}/rule_attributes.drl | 0 .../parser/antlr4}/rule_attributes2.drl | 0 .../parser/antlr4}/rule_attributes_alt.drl | 0 .../antlr4}/rule_calendars_attribute.drl | 0 .../antlr4}/rule_calendars_attribute2.drl | 0 .../antlr4}/rule_duration_expression.drl | 0 .../antlr4}/rule_enabled_expression.drl | 0 .../antlr4}/rule_names_number_prefix.drl | 0 .../parser => drl/parser/antlr4}/rule_not.drl | 0 .../parser/antlr4}/ruleflowgroup.drl | 0 .../parser/antlr4}/semicolon.drl | 0 .../parser/antlr4}/simple_query.drl | 0 .../parser/antlr4}/simple_rule.drl | 0 .../parser/antlr4}/soundslike_operator.drl | 0 .../parser/antlr4}/statement_ordering_1.drl | 0 .../parser/antlr4}/ternary_expression.drl | 0 .../test_CommentLineNumbersInConsequence.drl | 0 .../test_ComplexChainedCallWithFrom.drl | 0 .../parser/antlr4}/test_EmptyPattern.drl | 0 .../parser/antlr4}/test_EndPosition.drl | 0 .../parser/antlr4}/test_FunctionImport.drl | 0 .../test_SimpleAccessorArgWithFrom.drl | 0 .../antlr4}/test_SimpleAccessorWithFrom.drl | 0 .../test_SimpleFunctionCallWithFrom.drl | 0 .../antlr4}/test_SimpleMethodCallWithFrom.drl | 0 .../parser/antlr4}/type_with_meta.drl | 0 .../parser/antlr4}/with_eval.drl | 0 .../parser/antlr4}/with_predicate.drl | 0 .../parser/antlr4}/with_retval.drl | 0 drools-drl/drools-drl-parser/pom.xml | 2 +- .../parser/antlr4}/DRL6Expressions.g4 | 0 .../parser => drl/parser/antlr4}/DRLLexer.g4 | 0 .../parser => drl/parser/antlr4}/DRLParser.g4 | 0 .../parser => drl/parser/antlr4}/JavaLexer.g4 | 0 .../parser/antlr4}/JavaParser.g4 | 0 .../org/drools/drl/parser/DRLFactory.java | 3 - .../drl/parser/DrlExprParserFactory.java | 6 +- .../java/org/drools/drl/parser/DrlParser.java | 82 ++++++++++++------- .../parser/antlr4}/DRLErrorListener.java | 2 +- .../parser/antlr4}/DRLExpressions.java | 2 +- .../parser/antlr4}/DRLParserError.java | 2 +- .../parser/antlr4}/DRLParserException.java | 2 +- .../parser/antlr4}/DRLParserHelper.java | 12 ++- .../parser/antlr4}/DRLParserWrapper.java | 13 ++- .../parser/antlr4}/DRLVisitorImpl.java | 12 +-- .../parser/antlr4}/Developer_Notes.md | 0 .../parser/antlr4/Drl6ExprParserAntlr4.java} | 6 +- .../antlr4}/DroolsParserExceptionFactory.java | 2 +- .../parser/antlr4}/ParserHelper.java | 2 +- .../parser/antlr4}/ParserStringUtils.java | 2 +- .../drools/drl/parser/lang/DRL10Lexer.java | 46 ----------- .../builder/conf/LanguageLevelOption.java | 2 +- pom.xml | 6 +- 119 files changed, 108 insertions(+), 117 deletions(-) rename drools-drl/drools-drl-parser-tests/src/test/java/org/drools/{drl10/parser => drl/parser/antlr4}/DRLExprParserTest.java (99%) rename drools-drl/drools-drl-parser-tests/src/test/java/org/drools/{drl10/parser => drl/parser/antlr4}/DRLParserTest.java (94%) rename drools-drl/drools-drl-parser-tests/src/test/java/org/drools/{drl10/parser => drl/parser/antlr4}/DescrDumperTest.java (99%) rename drools-drl/drools-drl-parser-tests/src/test/java/org/drools/{drl10/parser => drl/parser/antlr4}/MiscDRLParserTest.java (99%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/Rule_with_Extends.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/Rule_with_Metadata.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/Rule_with_nested_LHS.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/accumulate.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/accumulateExternalFunction.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/accumulateMultipleFunctions.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/accumulateMultipleFunctionsConstraint.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/accumulateReverse.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/accumulate_multi_pattern.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/accumulate_with_bindings.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/accumulate_with_nested_from.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/almost_empty_rule.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/and_or_rule.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/autofocus.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/basic_binding.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/bindings.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/brackets_precedence.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/collect.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/collect_with_nested_from.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/comment.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/complex.dsl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/declaration-in-consequence.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/declare_type_with_fields.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/empty_rule.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/enumeration.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/eol_funny_business.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/escaped-string.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/eval_multiple.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/eval_parsing.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/eval_with_newline.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/expander_multiple_constraints.dslr (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/expander_multiple_constraints_flush.dslr (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/expander_spread_lines.dslr (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/extra_lhs_newline.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/forall.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/forallwithfrom.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/from.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/function_arrays.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/functions.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/globals.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/in_operator_test.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/lhs_semicolon_delim.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/literal_bool_and_negative.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/multiple_constraints.dsl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/multiple_rules.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/nested_conditional_elements.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/no-loop.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/not_exist_with_brackets.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/not_with_constraint.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/notin_operator_test.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/or_binding.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/or_binding_complex.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/or_binding_with_brackets.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/or_ce.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/or_nesting.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/package_attributes.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/pluggable_operators.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/qualified_classname.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/query_and_rule.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/quoted_string_name_rule.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/restrictions_test.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/rule_attributes.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/rule_attributes2.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/rule_attributes_alt.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/rule_calendars_attribute.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/rule_calendars_attribute2.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/rule_duration_expression.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/rule_enabled_expression.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/rule_names_number_prefix.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/rule_not.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/ruleflowgroup.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/semicolon.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/simple_query.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/simple_rule.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/soundslike_operator.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/statement_ordering_1.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/ternary_expression.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/test_CommentLineNumbersInConsequence.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/test_ComplexChainedCallWithFrom.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/test_EmptyPattern.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/test_EndPosition.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/test_FunctionImport.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/test_SimpleAccessorArgWithFrom.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/test_SimpleAccessorWithFrom.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/test_SimpleFunctionCallWithFrom.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/test_SimpleMethodCallWithFrom.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/type_with_meta.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/with_eval.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/with_predicate.drl (100%) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/{drl10/parser => drl/parser/antlr4}/with_retval.drl (100%) rename drools-drl/drools-drl-parser/src/main/antlr4/org/drools/{drl10/parser => drl/parser/antlr4}/DRL6Expressions.g4 (100%) rename drools-drl/drools-drl-parser/src/main/antlr4/org/drools/{drl10/parser => drl/parser/antlr4}/DRLLexer.g4 (100%) rename drools-drl/drools-drl-parser/src/main/antlr4/org/drools/{drl10/parser => drl/parser/antlr4}/DRLParser.g4 (100%) rename drools-drl/drools-drl-parser/src/main/antlr4/org/drools/{drl10/parser => drl/parser/antlr4}/JavaLexer.g4 (100%) rename drools-drl/drools-drl-parser/src/main/antlr4/org/drools/{drl10/parser => drl/parser/antlr4}/JavaParser.g4 (100%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/DRLErrorListener.java (97%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/DRLExpressions.java (98%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/DRLParserError.java (98%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/DRLParserException.java (96%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/DRLParserHelper.java (93%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/DRLParserWrapper.java (87%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/DRLVisitorImpl.java (98%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/Developer_Notes.md (100%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser/Drl10ExprParser.java => drl/parser/antlr4/Drl6ExprParserAntlr4.java} (94%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/DroolsParserExceptionFactory.java (99%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/ParserHelper.java (99%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/{drl10/parser => drl/parser/antlr4}/ParserStringUtils.java (98%) delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java diff --git a/.github/workflows/pr-downstream.yml b/.github/workflows/pr-downstream.yml index b82393a748f..5cca505b8f5 100644 --- a/.github/workflows/pr-downstream.yml +++ b/.github/workflows/pr-downstream.yml @@ -14,6 +14,7 @@ on: jobs: kogito-downstream-build: + if false: # Temporally disabled because downstream build doesn't work with the feature branch dev-new-parser concurrency: group: pr-${{ matrix.job_name }}_${{ matrix.os }}_${{ matrix.java-version }}_${{ matrix.maven-version }}_${{ github.head_ref }} cancel-in-progress: true diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java similarity index 99% rename from drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java rename to drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java index 1f27a9c861e..b573cd1ae5c 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLExprParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import static org.assertj.core.api.Assertions.assertThat; @@ -41,7 +41,7 @@ public class DRLExprParserTest { @BeforeEach public void setUp() throws Exception { - this.parser = new Drl10ExprParser(LanguageLevelOption.DRL6); + this.parser = new Drl6ExprParserAntlr4(LanguageLevelOption.DRL6); } @AfterEach diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserTest.java similarity index 94% rename from drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java rename to drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserTest.java index 35c4638ebc1..8aecc0fb056 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserTest.java @@ -1,4 +1,4 @@ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import java.util.List; @@ -13,9 +13,9 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.drools.drl10.parser.DRLParserHelper.computeTokenIndex; -import static org.drools.drl10.parser.DRLParserHelper.createDrlParser; -import static org.drools.drl10.parser.DRLParserHelper.parse; +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; class DRLParserTest { diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java similarity index 99% rename from drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java rename to drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java index d98ec8ec895..ab644f7dafb 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/DescrDumperTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import static org.assertj.core.api.Assertions.assertThat; @@ -358,7 +358,7 @@ public void testProcessImplicitConstraints() throws Exception { } public ConstraintConnectiveDescr parse( final String constraint ) { - DrlExprParser parser = new Drl10ExprParser(LanguageLevelOption.DRL6); + DrlExprParser parser = new Drl6ExprParserAntlr4(LanguageLevelOption.DRL6); 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/drl10/parser/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java similarity index 99% rename from drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java rename to drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java index 6353be53ac7..ae45a8cc3e2 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl10/parser/MiscDRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java @@ -1,4 +1,4 @@ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import java.io.BufferedReader; import java.io.IOException; @@ -39,7 +39,7 @@ import org.drools.drl.ast.descr.TypeDeclarationDescr; import org.drools.drl.ast.descr.TypeFieldDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; -import org.drools.drl10.parser.DRLParserWrapper; +import org.drools.drl.parser.antlr4.DRLParserWrapper; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_Extends.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Extends.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_Extends.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_Metadata.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_Metadata.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_Metadata.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_nested_LHS.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/Rule_with_nested_LHS.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_nested_LHS.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateExternalFunction.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateExternalFunction.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateExternalFunction.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateMultipleFunctions.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctions.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateMultipleFunctions.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateMultipleFunctionsConstraint.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateMultipleFunctionsConstraint.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateMultipleFunctionsConstraint.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateReverse.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulateReverse.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateReverse.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_multi_pattern.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_multi_pattern.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_multi_pattern.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_bindings.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_bindings.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_bindings.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/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 similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/accumulate_with_nested_from.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_nested_from.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/almost_empty_rule.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/almost_empty_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/almost_empty_rule.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/and_or_rule.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/and_or_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/and_or_rule.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/autofocus.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/autofocus.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/autofocus.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/basic_binding.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/basic_binding.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/basic_binding.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/bindings.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/bindings.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/bindings.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/brackets_precedence.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/brackets_precedence.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/brackets_precedence.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/collect.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/collect.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/collect_with_nested_from.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/collect_with_nested_from.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/collect_with_nested_from.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/comment.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/comment.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/comment.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/complex.dsl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/complex.dsl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/complex.dsl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/declaration-in-consequence.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declaration-in-consequence.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/declaration-in-consequence.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declare_type_with_fields.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/declare_type_with_fields.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/declare_type_with_fields.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/declare_type_with_fields.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/empty_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/empty_rule.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/empty_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/empty_rule.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/enumeration.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/enumeration.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/enumeration.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/enumeration.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eol_funny_business.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/eol_funny_business.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eol_funny_business.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/eol_funny_business.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/escaped-string.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/escaped-string.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/escaped-string.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/escaped-string.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_multiple.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/eval_multiple.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_multiple.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/eval_multiple.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_parsing.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/eval_parsing.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_parsing.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/eval_parsing.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_with_newline.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/eval_with_newline.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/eval_with_newline.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/eval_with_newline.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints.dslr b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/expander_multiple_constraints.dslr similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints.dslr rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/expander_multiple_constraints.dslr diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints_flush.dslr b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/expander_multiple_constraints_flush.dslr similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_multiple_constraints_flush.dslr rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/expander_multiple_constraints_flush.dslr diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_spread_lines.dslr b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/expander_spread_lines.dslr similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/expander_spread_lines.dslr rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/expander_spread_lines.dslr diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/extra_lhs_newline.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/extra_lhs_newline.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/extra_lhs_newline.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/extra_lhs_newline.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forall.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/forall.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forall.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/forall.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/forallwithfrom.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/forallwithfrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/forallwithfrom.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/from.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/from.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/from.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/function_arrays.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/function_arrays.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/function_arrays.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/functions.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/functions.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/functions.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/globals.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/globals.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/globals.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/in_operator_test.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/in_operator_test.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/in_operator_test.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/lhs_semicolon_delim.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/lhs_semicolon_delim.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/lhs_semicolon_delim.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/literal_bool_and_negative.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/literal_bool_and_negative.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/literal_bool_and_negative.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_constraints.dsl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_constraints.dsl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_constraints.dsl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_rules.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/multiple_rules.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_rules.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/nested_conditional_elements.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/nested_conditional_elements.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/nested_conditional_elements.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/no-loop.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/no-loop.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/no-loop.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/not_exist_with_brackets.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_exist_with_brackets.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/not_exist_with_brackets.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/not_with_constraint.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/not_with_constraint.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/not_with_constraint.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/notin_operator_test.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/notin_operator_test.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/notin_operator_test.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding_complex.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_complex.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding_complex.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding_with_brackets.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_binding_with_brackets.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding_with_brackets.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_ce.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_ce.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_ce.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_nesting.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/or_nesting.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_nesting.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_attributes.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/package_attributes.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_attributes.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/pluggable_operators.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/pluggable_operators.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/pluggable_operators.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_classname.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/qualified_classname.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_classname.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/query_and_rule.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/query_and_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/query_and_rule.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/quoted_string_name_rule.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/quoted_string_name_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/quoted_string_name_rule.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/restrictions_test.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/restrictions_test.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/restrictions_test.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes2.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes2.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes2.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes_alt.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_attributes_alt.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes_alt.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_calendars_attribute.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_calendars_attribute.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_calendars_attribute2.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_calendars_attribute2.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_calendars_attribute2.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_duration_expression.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_duration_expression.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_duration_expression.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_enabled_expression.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_enabled_expression.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_enabled_expression.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_names_number_prefix.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_names_number_prefix.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_names_number_prefix.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_not.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/rule_not.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_not.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/ruleflowgroup.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ruleflowgroup.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/ruleflowgroup.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/semicolon.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/semicolon.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/semicolon.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/simple_query.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_query.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/simple_query.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/simple_rule.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/simple_rule.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/simple_rule.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/soundslike_operator.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/soundslike_operator.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/soundslike_operator.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/statement_ordering_1.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/statement_ordering_1.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/statement_ordering_1.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/ternary_expression.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/ternary_expression.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/ternary_expression.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_CommentLineNumbersInConsequence.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_CommentLineNumbersInConsequence.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_CommentLineNumbersInConsequence.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_ComplexChainedCallWithFrom.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_ComplexChainedCallWithFrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_ComplexChainedCallWithFrom.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_EmptyPattern.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EmptyPattern.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_EmptyPattern.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_EndPosition.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_EndPosition.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_EndPosition.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_FunctionImport.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_FunctionImport.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_FunctionImport.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleAccessorArgWithFrom.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorArgWithFrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleAccessorArgWithFrom.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleAccessorWithFrom.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleAccessorWithFrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleAccessorWithFrom.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleFunctionCallWithFrom.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleFunctionCallWithFrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleFunctionCallWithFrom.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleMethodCallWithFrom.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/test_SimpleMethodCallWithFrom.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleMethodCallWithFrom.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/type_with_meta.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/type_with_meta.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/type_with_meta.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_eval.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_eval.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_eval.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_predicate.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_predicate.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_predicate.drl diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_retval.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl10/parser/with_retval.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_retval.drl diff --git a/drools-drl/drools-drl-parser/pom.xml b/drools-drl/drools-drl-parser/pom.xml index 0eeb7871009..d8b66f13e5a 100644 --- a/drools-drl/drools-drl-parser/pom.xml +++ b/drools-drl/drools-drl-parser/pom.xml @@ -140,7 +140,7 @@ true false - src/main/antlr4/org/drools/drl10/parser/ + src/main/antlr4/org/drools/drl/parser/antlr4 diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 similarity index 100% rename from drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRL6Expressions.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 similarity index 100% rename from drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLLexer.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 similarity index 100% rename from drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/DRLParser.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/JavaLexer.g4 similarity index 100% rename from drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaLexer.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/JavaLexer.g4 diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/JavaParser.g4 similarity index 100% rename from drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl10/parser/JavaParser.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/JavaParser.g4 diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java index 71b23c2fdd3..15bf0addf05 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DRLFactory.java @@ -25,7 +25,6 @@ import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognizerSharedState; import org.antlr.runtime.TokenStream; -import org.drools.drl.parser.lang.DRL10Lexer; import org.drools.drl.parser.lang.DRL5Expressions; import org.drools.drl.parser.lang.DRL5Lexer; import org.drools.drl.parser.lang.DRL5Parser; @@ -114,8 +113,6 @@ public static DRLLexer getDRLLexer(CharStream input, LanguageLevelOption languag case DRL6: case DRL6_STRICT: return new DRL6Lexer(input); - case DRL10: - return new DRL10Lexer(); } throw new RuntimeException("Unknown language level"); } 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 9ee116faf37..ae3ffcf9359 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 @@ -1,6 +1,6 @@ package org.drools.drl.parser; -import org.drools.drl10.parser.Drl10ExprParser; +import org.drools.drl.parser.antlr4.Drl6ExprParserAntlr4; import org.kie.internal.builder.conf.LanguageLevelOption; public class DrlExprParserFactory { @@ -10,9 +10,7 @@ public static DrlExprParser getDrlExrParser(LanguageLevelOption languageLevel) { case DRL5: case DRL6: case DRL6_STRICT: - return new Drl6ExprParser(languageLevel); - case DRL10: - return new Drl10ExprParser(languageLevel); + return DrlParser.ANTLR4_PARSER_ENABLED ? new Drl6ExprParserAntlr4(languageLevel) : new Drl6ExprParser(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 d6ee0c042bb..4bad571401f 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 @@ -18,8 +18,8 @@ */ package org.drools.drl.parser; -import org.drools.drl10.parser.DRLParserError; -import org.drools.drl10.parser.DRLParserWrapper; +import org.drools.drl.parser.antlr4.DRLParserError; +import org.drools.drl.parser.antlr4.DRLParserWrapper; import org.drools.io.InternalResource; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.parser.lang.DRLLexer; @@ -37,9 +37,11 @@ import java.io.IOException; import java.io.InputStream; import java.io.Reader; +import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.function.Function; /** * This is a low level parser API. This will return textual AST representations @@ -57,6 +59,9 @@ public class DrlParser { private DRLLexer lexer = null; private Resource resource = null; + public static final String ANTLR4_PARSER_ENABLED_PROPERTY = "drools.drl.antlr4.parser.enabled"; + public static final boolean ANTLR4_PARSER_ENABLED = Boolean.parseBoolean(System.getProperty(ANTLR4_PARSER_ENABLED_PROPERTY, "true")); // default is true + public static final LanguageLevelOption DEFAULT_LANGUAGE_LEVEL = LanguageLevelOption.DRL6; private final LanguageLevelOption languageLevel; @@ -76,16 +81,28 @@ public PackageDescr parse(final Resource resource, final String text) throws Dro public PackageDescr parse(final boolean isEditor, final String text) throws DroolsParserException { - lexer = DRLFactory.buildLexer(text, languageLevel); - DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); - return compile(isEditor, parser); + System.out.println("### parse : ANTLR4_PARSER_ENABLED = " + ANTLR4_PARSER_ENABLED); + if (ANTLR4_PARSER_ENABLED) { + // new parser based on antlr4 + return compileWithAntlr4Parser(parser -> parser.parse(new StringReader(text))); + } else { + lexer = DRLFactory.buildLexer(text, languageLevel); + DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); + return compile(isEditor, parser); + } } public PackageDescr parse(final boolean isEditor, final Reader reader) throws DroolsParserException { - lexer = DRLFactory.buildLexer(reader, languageLevel); - DRLParser parser = DRLFactory.buildParser( lexer, languageLevel ); - return compile(isEditor, parser); + System.out.println("### parse : ANTLR4_PARSER_ENABLED = " + ANTLR4_PARSER_ENABLED); + if (ANTLR4_PARSER_ENABLED) { + // new parser based on antlr4 + return compileWithAntlr4Parser(parser -> parser.parse(reader)); + } else { + lexer = DRLFactory.buildLexer(reader, languageLevel); + DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); + return compile(isEditor, parser); + } } public PackageDescr parse(final Resource resource, final Reader reader) throws DroolsParserException { @@ -166,29 +183,10 @@ public PackageDescr parse(final boolean isEditor, final InputStream is) throws DroolsParserException, IOException { this.resource = resource; String encoding = resource instanceof InternalResource ? ((InternalResource) resource).getEncoding() : null; - System.out.println("### parse : languageLevel = " + languageLevel); - if (languageLevel == LanguageLevelOption.DRL10) { + System.out.println("### parse : ANTLR4_PARSER_ENABLED = " + ANTLR4_PARSER_ENABLED); + if (ANTLR4_PARSER_ENABLED) { // new parser based on antlr4 - try { - DRLParserWrapper parser = new DRLParserWrapper(); - PackageDescr packageDescr = parser.parse(is); - for (final DRLParserError drlParserError : parser.getErrors()) { - final ParserError err = new ParserError(resource, - drlParserError.getMessage(), - drlParserError.getLineNumber(), - drlParserError.getColumn()); - this.results.add(err); - } - return !this.hasErrors() ? packageDescr : null; - } catch (Exception e) { - LOG.error("Exception", e); - final ParserError err = new ParserError(resource, - GENERIC_ERROR_MESSAGE + e.toString() + "\n" + Arrays.toString(e.getStackTrace()), - -1, - 0); - this.results.add(err); - throw new DroolsParserException(GENERIC_ERROR_MESSAGE + e.getMessage(), e); - } + return compileWithAntlr4Parser(parser -> parser.parse(is)); } else { // old parsers based on antlr3 lexer = DRLFactory.buildLexer(is, encoding, languageLevel); @@ -197,6 +195,30 @@ public PackageDescr parse(final boolean isEditor, } } + private PackageDescr compileWithAntlr4Parser(Function packageDescrFunction) throws DroolsParserException { + try { + // we don't use languageLevel here, assuming DRL6 compatible + DRLParserWrapper parser = new DRLParserWrapper(); + PackageDescr packageDescr = packageDescrFunction.apply(parser); + for (final DRLParserError drlParserError : parser.getErrors()) { + final ParserError err = new ParserError(resource, + drlParserError.getMessage(), + drlParserError.getLineNumber(), + drlParserError.getColumn()); + this.results.add(err); + } + return !this.hasErrors() ? packageDescr : null; + } catch (Exception e) { + LOG.error("Exception", e); + final ParserError err = new ParserError(resource, + GENERIC_ERROR_MESSAGE + e.toString() + "\n" + Arrays.toString(e.getStackTrace()), + -1, + 0); + this.results.add(err); + throw new DroolsParserException(GENERIC_ERROR_MESSAGE + e.getMessage(), e); + } + } + /** * This will expand the DRL. useful for debugging. * diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLErrorListener.java similarity index 97% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLErrorListener.java index 0e5b5985b6c..00f9c4bc48f 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLErrorListener.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLErrorListener.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import java.util.ArrayList; import java.util.List; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLExpressions.java similarity index 98% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLExpressions.java index e7aa8102c48..4c057189a15 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLExpressions.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLExpressions.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import java.util.LinkedList; import java.util.List; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserError.java similarity index 98% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserError.java index 4b893e11e46..7c8f2c68900 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserError.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserError.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; /** * Error information while parsing DRL diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserException.java similarity index 96% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserException.java index 833d1aa8df0..79bd114d997 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserException.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserException.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; public class DRLParserException extends RuntimeException { diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserHelper.java similarity index 93% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserHelper.java index f4436bf44b0..3d91f782a48 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserHelper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserHelper.java @@ -16,10 +16,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import java.io.IOException; import java.io.InputStream; +import java.io.Reader; import java.io.UncheckedIOException; import org.antlr.v4.runtime.CharStream; @@ -63,6 +64,15 @@ public static DRLParser createDrlParser(InputStream is) { } } + public static DRLParser createDrlParser(Reader reader) { + try { + CharStream charStream = CharStreams.fromReader(reader); + return createDrlParser(charStream); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + private static DRLParser createDrlParser(CharStream charStream) { DRLLexer drlLexer = new DRLLexer(charStream); CommonTokenStream commonTokenStream = new CommonTokenStream(drlLexer); diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserWrapper.java similarity index 87% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserWrapper.java index 914255e1375..c28e57b9974 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLParserWrapper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserWrapper.java @@ -16,9 +16,10 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import java.io.InputStream; +import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -27,7 +28,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.drools.drl10.parser.DRLParserHelper.compilationUnitContext2PackageDescr; +import static org.drools.drl.parser.antlr4.DRLParserHelper.compilationUnitContext2PackageDescr; /** * Wrapper for DRLParser. Somewhat duplicated from DRLParserHelper, but this class is instantiated and holds errors. @@ -54,6 +55,14 @@ public PackageDescr parse(InputStream is) { return parse(drlParser); } + /** + * Main entry point for parsing DRL + */ + public PackageDescr parse(Reader reader) { + DRLParser drlParser = DRLParserHelper.createDrlParser(reader); + return parse(drlParser); + } + private PackageDescr parse(DRLParser drlParser) { DRLErrorListener errorListener = new DRLErrorListener(); drlParser.addErrorListener(errorListener); diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java similarity index 98% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java index a977fee9882..a3cae67b9b2 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DRLVisitorImpl.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import java.util.ArrayList; import java.util.List; @@ -58,11 +58,11 @@ import org.drools.drl.ast.descr.UnitDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; -import static org.drools.drl10.parser.DRLParserHelper.getTextWithoutErrorNode; -import static org.drools.drl10.parser.ParserStringUtils.getTextPreservingWhitespace; -import static org.drools.drl10.parser.ParserStringUtils.getTokenTextPreservingWhitespace; -import static org.drools.drl10.parser.ParserStringUtils.safeStripStringDelimiters; -import static org.drools.drl10.parser.ParserStringUtils.trimThen; +import static org.drools.drl.parser.antlr4.DRLParserHelper.getTextWithoutErrorNode; +import static org.drools.drl.parser.antlr4.ParserStringUtils.getTextPreservingWhitespace; +import static org.drools.drl.parser.antlr4.ParserStringUtils.getTokenTextPreservingWhitespace; +import static org.drools.drl.parser.antlr4.ParserStringUtils.safeStripStringDelimiters; +import static org.drools.drl.parser.antlr4.ParserStringUtils.trimThen; import static org.drools.util.StringUtils.unescapeJava; /** diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Developer_Notes.md similarity index 100% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Developer_Notes.md rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Developer_Notes.md diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java similarity index 94% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java index 19ec4735363..220c8bb0667 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/Drl10ExprParser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import java.util.Collections; import java.util.List; @@ -34,13 +34,13 @@ * This is a helper class that provides helper methods to parse expressions * using both the DRLExpressions parser and the DRLExprTree parser. */ -public class Drl10ExprParser implements DrlExprParser { +public class Drl6ExprParserAntlr4 implements DrlExprParser { private ParserHelper helper = null; private final LanguageLevelOption languageLevel; - public Drl10ExprParser(LanguageLevelOption languageLevel) { + public Drl6ExprParserAntlr4(LanguageLevelOption languageLevel) { this.languageLevel = languageLevel; } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DroolsParserExceptionFactory.java similarity index 99% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DroolsParserExceptionFactory.java index abf586c55d0..622ea8ae3b8 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/DroolsParserExceptionFactory.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DroolsParserExceptionFactory.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import java.io.PrintWriter; import java.io.StringWriter; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java similarity index 99% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java index f729115b7ca..82d40b63020 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserHelper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java @@ -29,7 +29,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import java.util.ArrayDeque; import java.util.ArrayList; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserStringUtils.java similarity index 98% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserStringUtils.java index ef22da2dce3..22ea2a7fa65 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl10/parser/ParserStringUtils.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserStringUtils.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.drools.drl10.parser; +package org.drools.drl.parser.antlr4; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.TokenStream; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java deleted file mode 100644 index 15f6157bd3e..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL10Lexer.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.drl.parser.lang; - -import java.util.List; - -import org.antlr.runtime.Token; -import org.drools.drl.parser.DroolsParserException; - -/** - * No implementation because everything is handled by DRL10Parser - */ -public class DRL10Lexer implements DRLLexer { - - @Override - public String getSourceName() { - throw new UnsupportedOperationException("This method should not be called"); - } - - @Override - public Token nextToken() { - throw new UnsupportedOperationException("This method should not be called"); - } - - @Override - public List getErrors() { - throw new UnsupportedOperationException("This method should not be called"); - } - -} \ No newline at end of file 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 86266a0f2d3..ca8b96ee91a 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), DRL10(false); + DRL5(false), DRL6(false), DRL6_STRICT(true); private final boolean useJavaAnnotations; diff --git a/pom.xml b/pom.xml index 40f4d9d7240..c0fd1291775 100644 --- a/pom.xml +++ b/pom.xml @@ -312,10 +312,10 @@ - DRL10 + disableNewParser - DRL10 + disableNewParser @@ -325,7 +325,7 @@ maven-surefire-plugin - DRL10 + false From 46efc820f1532ed1e5297383c50ba2416cfbf74e Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 21 Feb 2024 16:30:56 +0900 Subject: [PATCH 056/141] [incubator-kie-drools#5679] New DRL parser : Test failure : RHS end without preceding white-space (#5698) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 49 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLLexer.g4 | 7 ++- 2 files changed, 55 insertions(+), 1 deletion(-) 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 ae45a8cc3e2..c40543c485e 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 @@ -3440,4 +3440,53 @@ public void ruleTokenInRhs() throws Exception { RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int rule = 10;"); } + + @Test + void semicolonEnd() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " delete($s);end\n"; // no space after semicolon + + PackageDescr packageDescr = parser.parse(text ); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("delete($s);"); + } + + @Test + void braceEnd() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " modify($p) { setAge(2) }end\n"; // no space after right brace + + System.out.println(text); + + PackageDescr packageDescr = parser.parse(text ); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("modify($p) { setAge(2) }"); + } + + @Test + void parenthesisEnd() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p)end\n"; // no space after right parenthesis + + System.out.println(text); + + PackageDescr packageDescr = parser.parse(text ); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("retract($p)"); + } } 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/DRLLexer.g4 index 8aac81873cc..a2ef0328237 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/DRLLexer.g4 @@ -158,4 +158,9 @@ DrlUnicodeEscape mode RHS; RHS_WS : [ \t\r\n\u000C]+ -> channel(HIDDEN); DRL_RHS_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) {setText("end");} -> popMode; -RHS_CHUNK : ~[ \t\r\n\u000C]+ ; +RHS_CHUNK + : ~[ ;})\t\r\n\u000C]+ [;})]? // ; } ) could be a delimitter proceding 'end' + | SEMI + | RBRACE + | RPAREN + ; \ No newline at end of file From 96e60ad061d9fa72f6af0fa68eef6190a545420b Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 26 Feb 2024 18:14:59 +0900 Subject: [PATCH 057/141] [incubator-kie-drools#5700] [new-parser] Can't use single-quoted Strings in RHS (#5726) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 45 ++++++++++++++++--- .../org/drools/drl/parser/antlr4/DRLLexer.g4 | 20 +++++++-- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 2 +- 4 files changed, 56 insertions(+), 13 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 c40543c485e..f5316757822 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 @@ -3449,7 +3449,6 @@ void semicolonEnd() { " $s : String()\n" + "then\n" + " delete($s);end\n"; // no space after semicolon - PackageDescr packageDescr = parser.parse(text ); RuleDescr ruleDescr = packageDescr.getRules().get(0); @@ -3464,9 +3463,6 @@ void braceEnd() { " $p : Person()\n" + "then\n" + " modify($p) { setAge(2) }end\n"; // no space after right brace - - System.out.println(text); - PackageDescr packageDescr = parser.parse(text ); RuleDescr ruleDescr = packageDescr.getRules().get(0); @@ -3481,12 +3477,47 @@ void parenthesisEnd() { " $p : Person()\n" + "then\n" + " retract($p)end\n"; // no space after right parenthesis + PackageDescr packageDescr = parser.parse(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("retract($p)"); + } - System.out.println(text); + @Test + void singleQuoteInRhsWithSpace() { + String consequence = getResultConsequence(" System.out.println( 'singleQuoteInRhs' );\n"); + assertThat(consequence) + .as("Single quote should be converted to double quote") + .isEqualToIgnoringWhitespace("System.out.println( \"singleQuoteInRhs\" );"); + } - PackageDescr packageDescr = parser.parse(text ); + @Test + void singleQuoteInRhsWithoutSpace() { + String consequence = getResultConsequence(" System.out.println('singleQuoteInRhs');\n"); + assertThat(consequence) + .as("Single quote should be converted to double quote") + .isEqualToIgnoringWhitespace("System.out.println( \"singleQuoteInRhs\" );"); + } + + @Test + void singleQuoteInDoubleQuoteInRhsWithoutSpace() { + String consequence = getResultConsequence(" System.out.println(\"There is '\" + $s + \"' in the workspace.\");\n"); + assertThat(consequence) + .as("Single quote should not be converted to double quote in case of inside double quotes") + .isEqualToIgnoringWhitespace("System.out.println(\"There is '\" + $s + \"' in the workspace.\");"); + } + + private String getResultConsequence(String rhs) { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + rhs + + "end\n"; + PackageDescr packageDescr = parser.parse(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); - assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("retract($p)"); + return ruleDescr.getConsequence().toString(); } } 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/DRLLexer.g4 index a2ef0328237..a54ee07fdac 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/DRLLexer.g4 @@ -158,9 +158,21 @@ DrlUnicodeEscape mode RHS; RHS_WS : [ \t\r\n\u000C]+ -> channel(HIDDEN); DRL_RHS_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) {setText("end");} -> popMode; + +RHS_STRING_LITERAL + // cannot reuse DRL_STRING_LITERAL because Actions are ignored in referenced rules + : ('"' ( DrlEscapeSequence | ~('\\'|'"') )* '"') + | ('\'' ( DrlEscapeSequence | ~('\\'|'\'') )* '\'') { setText( normalizeString( getText() ) ); } + ; + RHS_CHUNK - : ~[ ;})\t\r\n\u000C]+ [;})]? // ; } ) could be a delimitter proceding 'end' - | SEMI - | RBRACE + : ~[ ()[\]{},;\t\r\n\u000C]+ // ;}) could be a delimitter proceding 'end'. ()[]{},; are delimiters to match RHS_STRING_LITERAL + | LPAREN | RPAREN - ; \ No newline at end of file + | LBRACK + | RBRACK + | LBRACE + | RBRACE + | COMMA + | SEMI + ; 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/DRLParser.g4 index 933c013ee6c..5ae8c9016b2 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/DRLParser.g4 @@ -428,7 +428,7 @@ lhsAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) rhs : DRL_THEN consequence ; -consequence : RHS_CHUNK* ; +consequence : ( RHS_STRING_LITERAL | RHS_CHUNK )* ; stringId : ( IDENTIFIER | DRL_STRING_LITERAL ) ; 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 a3cae67b9b2..e28b6df8873 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 @@ -263,7 +263,7 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { if (ctx.rhs() != null) { ruleDescr.setConsequenceLocation(ctx.rhs().getStart().getLine(), ctx.rhs().getStart().getCharPositionInLine()); // location of "then" - ruleDescr.setConsequence(trimThen(getTextPreservingWhitespace(ctx.rhs()))); // RHS is just a text + ruleDescr.setConsequence(trimThen(getTokenTextPreservingWhitespace(ctx.rhs(), tokenStream))); // RHS is just a text } return ruleDescr; From 0528dc249dd376ad635b9b3d180a9ed88f69074a Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 26 Feb 2024 20:04:46 +0900 Subject: [PATCH 058/141] [incubator-kie-drools#5701] org.kie.api.KieBase.getRule(String, String) is null (#5730) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 17 +++++++++++++++++ .../drl/parser/antlr4/DRLVisitorImpl.java | 6 ++++-- 2 files changed, 21 insertions(+), 2 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 f5316757822..d06a7033c87 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 @@ -3520,4 +3520,21 @@ private String getResultConsequence(String rhs) { RuleDescr ruleDescr = packageDescr.getRules().get(0); return ruleDescr.getConsequence().toString(); } + + void ruleDescrProperties() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p);\n" + + "end\n"; + + PackageDescr packageDescr = parser.parse(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + assertThat(ruleDescr.getName()).isEqualTo("R1"); + assertThat(ruleDescr.getNamespace()).isEqualTo("org.drools"); + } } 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 e28b6df8873..c37284fa516 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 @@ -126,8 +126,10 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc } else if (descr instanceof AttributeDescr) { packageDescr.addAttribute((AttributeDescr) descr); } else if (descr instanceof RuleDescr) { // QueryDescr extends RuleDescr - packageDescr.addRule((RuleDescr) descr); - packageDescr.afterRuleAdded((RuleDescr) descr); + RuleDescr ruleDescr = (RuleDescr) descr; + packageDescr.addRule(ruleDescr); + packageDescr.afterRuleAdded(ruleDescr); + ruleDescr.setNamespace(packageDescr.getNamespace()); } }); } From 21bc906aeda10d4c907e27a68d79b7ff63df5d14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Thu, 29 Feb 2024 09:40:23 +0100 Subject: [PATCH 059/141] Fix super_key failed predicate (#5748) --- .../drl/parser/antlr4/DRLExprParserTest.java | 38 +++++++++++++++++++ .../drl/parser/antlr4/DRL6Expressions.g4 | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) 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 b573cd1ae5c..63435291109 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 @@ -268,4 +268,42 @@ public void testNestedExpression() throws Exception { assertThat(left.getExpression()).isEqualTo("a"); assertThat(right.getExpression()).isEqualTo("b"); } + + @Test + public void selector_dot_super() { + String source = "SomeClass.super.getData() != null"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo("!="); + + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + + assertThat(left.getExpression()).isEqualTo("SomeClass.super.getData()"); + assertThat(right.getExpression()).isEqualTo("null"); + } + + @Test + public void selector_dot_identifier() { + String source = "getAddress().getCity().length() == 5"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo("=="); + + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + + assertThat(left.getExpression()).isEqualTo("getAddress().getCity().length()"); + assertThat(right.getExpression()).isEqualTo("5"); + } } 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/DRL6Expressions.g4 index ef6e0982672..a981b208676 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/DRL6Expressions.g4 @@ -774,7 +774,7 @@ extends_key ; super_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.SUPER))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : {(helper.validateIdentifierKey(DroolsSoftKeywords.SUPER))}? id=SUPER { helper.emit($id, DroolsEditorType.KEYWORD); } ; instanceof_key From c746b66639aacff0c6dbdff02d40f9cf1dbe1c24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Thu, 29 Feb 2024 09:40:47 +0100 Subject: [PATCH 060/141] Fix minor issues in the new parser (#5747) * Add missing `@Test` annotation * Fix a typo in method name --- .../src/main/java/org/drools/compiler/lang/DescrDumper.java | 2 +- .../org/drools/compiler/rule/builder/PatternBuilder.java | 2 +- .../drools/compiler/rule/builder/QueryElementBuilder.java | 6 +++--- .../org/drools/drl/parser/antlr4/MiscDRLParserTest.java | 5 +++-- .../java/org/drools/drl/parser/DrlExprParserFactory.java | 2 +- .../org/drools/mvel/compiler/lang/DRLExprParserTest.java | 4 ++-- .../java/org/drools/mvel/compiler/lang/DescrDumperTest.java | 2 +- .../drools/verifier/visitor/ExprConstraintDescrVisitor.java | 2 +- 8 files changed, 13 insertions(+), 12 deletions(-) diff --git a/drools-compiler/src/main/java/org/drools/compiler/lang/DescrDumper.java b/drools-compiler/src/main/java/org/drools/compiler/lang/DescrDumper.java index 5cc792e61d3..52137604b4d 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/lang/DescrDumper.java +++ b/drools-compiler/src/main/java/org/drools/compiler/lang/DescrDumper.java @@ -138,7 +138,7 @@ public StringBuilder dump( StringBuilder sbuilder, } private void processConstraint(StringBuilder sbuilder, ExprConstraintDescr base, boolean isInsideRelCons, DumperContext context) { - DrlExprParser expr = DrlExprParserFactory.getDrlExrParser(context.getRuleContext().getConfiguration().getOption(LanguageLevelOption.KEY)); + DrlExprParser expr = DrlExprParserFactory.getDrlExprParser(context.getRuleContext().getConfiguration().getOption(LanguageLevelOption.KEY)); ConstraintConnectiveDescr result = expr.parse( base.getExpression() ); if ( result.getDescrs().size() == 1 ) { dump( sbuilder, diff --git a/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java b/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java index 5a5dafaa606..b57e2c9cc63 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java +++ b/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java @@ -1804,7 +1804,7 @@ protected ConstraintConnectiveDescr parseExpression(final RuleBuildContext conte final PatternDescr patternDescr, final BaseDescr original, final String expression) { - DrlExprParser parser = DrlExprParserFactory.getDrlExrParser(context.getConfiguration().getOption(LanguageLevelOption.KEY)); + DrlExprParser parser = DrlExprParserFactory.getDrlExprParser(context.getConfiguration().getOption(LanguageLevelOption.KEY)); ConstraintConnectiveDescr result = parser.parse(normalizeEval(expression)); result.setResource(patternDescr.getResource()); result.copyLocation(original); diff --git a/drools-compiler/src/main/java/org/drools/compiler/rule/builder/QueryElementBuilder.java b/drools-compiler/src/main/java/org/drools/compiler/rule/builder/QueryElementBuilder.java index 3889990858e..7de694c96cf 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/rule/builder/QueryElementBuilder.java +++ b/drools-compiler/src/main/java/org/drools/compiler/rule/builder/QueryElementBuilder.java @@ -69,7 +69,7 @@ public RuleConditionElement build( RuleBuildContext context, BaseDescr descr ) { throw new UnsupportedOperationException(); } - + public RuleConditionElement build( RuleBuildContext context, BaseDescr descr, Pattern prefixPattern ) { @@ -265,7 +265,7 @@ private void processBinding( RuleBuildContext context, } else { // it must be a literal/expression // it's an expression and thus an input - DrlExprParser parser = DrlExprParserFactory.getDrlExrParser(context.getConfiguration().getOption(LanguageLevelOption.KEY)); + DrlExprParser parser = DrlExprParserFactory.getDrlExprParser(context.getConfiguration().getOption(LanguageLevelOption.KEY)); ConstraintConnectiveDescr bresult = parser.parse( bind.getExpression() ); if ( parser.hasErrors() ) { for ( DroolsParserException error : parser.getErrors() ) { @@ -396,7 +396,7 @@ private static int getPos( String identifier, private ConstraintConnectiveDescr parseExpression( final RuleBuildContext context, final PatternDescr patternDescr, final String expression ) { - DrlExprParser parser = DrlExprParserFactory.getDrlExrParser( context.getConfiguration().getOption(LanguageLevelOption.KEY)); + DrlExprParser parser = DrlExprParserFactory.getDrlExprParser( context.getConfiguration().getOption(LanguageLevelOption.KEY)); ConstraintConnectiveDescr result = parser.parse( expression ); if ( result == null || parser.hasErrors() ) { for ( DroolsParserException error : parser.getErrors() ) { 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 d06a7033c87..cbc9686acb7 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 @@ -3115,7 +3115,7 @@ public void parse_IsQuery() throws Exception { @Test public void parse_FromFollowedByQuery() throws Exception { - // the 'from' expression requires a ";" to disambiguate the "?" + // the 'from' expression requires a ";" to disambiguate the "?" // prefix for queries from the ternary operator "? :" final String text = "rule X when Cheese() from $cheesery ?person( \"Mark\", 42; ) then end"; RuleDescr rule = parseAndGetFirstRuleDescr( @@ -3135,7 +3135,7 @@ public void parse_FromFollowedByQuery() throws Exception { @Test public void parse_FromWithTernaryFollowedByQuery() throws Exception { - // the 'from' expression requires a ";" to disambiguate the "?" + // the 'from' expression requires a ";" to disambiguate the "?" // prefix for queries from the ternary operator "? :" final String text = "rule X when Cheese() from (isFull ? $cheesery : $market) ?person( \"Mark\", 42; ) then end"; RuleDescr rule = parseAndGetFirstRuleDescr( @@ -3521,6 +3521,7 @@ private String getResultConsequence(String rhs) { return ruleDescr.getConsequence().toString(); } + @Test void ruleDescrProperties() { final String text = "package org.drools\n" + "rule R1\n" + 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 ae3ffcf9359..58659218037 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 @@ -5,7 +5,7 @@ public class DrlExprParserFactory { - public static DrlExprParser getDrlExrParser(LanguageLevelOption languageLevel) { + public static DrlExprParser getDrlExprParser(LanguageLevelOption languageLevel) { switch (languageLevel) { case DRL5: case DRL6: diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java index c7357aad4de..3a59b507301 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java @@ -43,7 +43,7 @@ public class DRLExprParserTest { @Before public void setUp() throws Exception { new EvaluatorRegistry(); - this.parser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL6); + this.parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); } @After @@ -182,7 +182,7 @@ public void testBindingWithRestrictions() throws Exception { AtomicExprDescr right = (AtomicExprDescr) rel.getRight(); assertThat(right.getExpression()).isEqualTo("value"); - + rel = (RelationalExprDescr) result.getDescrs().get( 1 ); assertThat(rel.getOperator()).isEqualTo("<"); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java index 5eb52e62830..0af0bc01635 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java @@ -359,7 +359,7 @@ public void testProcessImplicitConstraints() throws Exception { } public ConstraintConnectiveDescr parse( final String constraint ) { - DrlExprParser parser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL6); + DrlExprParser parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); ConstraintConnectiveDescr result = parser.parse( constraint ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); diff --git a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java index 6e6ef96a82a..89b05be9f93 100644 --- a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java +++ b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java @@ -58,7 +58,7 @@ public ExprConstraintDescrVisitor(Pattern pattern, VerifierData data, OrderNumbe public void visit(ExprConstraintDescr descr) { - DrlExprParser drlExprParser = DrlExprParserFactory.getDrlExrParser(LanguageLevelOption.DRL5); + DrlExprParser drlExprParser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL5); ConstraintConnectiveDescr constraintConnectiveDescr = drlExprParser.parse(descr.getExpression()); visit(constraintConnectiveDescr.getDescrs()); From 643628ba6e1c55a7e9d799d5960fddaba79eb5a1 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 4 Mar 2024 20:13:13 +0900 Subject: [PATCH 061/141] =?UTF-8?q?[incubator-kie-drools#5743]=20Update=20?= =?UTF-8?q?Developer=5FNotes.md=20to=20be=20community=E2=80=A6=20(#5751)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools#5743] Update Developer_Notes.md to be community-friendly * Update drools-drl/drools-drl-parser/Developer_Notes.md Co-authored-by: Jiří Locker * Update drools-drl/drools-drl-parser/Developer_Notes.md Co-authored-by: Jiří Locker * - Add Design notes --------- Co-authored-by: Jiří Locker --- .../drools-drl-parser/Developer_Notes.md | 104 ++++++++++++++++++ .../drl/parser/antlr4/Developer_Notes.md | 38 ------- 2 files changed, 104 insertions(+), 38 deletions(-) create mode 100644 drools-drl/drools-drl-parser/Developer_Notes.md delete mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Developer_Notes.md diff --git a/drools-drl/drools-drl-parser/Developer_Notes.md b/drools-drl/drools-drl-parser/Developer_Notes.md new file mode 100644 index 00000000000..d3d2d77e1be --- /dev/null +++ b/drools-drl/drools-drl-parser/Developer_Notes.md @@ -0,0 +1,104 @@ +# drools-drl-parser + +In this `dev-new-parser` branch, `drools-drl-parser` has 2 implementations of the DRL parser. The new parser is under development, and the old parser is used in the current drools code base. + +The old DRL parser is based on Antlr3 and contains lots of hard-coded logic in generated java codes, so it's hard to maintain e.g. [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java). It is the reason why the new parser is being developed. The old parser resources are placed under `src/main/java/org/drools/drl/parser/lang` and `src/main/resources/org/drools/drl/parser`. + +The new DRL parser is based on Antlr4, which has Visitor and Listener support, so the parser would have cleaner separation between the parser syntax (`DRLParser.g4`) and Java code which generates Descr objects (`DRLVisitorImpl.java`). It would be easier to maintain and extend the parser. The new parser resources are placed under `src/main/java/org/drools/drl/parser/antlr4` and `src/main/antlr4/org/drools/drl/parser/antlr4`. + +## The current status of the new parser development +The new DRL parser doesn't introduce new syntax at the first stage. In order to keep the compatibility with the old parser, we make use of existing unit tests. + +As of 2024/02/27, we hit lots of test failures in existing drools unit tests. The test failures are filed as child issues of the parent issue [Experiment: New DRL Parser](https://github.com/apache/incubator-kie-drools/issues/5678). We will fix the test failures one by one. + +## How to contribute to the development + +**Contribution would be highly appreciated!** Here is a rough guide to contribute to the development. + +1. Look at the parent issue [Experiment: New DRL Parser](https://github.com/apache/incubator-kie-drools/issues/5678) and choose a child issue which you want to work on. +2. If you have an ASF committer role, assign yourself to the child issue. If you don't have the role, post a comment on the child issue that you are working on it so that we can avoid duplicated work. +3. Create a feature branch based on the `dev-new-parser` branch. +4. Fix the issue and make sure that the test in problem is passed and also all tests under `drools-drl-parser-tests` are passed. +5. Add new tests to `drools-drl-parser-tests` to cover the issue. Hopefully, such a test would be a Descr comparison test. See `MiscDRLParserTest` and `DRLExprParserTest`. +6. File a pull request to the `dev-new-parser` branch. **Be careful not to file a pull request to the `main` branch.** + +## Design notes + +`org.drools.drl.parser.DrlParser` is a common entry point of the new/old parser implementations. Depending on a system property switch `drools.drl.antlr4.parser.enabled`, it chooses the new parser `org.drools.drl.parser.antlr4.DRLParserWrapper` or the old parser `org.drools.drl.parser.lang.DRL6Parser`. + +The responsibilities of a DRL parser are: + +1. Parse DRL text and generate an AST (abstract syntax tree) +2. Using the AST, generate `Descr` objects which encapsulate information to be used in the later build phase. The top level object is `PackageDescr`. +3. If there are any parse errors, populate `List results`. + +Common to Antlr 3 and 4, Lexer/Parser java classes are generated from grammar files. For the new parser, grammar files are `DRLLexer.g4` and `DRLParser.g4`. For the old parser, the lexer grammar is `DRL6Lexer.g`, but the parser grammar `drl.g` had been removed from the repo long time ago (https://github.com/apache/incubator-kie-drools/commit/c2ef448d8ed2f935480b9576f4dc83ba7b007a9b) because we directly customized the generated `DRL6Parser.java`. We no longer generate `DRL6Parser.java` with Antlr3 tooling. + +With the Antlr3 old parser, we had to write the `Descr` object generation java code inside the parser grammar file (= parser actions). Eventually, we had gone to the direct java code customization, probably because some features were not feasible with parser actions. + +With the Antlr4 new parser, we can isolate java codes from `DRLParser.g4` to `DRLVisitorImpl.java` which visits the AST and generate the `Descr` objects. There is no need to customize generated java codes (e.g. `DRLLexer.java`, `DRLParser.java` under `target/generated-sources`). When we fix or expand the parser, we should edit java sources under `src/main/java/org/drools/drl/parser/antlr4` (e.g. `DRLVisitorImpl.java`, `DRLParserWrapper.jva`). + +--- + +For `DRL6Expressions`, we take a little different approach. `DrlExprParserFactory` is a common entry point of the new/old **expression** parser implementations. Similar to `DrlParser`, depending on a system property switch `drools.drl.antlr4.parser.enabled`, it chooses the new parser `org.drools.drl.parser.antlr4.Drl6ExprParserAntlr4` or the old parser `org.drools.drl.parser.Drl6ExprParser`. + +The responsibilities of an expression parser are: + +1. Parse DRL constraint text and generate an AST +2. Using the AST, generate `Descr` objects which encapsulate information to be used in the build phase. The top level object depends on the constraint. +3. If there are any parse errors, store them to be retrieved by `List getErrors()` + +As the old expression parser doesn't have the problem of "hard-coded", the new expression parser grammar file `DRL6Expressions.g4` is basically the same as the old `DRL6Expressions.g`, but just adjusted to work with Antlr4. So not using Visitor pattern at the moment. Applying Visitor pattern to the new expression parser is one of refactoring candidates. + +## Additional notes + +- The new parser are consist of 2 important parsers. + - One is `DRLParser` which is generated from `DRLParser.g4`. This parser is responsible for parsing an entire DRL text and generating an AST. Descr objects are generated by applying `DRLVisitorImpl` to the AST. Drools engine uses the parser with `DRLParserWrapper`. + - The other is `DRL6Expressions` which is generated from `Drl6Expressions.g4`. This parser is specifically used to parse LHS constraints at the later rule compile phase. Drools engine uses the parser with `Drl6ExprParserAntlr4`. + +- As of 2024/02/27, we have 4 test classes under `drools-drl-parser-tests`. + - `DRLParserTest` is a very basic test to check if the parser can parse DRL. + - `MiscDRLParserTest` contains various DRL syntax to check if the parser generates correct Descr objects. `MiscDRLParserTest` was ported from [RuleParserTest](https://github.com/apache/incubator-kie-drools/blob/main/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java) so that we can ensure the compatibility of generated Descr objects between the old implementation and the new one. `MiscDRLParserTest` still has several test cases with `@Disabled` which are relatively lower priority or edge cases. They are also the target of the ongoing development. + - `DRLExprParserTest` is to test `DRL6Expressions` parser. + - `DescrDumperTest` is to test the dump result of generated Descr objects. This is originally a test for `DescDumper`, but it's also useful to test `DRL6Expressions` parser. + - It would be fine to add more test classes if necessary. + +- As of 2024/02/27, the `dev-new-parser` branch even fails to build `kie-dmn-validation`. Please ignore the build failure until we fix the test failures of `drools-model-codegen` +- `drools-model-codegen` is a good place to detect various test failures. Once we clean up the test failures of `drools-model-codegen`, we would tackle `kie-dmn-validation` build and `drools-test-coverage` tests. + +- `DRL5Parser` and `DRL6StrictParser` are minor variants, and they will likely be removed in the near feature. + +- About similar areas: + - `drools-compiler` contains `JavaParser` which was generated by `Java.g`. This is used by `drools-mvel` to execute java dialect. As `drools-mvel` is deprecated, it is not the scope of this new parser development. + - `drools-model/drools-mvel-parser` contains javacc based `mvel.jj` to parse constraint and RHS in executable models. It is good enough as it is, so not the scope of this new parser development. + +### (Advanced) How was the new parser developed? + +**DRLParser** + +1. The starting point is [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java). While it contains lots of customizations, we can map its javadoc (e.g. `packageStatement := PACKAGE qualifiedIdentifier SEMICOLON?`) to `DRLParser.g4` (e.g. `packagedef : PACKAGE name=drlQualifiedName SEMI? ;`). +2. `DRLLexer.g4` is written to define tokens for DRL. +3. `DRLLexer.g4` imports `JavaLexer.g4` to reuse Java tokens. `DRLParser.g4` imports `JavaParser.g4` to reuse Java grammar. These Java parser files are distributed by ANTLR4 under BSD license. +4. In `DRLLexer.g4`, basically define tokens with a prefix "DRL_" to clarify they are DRL keywords. +5. In `DRLParser.g4`, define parser rules with a prefix "drl" if the rule name conflicts with `JavaParser.g4`. Sometimes we need to do that, because such a rule may contain DRL keywords. +6. (As of 2024/02/27) this parser doesn't deeply parse rule RHS (just multiple `RHS_CHUNK`s), because Drools passes RHS text to drools-compiler as-is. In case of developing DRL editors, we may need to integrate another Java LSP to support RHS code completion, etc. +7. LHS constraint (e.g. `age > 30`) is also handled as text. Further processing will be done by `DRL6Expressions` parser in the later compiler phase. +8. `DRLParser` processes a DRL text and produces an AST. Then apply `DRLVisitorImpl` to generate PackageDescr following the visitor pattern. So the main work would be implementing `DRLParser.g4` and `DRLVisitorImpl`. +9. Errors are handled by `DRLErrorListener` + +**DRL6Expressions** + +1. `DRL6Expressions.g4` was copied from `DRL6Expressions.g` in the old parser. Then, it was modified to work with Antlr4. + +### Refactoring candidates +- New parser related class names are not very consistent. There is a room to improve. +- `DRLParserHelper` and `DRLParserWrapper` have some duplicated code and purpose. We can merge them into one class. +- `MiscDRLParserTest` can be cleaner and fixed to align with SonarLint suggestions. +- There is parser rules overlap between `DRLParser.g4` and `DRL6Expressions.g4` after `conditionalOrExpression`. There is a room to improve. e.g. delegating the constraint parsing to `DRL6Expressions` parser. +- `DRL6Expressions` parser doesn't use Visitor pattern at the moment. Rather, it uses more parser actions. It would be nice to use Visitor pattern to generate Descr objects. + +### Development environment tips +- IntelliJ IDEA has an ANTLR4 plugin, which "ANTLR Preview" window displays a parse tree. It is very useful to debug the parser rules. + +### Resources +[The Definitive ANTLR 4 Reference](https://pragprog.com/titles/tpantlr2/the-definitive-antlr-4-reference/) \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Developer_Notes.md b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Developer_Notes.md deleted file mode 100644 index c521ee6d14f..00000000000 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Developer_Notes.md +++ /dev/null @@ -1,38 +0,0 @@ -## drools-parser - -This module is a reimplementation of the DRL (Drools Rule Language) parser based on ANTLR4. - -The current [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java) is based on ANTLR3 and contains a lot of custom modifications, which is hard to maintain. This new module should keep the separation between the parser syntax (`DRLParser.g4`) and the Descr generation (`DRLVisitorImpl.java`). - -This module started with a part of LSP to develop DRL editors, but it is not limited to that. This module will also replace DRL6Parser in the drools code base. - -### How is this developed? - -1. The starting point is [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java). While it contains lots of customizations, we can map its javadoc (e.g. `packageStatement := PACKAGE qualifiedIdentifier SEMICOLON?`) to `DRLParser.g4` (e.g. `packagedef : PACKAGE name=drlQualifiedName SEMI? ;`). -2. `DRLLexer.g4` is written to define tokens for DRL. -3. `DRLLexer.g4` imports `JavaLexer.g4` to reuse Java tokens. `DRLParser.g4` imports `JavaParser.g4` to reuse Java grammar. These Java parser files are distributed by ANTLR4 under BSD license. -4. In `DRLLexer.g4`, basically define tokens with a prefix "DRL_" to clarify they are DRL keywords. -5. In `DRLParser.g4`, define parser rules with a prefix "drl" if the rule name conflicts with `JavaParser.g4`. Sometimes we need to do that, because such a rule may contain DRL keywords. -6. (As of 2023/10/31) this parser doesn't deeply parse rule RHS (just multiple `RHS_CHUNK`s), because Drools passes RHS text to drools-compiler as-is. In case of developing DRL editors, we may need to integrate another Java LSP to support RHS code completion, etc. -7. LHS constraint (e.g. `age > 30`) is also handled as text. Further processing will be done in the later compiler phase. -8. `DRLParser` processes a DRL text and produces an AST(abstract syntax tree). Then apply `DRLVisitorImpl` to generate PackageDescr following the visitor pattern. So the main work would be implementing `DRLParser.g4` and `DRLVisitorImpl`. -9. Errors are handled by `DRLErrorListener` -10. (As of 2023/10/31) We have 2 test classes. `DRLParserTest` is a very basic test to check if the parser can parse DRL. `MiscDRLParserTest` contains various DRL syntax to check if the parser generates correct Descr objects. `MiscDRLParserTest` was ported from [RuleParserTest](https://github.com/apache/incubator-kie-drools/blob/main/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java) so that we can ensure the compatibility of generated Descr objects between the current implementation and the new one. -11. As `DRL6Parser` contains hard-coded customizations, sometimes we need to read and understand the `DRL6Parser` source codes to meet the compatibility. -12. (As of 2023/10/31) `MiscDRLParserTest` still has several test cases with `@Disabled` which are relatively lower priority or edge cases. They need to be resolved at some point in the future. To fix the issues, file a JIRA, remove the `@Disabled` annotation, and fix the implementation to pass the test case. - -### Next steps - -1. Create a feature branch in drools repo and replace `DRL6Parser` with this new parser. -2. We will detect issues in the new parser by running the existing tests in drools repo. If we find any issues, we will fix them in the new parser and add new tests to cover them. Such tests would be more or less Descr comparison tests, so we would add a new test class which is similar to `MiscDRLParserTest`. - -### Refactoring candidates -- `DRLParserHelper` and `DRLParserWrapper` have some duplicated code and purpose. We can merge them into one class. -- `MiscDRLParserTest` can be cleaner and fixed to align with SonarLint suggestions. -- Constraint related parser rules after `conditionalOrExpression` are written in antlr3 style. They could be refactored to antlr4 style (like `lhsExpression`). - -### Development tips -- IntelliJ IDEA has an ANTLR4 plugin, which "ANTLR Preview" window displays a parse tree. It is very useful to debug the parser rules. - -### Resources -[The Definitive ANTLR 4 Reference](https://pragprog.com/titles/tpantlr2/the-definitive-antlr-4-reference/) \ No newline at end of file From 63e12cbdc06ee74b13a8ba67fd5c477e322501bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Tue, 5 Mar 2024 08:23:33 +0100 Subject: [PATCH 062/141] Fix the rest of the keywords (#5759) --- drools-drl/drools-drl-parser-tests/pom.xml | 5 ++ .../drl/parser/antlr4/DRLExprParserTest.java | 49 +++++++++++++------ .../drl/parser/antlr4/DRL6Expressions.g4 | 36 +++++++------- 3 files changed, 57 insertions(+), 33 deletions(-) diff --git a/drools-drl/drools-drl-parser-tests/pom.xml b/drools-drl/drools-drl-parser-tests/pom.xml index 7e0c4d5f886..4f3a19c8127 100644 --- a/drools-drl/drools-drl-parser-tests/pom.xml +++ b/drools-drl/drools-drl-parser-tests/pom.xml @@ -55,6 +55,11 @@ junit-jupiter-engine test + + org.junit.jupiter + junit-jupiter-params + test + ch.qos.logback logback-classic 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 63435291109..f740b369ea8 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 @@ -30,6 +30,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.kie.internal.builder.conf.LanguageLevelOption; /** @@ -269,41 +271,58 @@ public void testNestedExpression() throws Exception { assertThat(right.getExpression()).isEqualTo("b"); } - @Test - public void selector_dot_super() { - String source = "SomeClass.super.getData() != null"; + /** + * Each test input is a simple expression covering one of the existing keywords. The test is successful if the parser has + * no errors and the descriptor's expression string is equal to the input. + * + * @param source expression using a keyword + */ + @ParameterizedTest + @ValueSource(strings = { + "(X) x", + "SomeClass.super.getData()", + "(boolean) b", + "(char) c", + "(byte) b", + "(short) s", + "(int) i", + "(long) l", + "(float) f", + "(double) d", + "this()", + "Object[][].class.getName()", + "newArrayList()" + }) + void testKeywords(String source) { ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); assertThat(result.getDescrs().size()).isEqualTo(1); - RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); - assertThat(expr.getOperator()).isEqualTo("!="); - - AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); - AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + AtomicExprDescr expr = (AtomicExprDescr) result.getDescrs().get( 0 ); - assertThat(left.getExpression()).isEqualTo("SomeClass.super.getData()"); - assertThat(right.getExpression()).isEqualTo("null"); + assertThat(expr.getExpression()).isEqualTo(source); } @Test - public void selector_dot_identifier() { - String source = "getAddress().getCity().length() == 5"; + public void testKeyword_instanceof() { + String source = "a instanceof A"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); assertThat(result.getDescrs().size()).isEqualTo(1); + // Unlike the other keywords, instanceof can only be used in a relational expression, + // so it needs to be tested differently. RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); - assertThat(expr.getOperator()).isEqualTo("=="); + assertThat(expr.getOperator()).isEqualTo("instanceof"); AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); - assertThat(left.getExpression()).isEqualTo("getAddress().getCity().length()"); - assertThat(right.getExpression()).isEqualTo("5"); + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("A"); } } 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/DRL6Expressions.g4 index a981b208676..2b4a62e913f 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/DRL6Expressions.g4 @@ -770,72 +770,72 @@ assignmentOperator // KEYWORDS // -------------------------------------------------------- extends_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.EXTENDS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=EXTENDS { helper.emit($id, DroolsEditorType.KEYWORD); } ; super_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.SUPER))}? id=SUPER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=SUPER { helper.emit($id, DroolsEditorType.KEYWORD); } ; instanceof_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=INSTANCEOF { helper.emit($id, DroolsEditorType.KEYWORD); } ; boolean_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.BOOLEAN))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=BOOLEAN { helper.emit($id, DroolsEditorType.KEYWORD); } ; char_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.CHAR))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=CHAR { helper.emit($id, DroolsEditorType.KEYWORD); } ; byte_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.BYTE))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=BYTE { helper.emit($id, DroolsEditorType.KEYWORD); } ; short_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.SHORT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=SHORT { helper.emit($id, DroolsEditorType.KEYWORD); } ; int_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.INT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=INT { helper.emit($id, DroolsEditorType.KEYWORD); } ; float_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.FLOAT))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=FLOAT { helper.emit($id, DroolsEditorType.KEYWORD); } ; long_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.LONG))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=LONG { helper.emit($id, DroolsEditorType.KEYWORD); } ; double_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.DOUBLE))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=DOUBLE { helper.emit($id, DroolsEditorType.KEYWORD); } ; void_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.VOID))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=VOID { helper.emit($id, DroolsEditorType.KEYWORD); } ; this_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.THIS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=THIS { helper.emit($id, DroolsEditorType.KEYWORD); } ; class_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.CLASS))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=CLASS { helper.emit($id, DroolsEditorType.KEYWORD); } ; new_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.NEW))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=NEW { helper.emit($id, DroolsEditorType.KEYWORD); } ; not_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.NOT))}? id=DRL_NOT { helper.emit($id, DroolsEditorType.KEYWORD); } + : id=DRL_NOT { helper.emit($id, DroolsEditorType.KEYWORD); } ; in_key - : {(helper.validateIdentifierKey(DroolsSoftKeywords.IN))}? id=DRL_IN { helper.emit($id, DroolsEditorType.KEYWORD); } - ; + : id=DRL_IN { helper.emit($id, DroolsEditorType.KEYWORD); } + ; operator_key // TODO get rid of the DRL_MATCHES token or introduce DRL_CONTAINS etc. for consistency. From cd9bd78fe5830e68ede8b797264f74bd3c8cdf49 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 7 Mar 2024 17:09:28 +0900 Subject: [PATCH 063/141] =?UTF-8?q?[incubator-kie-drools#5705]=20[new-pars?= =?UTF-8?q?er]=20no=20viable=20alternative=20after=20=E2=80=A6=20(#5767)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools#5705] [new-parser] no viable alternative after contains operator * - Add comment * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker * - add javadoc to ParserHelper.isPluggableEvaluator --------- Co-authored-by: Jiří Locker --- .../drl/parser/antlr4/MiscDRLParserTest.java | 73 ++++++++++++++++++- .../drl/parser/antlr4/DRL6Expressions.g4 | 7 +- .../org/drools/drl/parser/antlr4/DRLLexer.g4 | 10 ++- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 21 ++++-- .../drl/parser/antlr4/ParserHelper.java | 8 ++ 5 files changed, 108 insertions(+), 11 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 cbc9686acb7..c869a190627 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 @@ -39,11 +39,12 @@ import org.drools.drl.ast.descr.TypeDeclarationDescr; import org.drools.drl.ast.descr.TypeFieldDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; -import org.drools.drl.parser.antlr4.DRLParserWrapper; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import static org.assertj.core.api.Assertions.assertThat; @@ -3538,4 +3539,74 @@ void ruleDescrProperties() { assertThat(ruleDescr.getName()).isEqualTo("R1"); assertThat(ruleDescr.getNamespace()).isEqualTo("org.drools"); } + + /** + * Each test input is a constraint expression covering one of the existing DRL operators. The test is successful if the parser has + * no errors and the descriptor's expression string is equal to the input. + * + * @param constraint expression using an operator + */ + @ParameterizedTest + @ValueSource(strings = { + "country matches \"[a-z]*\"", + "country not matches \"[a-z]*\"", + "person memberOf $europeanDescendants", + "person not memberOf $europeanDescendants", + "countries contains \"UK\"", + "countries not contains \"UK\"", + "countries excludes \"UK\"", + "countries not excludes \"UK\"", + "firstName soundslike \"John\"", + "firstName not soundslike \"John\"", + "routingValue str[startsWith] \"R1\"", + "routingValue not str[startsWith] \"R1\"" + }) + void constraintOperators(String constraint) { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person(" + constraint + ")\n" + + "then\n" + + "end\n"; + + PackageDescr packageDescr = parser.parse(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + AndDescr lhs = ruleDescr.getLhs(); + PatternDescr patternDescr = (PatternDescr) lhs.getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualToIgnoringWhitespace(constraint); + } + + @ParameterizedTest + @ValueSource(strings = { + "country matches \"[a-z]*\" || matches \"[A-Z]*\"", + "country not matches \"[a-z]*\" || not matches \"[A-Z]*\"", + "person memberOf $europeanDescendants || memberOf $africanDescendants", + "person not memberOf $europeanDescendants || not memberOf $africanDescendants", + "countries contains \"UK\" || contains \"US\"", + "countries not contains \"UK\" || not contains \"US\"", + "countries excludes \"UK\" || excludes \"US\"", + "countries not excludes \"UK\" || not excludes \"US\"", + "firstName soundslike \"John\" || soundslike \"Paul\"", + "firstName not soundslike \"John\" && not soundslike \"Paul\"", + "routingValue str[startsWith] \"R1\" || str[startsWith] \"R2\"", + "routingValue not str[startsWith] \"R1\" && not str[startsWith] \"R2\"" + }) + void halfConstraintOperators(String constraint) { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person(" + constraint + ")\n" + + "then\n" + + "end\n"; + + PackageDescr packageDescr = parser.parse(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + AndDescr lhs = ruleDescr.getLhs(); + PatternDescr patternDescr = (PatternDescr) lhs.getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualToIgnoringWhitespace(constraint); + } } 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/DRL6Expressions.g4 index 2b4a62e913f..51ea965a0f2 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/DRL6Expressions.g4 @@ -838,10 +838,11 @@ in_key ; operator_key - // TODO get rid of the DRL_MATCHES token or introduce DRL_CONTAINS etc. for consistency. - : {(helper.isPluggableEvaluator(false))}? id=(IDENTIFIER|DRL_MATCHES) { helper.emit($id, DroolsEditorType.KEYWORD); } + // At the moment, we list possible DRLLexer tokens here, but we may be able to improve this by isolating lexers. IDENTIFIER is required to accept custom operators + // We need to keep this semantic predicate for custom operators + : {(helper.isPluggableEvaluator(false))}? id=(IDENTIFIER|DRL_MATCHES|DRL_MEMBEROF|DRL_CONTAINS|DRL_EXCLUDES|DRL_SOUNDSLIKE|DRL_STR) { helper.emit($id, DroolsEditorType.KEYWORD); } ; neg_operator_key - : {(helper.isPluggableEvaluator(true))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : {(helper.isPluggableEvaluator(true))}? id=(IDENTIFIER|DRL_MATCHES|DRL_MEMBEROF|DRL_CONTAINS|DRL_EXCLUDES|DRL_SOUNDSLIKE|DRL_STR) { helper.emit($id, DroolsEditorType.KEYWORD); } ; 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/DRLLexer.g4 index a54ee07fdac..79c439586f6 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/DRLLexer.g4 @@ -45,8 +45,6 @@ DRL_NOT : 'not'; DRL_IN : 'in'; DRL_FROM : 'from'; DRL_COLLECT : 'collect'; -DRL_MATCHES : 'matches'; -DRL_MEMBEROF : 'memberOf'; DRL_ACCUMULATE : 'accumulate'; DRL_ACC : 'acc'; DRL_INIT : 'init'; @@ -58,6 +56,14 @@ DRL_EVAL : 'eval'; DRL_FORALL : 'forall'; DRL_OVER : 'over'; +// constraint operators +DRL_MATCHES : 'matches'; +DRL_MEMBEROF : 'memberOf'; +DRL_CONTAINS : 'contains'; +DRL_EXCLUDES : 'excludes'; +DRL_SOUNDSLIKE : 'soundslike'; +DRL_STR : 'str'; + // temporal operators DRL_AFTER : 'after'; DRL_BEFORE : 'before'; 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/DRLParser.g4 index 5ae8c9016b2..d65c9e2b735 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/DRLParser.g4 @@ -129,6 +129,8 @@ positionalConstraints : constraint (COMMA constraint)* SEMI ; constraints : constraint (COMMA constraint)* ; constraint : ( nestedConstraint | conditionalOrExpression ) ; nestedConstraint : ( IDENTIFIER ( DOT | HASH ) )* IDENTIFIER DOT LPAREN constraints RPAREN ; + +// TBD: constraint parsing could be delegated to DRL6ExpressionParser conditionalOrExpression : left=conditionalAndExpression (OR right=conditionalAndExpression)* ; conditionalAndExpression : left=inclusiveOrExpression (AND right=inclusiveOrExpression)* ; inclusiveOrExpression : left=exclusiveOrExpression (BITOR right=exclusiveOrExpression)* ; @@ -149,9 +151,18 @@ relationalOperator | GE | GT | LT + | drlRelationalOperator | temporalOperator ; +drlRelationalOperator + : DRL_NOT? DRL_MATCHES + | DRL_NOT? DRL_MEMBEROF + | DRL_NOT? DRL_CONTAINS + | DRL_NOT? DRL_EXCLUDES + | DRL_NOT? DRL_SOUNDSLIKE + | DRL_NOT? DRL_STR LBRACK IDENTIFIER RBRACK ; + /* function := FUNCTION type? ID parameters(typed) chunk_{_} */ functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters block ; @@ -200,6 +211,10 @@ drlKeywords | DRL_FROM | DRL_MATCHES | DRL_MEMBEROF + | DRL_CONTAINS + | DRL_EXCLUDES + | DRL_SOUNDSLIKE + | DRL_STR | DRL_ACCUMULATE | DRL_ACC | DRL_INIT @@ -249,13 +264,9 @@ drlExpression | drlExpression bop=(MUL|DIV|MOD) drlExpression | drlExpression bop=(ADD|SUB) drlExpression | drlExpression (LT LT | GT GT GT | GT GT) drlExpression - | drlExpression bop=(LE | GE | GT | LT) drlExpression - | drlExpression temporalOperator drlExpression | drlExpression bop=INSTANCEOF (typeType | pattern) - | drlExpression bop=DRL_MATCHES drlExpression - | drlExpression DRL_NOT? DRL_MEMBEROF drlExpression + | drlExpression relationalOperator drlExpression | drlExpression bop=DRL_UNIFY drlExpression - | drlExpression bop=(EQUAL | NOTEQUAL) drlExpression | drlExpression bop=BITAND drlExpression | drlExpression bop=CARET drlExpression | drlExpression bop=BITOR drlExpression diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java index 82d40b63020..1d533e3c51f 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java @@ -231,6 +231,14 @@ public boolean isPluggableEvaluator( int offset, return text2Validate != null && DroolsSoftKeywords.isOperator(text2Validate, negated); } + /** + * Check if the next token is a registered operator. + * The registry is dynamic, so we can add custom operators dynamically. + * @see org.drools.drl.parser.impl.Operator#addOperatorToRegistry(String, boolean) + * + * @param negated true if the operator needs to support negation + * @return true if the next token is a registered operator + */ public boolean isPluggableEvaluator( boolean negated ) { return isPluggableEvaluator( 1, negated ); From f36a0c9f5013ee997b6a860fc3db69f02273be85 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Sat, 9 Mar 2024 17:56:14 +0900 Subject: [PATCH 064/141] [incubator-kie-drools#5707] [new-parser] null-safe dereferencing broken (#5771) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 30 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 1 + 2 files changed, 31 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 c869a190627..5c82ed73ff2 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 @@ -3609,4 +3609,34 @@ void halfConstraintOperators(String constraint) { ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); assertThat(exprConstraintDescr.getExpression()).isEqualToIgnoringWhitespace(constraint); } + + @Test + void nullSafeDereferencing() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person(address!.city == $city)\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("address!.city == $city"); + } + + @Test + void nullSafeDereferencingMethodCall() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person(address!.city!.startsWith(\"M\"))\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("address!.city!.startsWith(\"M\")"); + } } 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/DRLParser.g4 index d65c9e2b735..6a98fab11ee 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/DRLParser.g4 @@ -253,6 +253,7 @@ drlExpression | SUPER superSuffix | explicitGenericInvocation ) + | drlExpression NULL_SAFE_DOT ( drlIdentifier | methodCall ) | drlExpression LBRACK drlExpression RBRACK | DRL_EVAL LPAREN conditionalOrExpression RPAREN | methodCall From f388e0399787ab602617b6baf4d44a5c679bcf21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 13 Mar 2024 16:51:43 +0100 Subject: [PATCH 065/141] Add error listener to DrlExprParser (#5778) --- .../compiler/rule/builder/PatternBuilder.java | 4 +- .../drools/drl/ast/descr/OperatorDescr.java | 2 +- .../drl/parser/antlr4/DRLExprParserTest.java | 47 ++++++++++++ .../parser/antlr4/Drl6ExprParserAntlr4.java | 14 ++-- .../antlr4/DroolsParserExceptionFactory.java | 76 ++++++++----------- .../drl/parser/antlr4/ParserHelper.java | 13 +--- 6 files changed, 91 insertions(+), 65 deletions(-) diff --git a/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java b/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java index b57e2c9cc63..6a481d3d915 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java +++ b/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java @@ -1806,8 +1806,6 @@ protected ConstraintConnectiveDescr parseExpression(final RuleBuildContext conte final String expression) { DrlExprParser parser = DrlExprParserFactory.getDrlExprParser(context.getConfiguration().getOption(LanguageLevelOption.KEY)); ConstraintConnectiveDescr result = parser.parse(normalizeEval(expression)); - result.setResource(patternDescr.getResource()); - result.copyLocation(original); if (parser.hasErrors()) { for (DroolsParserException error : parser.getErrors()) { registerDescrBuildError(context, patternDescr, @@ -1815,6 +1813,8 @@ protected ConstraintConnectiveDescr parseExpression(final RuleBuildContext conte } return null; } + result.setResource(patternDescr.getResource()); + result.copyLocation(original); return result; } 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 220923bcbc2..561bebe19a0 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 @@ -55,7 +55,7 @@ public String getOperator() { } public void setOperator( String operator ) { - this.operator = operator.trim(); + this.operator = operator != null ? operator.trim() : null; } 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 f740b369ea8..6fc7eecc6e6 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 @@ -26,6 +26,7 @@ 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.DroolsParserException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -325,4 +326,50 @@ public void testKeyword_instanceof() { assertThat(left.getExpression()).isEqualTo("a"); assertThat(right.getExpression()).isEqualTo("A"); } + + @Test + public void testMismatchedInput() { + String source = "+"; + parser.parse(source); + assertThat(parser.hasErrors()).isTrue(); + assertThat(parser.getErrors()).hasSize(1); + DroolsParserException exception = parser.getErrors().get(0); + assertThat(exception.getErrorCode()).isEqualTo("ERR 102"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(1); + assertThat(exception.getOffset()).isEqualTo(1); + assertThat(exception.getMessage()) + .startsWithIgnoringCase("[ERR 102] Line 1:1 mismatched input '' expecting ") + .contains("TIME_INTERVAL", "DRL_STRING_LITERAL", "?/", "boolean", "byte", "char", "double", "float", "int", "long", "new", "short", "super", "DECIMAL_LITERAL", "HEX_LITERAL", "FLOAT_LITERAL", "BOOL_LITERAL", "STRING_LITERAL", "null", "(", "[", ".", "<", "!", "~", "++", "--", "+", "-", "*", "/", "IDENTIFIER"); + } + + @Test + public void testExtraneousInput() { + String source = "a +; b"; + parser.parse(source); + assertThat(parser.hasErrors()).isTrue(); + assertThat(parser.getErrors()).hasSize(1); + DroolsParserException exception = parser.getErrors().get(0); + assertThat(exception.getErrorCode()).isEqualTo("ERR 109"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(3); + assertThat(exception.getOffset()).isEqualTo(3); + assertThat(exception.getMessage()) + .startsWithIgnoringCase("[ERR 109] Line 1:3 extraneous input ';' expecting ") + .contains("TIME_INTERVAL", "DRL_STRING_LITERAL", "?/", "boolean", "byte", "char", "double", "float", "int", "long", "new", "short", "super", "DECIMAL_LITERAL", "HEX_LITERAL", "FLOAT_LITERAL", "BOOL_LITERAL", "STRING_LITERAL", "null", "(", "[", ".", "<", "!", "~", "++", "--", "+", "-", "*", "/", "IDENTIFIER"); + } + @Test + public void testNoViableAlt() { + String source = "a~a"; + parser.parse(source); + assertThat(parser.hasErrors()).isTrue(); + assertThat(parser.getErrors()).hasSize(1); + DroolsParserException exception = parser.getErrors().get(0); + assertThat(exception.getErrorCode()).isEqualTo("ERR 101"); + assertThat(exception.getLineNumber()).isEqualTo(1); + 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'"); + } } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java index 220c8bb0667..4505ca428ae 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java @@ -21,9 +21,11 @@ import java.util.Collections; import java.util.List; +import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; import org.drools.drl.parser.DrlExprParser; @@ -47,11 +49,16 @@ public Drl6ExprParserAntlr4(LanguageLevelOption languageLevel) { /** Parse an expression from text */ public ConstraintConnectiveDescr parse(final String text) { ConstraintConnectiveDescr constraint = null; - try { DRLLexer lexer = new DRLLexer(CharStreams.fromString(text)); CommonTokenStream input = new CommonTokenStream(lexer); - helper = new ParserHelper(input, null, languageLevel); + helper = new ParserHelper(input, languageLevel); DRLExpressions parser = new DRL6Expressions(input, 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(); @@ -59,9 +66,6 @@ public ConstraintConnectiveDescr parse(final String text) { constraint = ConstraintConnectiveDescr.newAnd(); constraint.addOrMerge(expr); } - } catch (RecognitionException e) { - helper.reportError(e); - } return constraint; } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DroolsParserExceptionFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DroolsParserExceptionFactory.java index 622ea8ae3b8..c40636256f8 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DroolsParserExceptionFactory.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DroolsParserExceptionFactory.java @@ -20,13 +20,12 @@ import java.io.PrintWriter; import java.io.StringWriter; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.antlr.v4.runtime.FailedPredicateException; +import org.antlr.v4.runtime.InputMismatchException; import org.antlr.v4.runtime.NoViableAltException; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Token; @@ -42,8 +41,6 @@ * @see DroolsParserException */ public class DroolsParserExceptionFactory { - public final static String NO_VIABLE_ALT_MESSAGE = "Line %1$d:%2$d no viable alternative at input '%3$s'%4$s"; - public final static String FAILED_PREDICATE_MESSAGE = "Line %1$d:%2$d rule '%3$s' failed predicate: {%4$s}?%5$s"; public final static String TRAILING_SEMI_COLON_NOT_ALLOWED_MESSAGE = "Line %1$d:%2$d trailing semi-colon not allowed%3$s"; public final static String PARSER_LOCATION_MESSAGE_COMPLETE = " in %1$s %2$s"; public final static String PARSER_LOCATION_MESSAGE_PART = " in %1$s"; @@ -103,58 +100,45 @@ public DroolsParserException createTrailingSemicolonException( int line, /** * This method creates a DroolsParserException full of information. * - * @param e - * original exception + * @param offendingSymbol + * @param line + * @param charPositionInLine + * @param e original exception * @return DroolsParserException filled. */ - public DroolsParserException createDroolsException( RecognitionException e ) { - List codeAndMessage = createErrorMessage( e ); - return new DroolsParserException( codeAndMessage.get( 1 ), - codeAndMessage - .get( 0 ), - // TODO verify this is correct - e.getOffendingToken().getLine(), - e.getOffendingToken().getCharPositionInLine(), - e.getOffendingToken().getStartIndex(), + public DroolsParserException createDroolsException(Object offendingSymbol, int line, int charPositionInLine, String message, RecognitionException e ) { + return new DroolsParserException( determineErrorCode( e ), + String.format("Line %d:%d %s", line, charPositionInLine, message), + line, + charPositionInLine, + determineStartingIndex(offendingSymbol), e ); } + private int determineStartingIndex(Object offendingSymbol) { + if (offendingSymbol instanceof Token) { + return ((Token) offendingSymbol).getStartIndex(); + } + return -1; + } + /** - * This will take a RecognitionException, and create a sensible error - * message out of it + * Determines the error code based on a specific subtype of RecognitionException. */ - private List createErrorMessage( RecognitionException e ) { - List codeAndMessage = new ArrayList<>( 2 ); - String message; + private String determineErrorCode( RecognitionException e ) { + if (e == null) { + return "ERR 109"; + } + if ( e instanceof InputMismatchException) { + return "ERR 102"; + } if ( e instanceof NoViableAltException ) { - // NoViableAltException nvae = (NoViableAltException) e; - message = String.format( - NO_VIABLE_ALT_MESSAGE, - // TODO verify this is correct - e.getOffendingToken().getLine(), - e.getOffendingToken().getCharPositionInLine(), - getBetterToken( e.getOffendingToken() ), - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 101" ); - } else if ( e instanceof FailedPredicateException ) { - FailedPredicateException fpe = (FailedPredicateException) e; - String ruleName = fpe.getRecognizer().getRuleNames()[fpe.getRuleIndex()]; - message = String.format( - FAILED_PREDICATE_MESSAGE, - // TODO verify this is correct - e.getOffendingToken().getLine(), - e.getOffendingToken().getCharPositionInLine(), - ruleName, - fpe.getPredicate(), - formatParserLocation() ); - codeAndMessage.add( message ); - codeAndMessage.add( "ERR 103" ); + return "ERR 101"; } - if ( codeAndMessage.get( 0 ).length() == 0 ) { - codeAndMessage.add( "?????" ); + if ( e instanceof FailedPredicateException ) { + return "ERR 103"; } - return codeAndMessage; + throw new IllegalArgumentException("Unexpected exception type: " + e); } public DroolsParserException createDroolsException( Exception e, diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java index 1d533e3c51f..504233edee7 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java @@ -120,11 +120,9 @@ public class ParserHelper { private final LanguageLevelOption languageLevel; public ParserHelper(TokenStream input, - RecognizerSharedState state, LanguageLevelOption languageLevel) { this.errorMessageFactory = new DroolsParserExceptionFactory( paraphrases, languageLevel ); this.input = input; - this.state = state; this.languageLevel = languageLevel; } @@ -360,15 +358,8 @@ public boolean validateAttribute( int index ) { DroolsSoftKeywords.DIRECT ); } - public void reportError( RecognitionException ex ) { - // if we've already reported an error and have not matched a token - // yet successfully, don't report any errors. - if ( state.errorRecovery ) { - return; - } - state.errorRecovery = true; - - errors.add( errorMessageFactory.createDroolsException( ex ) ); + public void reportError(Object offendingSymbol, int line, int charPositionInLine, String message, RecognitionException ex ) { + errors.add( errorMessageFactory.createDroolsException( offendingSymbol, line, charPositionInLine, message, ex ) ); } public void reportError( Exception e ) { From 6b7f1de1c5cd9197597df9af77455712e134b943 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 18 Mar 2024 10:23:05 +0900 Subject: [PATCH 066/141] [incubator-kie-drools#5776] [new-parser] failed to parse when a method name is a drl keyword (#5783) --- .../drl/parser/antlr4/DRLExprParserTest.java | 27 +++++++ .../drl/parser/antlr4/MiscDRLParserTest.java | 15 ++++ .../drl/parser/antlr4/DRL6Expressions.g4 | 78 ++++++++++++++++++- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 13 +++- 4 files changed, 126 insertions(+), 7 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 6fc7eecc6e6..c404d2e0ef0 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 @@ -212,6 +212,33 @@ public void testDoubleBinding() throws Exception { assertThat(bind.getExpression()).isEqualTo("y[z].foo"); } + @Test + public void testDrlKeywordMethodCall() throws Exception { + String source = "x.contains( 1, a )"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + AtomicExprDescr descr = (AtomicExprDescr) result.getDescrs().get( 0 ); + assertThat(descr.getExpression()).isEqualTo("x.contains( 1, a )"); + } + + @Test + public void testDrlKeywordMethodCallBinding() throws Exception { + String source = "$x : x.contains( 1, a )"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(1); + + BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("x.contains( 1, a )"); + } + @Test public void testDeepBinding() throws Exception { String source = "($a : a > $b : b[10].prop || 10 != 20) && $x : someMethod(10) == 20"; 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 5c82ed73ff2..0b394bbdd3b 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 @@ -3639,4 +3639,19 @@ void nullSafeDereferencingMethodCall() { ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("address!.city!.startsWith(\"M\")"); } + + @Test + void nullSafeDereferencingMethodCallBindVariable() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person( $containsL : address!.city.contains(\"L\") )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("$containsL : address!.city.contains(\"L\")"); + } } 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/DRL6Expressions.g4 index 51ea965a0f2..c8a34b50764 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/DRL6Expressions.g4 @@ -162,6 +162,76 @@ typeArgument | QUESTION ((extends_key | super_key) type)? ; +// matches any drl keywords +drlKeywords returns [Token token] + : DRL_UNIT + | DRL_FUNCTION + | DRL_GLOBAL + | DRL_DECLARE + | DRL_RULE + | DRL_QUERY + | DRL_WHEN + | DRL_THEN + | DRL_END + | DRL_AND + | DRL_OR + | DRL_EXISTS + | DRL_NOT + | DRL_IN + | DRL_FROM + | DRL_MATCHES + | DRL_MEMBEROF + | DRL_CONTAINS + | DRL_EXCLUDES + | DRL_SOUNDSLIKE + | DRL_STR + | DRL_ACCUMULATE + | DRL_ACC + | DRL_INIT + | DRL_ACTION + | DRL_REVERSE + | DRL_RESULT + | DRL_ENTRY_POINT + | DRL_EVAL + | DRL_SALIENCE + | DRL_ENABLED + | DRL_NO_LOOP + | DRL_AUTO_FOCUS + | DRL_LOCK_ON_ACTIVE + | DRL_REFRACT + | DRL_DIRECT + | DRL_AGENDA_GROUP + | DRL_ACTIVATION_GROUP + | DRL_RULEFLOW_GROUP + | DRL_DATE_EFFECTIVE + | DRL_DATE_EXPIRES + | DRL_DIALECT + | DRL_CALENDARS + | DRL_TIMER + | DRL_DURATION + ; + +// matches any identifiers including acceptable java keywords (defined in JavaParser.g4) and drl keywords +drlIdentifier returns [Token token] + : drlKeywords + | IDENTIFIER + | MODULE + | OPEN + | REQUIRES + | EXPORTS + | OPENS + | TO + | USES + | PROVIDES + | WITH + | TRANSITIVE + | YIELD + | SEALED + | PERMITS + | RECORD + | VAR + ; + // -------------------------------------------------------- // EXPRESSIONS // -------------------------------------------------------- @@ -608,18 +678,18 @@ primary returns [BaseDescr result] //| void_key DOT class_key | inlineMapExpression | inlineListExpression - | i1=IDENTIFIER { helper.emit($i1, DroolsEditorType.IDENTIFIER); } + | i1=drlIdentifier { helper.emit($i1.token, DroolsEditorType.IDENTIFIER); } ( - ( d=DOT i2=IDENTIFIER { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + ( d=DOT i2=drlIdentifier { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($i2.token, DroolsEditorType.IDENTIFIER); } ) | ( d=(DOT|NULL_SAFE_DOT) LPAREN { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($LPAREN, DroolsEditorType.SYMBOL); } expression (COMMA { helper.emit($COMMA, DroolsEditorType.SYMBOL); } expression)* RPAREN { helper.emit($RPAREN, DroolsEditorType.SYMBOL); } ) | - ( h=HASH i2=IDENTIFIER { helper.emit($h, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + ( h=HASH i2=drlIdentifier { helper.emit($h, DroolsEditorType.SYMBOL); helper.emit($i2.token, DroolsEditorType.IDENTIFIER); } ) | - ( n=NULL_SAFE_DOT i2=IDENTIFIER { helper.emit($n, DroolsEditorType.SYMBOL); helper.emit($i2, DroolsEditorType.IDENTIFIER); } ) + ( n=NULL_SAFE_DOT i2=drlIdentifier { helper.emit($n, DroolsEditorType.SYMBOL); helper.emit($i2.token, DroolsEditorType.IDENTIFIER); } ) )* (identifierSuffix)? ; 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/DRLParser.g4 index 6a98fab11ee..c358c663094 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/DRLParser.g4 @@ -247,16 +247,16 @@ drlExpression | drlExpression bop=DOT ( drlIdentifier - | methodCall + | drlMethodCall | THIS | NEW nonWildcardTypeArguments? innerCreator | SUPER superSuffix | explicitGenericInvocation ) - | drlExpression NULL_SAFE_DOT ( drlIdentifier | methodCall ) + | drlExpression NULL_SAFE_DOT ( drlIdentifier | drlMethodCall ) | drlExpression LBRACK drlExpression RBRACK | DRL_EVAL LPAREN conditionalOrExpression RPAREN - | methodCall + | drlMethodCall | NEW drlCreator | LPAREN annotation* typeType (BITAND typeType)* RPAREN drlExpression | drlExpression postfix=(INC | DEC) @@ -286,6 +286,13 @@ drlExpression | classType COLONCOLON typeArguments? NEW ; +/* extending JavaParser methodCall in order to accept drl keywords as method name */ +drlMethodCall + : drlIdentifier LPAREN expressionList? RPAREN + | THIS LPAREN expressionList? RPAREN + | SUPER LPAREN expressionList? RPAREN + ; + temporalOperator : DRL_NOT? bop=(DRL_AFTER | DRL_BEFORE | DRL_COINCIDES | DRL_DURING | DRL_INCLUDES | DRL_FINISHES | DRL_FINISHED_BY | DRL_MEETS | DRL_MET_BY | DRL_OVERLAPS | DRL_OVERLAPPED_BY | DRL_STARTS | DRL_STARTED_BY) timeAmount? ; timeAmount : LBRACK (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL) (COMMA (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL))* RBRACK ; From e5a4df252e72130fbe62dfbf2b65689015d8867f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Mon, 18 Mar 2024 11:08:06 +0100 Subject: [PATCH 067/141] Primary rule should accept `this` keyword (#5791) As in `String(this == "x")`. --- .../java/org/drools/drl/parser/antlr4/DRLExprParserTest.java | 1 + .../main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) 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 c404d2e0ef0..e32f287beb2 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 @@ -317,6 +317,7 @@ public void testNestedExpression() throws Exception { "(long) l", "(float) f", "(double) d", + "this", "this()", "Object[][].class.getName()", "newArrayList()" 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/DRL6Expressions.g4 index c8a34b50764..d85859d3bd5 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/DRL6Expressions.g4 @@ -671,7 +671,7 @@ primary returns [BaseDescr result] : expr=parExpression { if( buildDescr ) { $result = $expr.result; } } | nonWildcardTypeArguments (explicitGenericInvocationSuffix | this_key arguments) | literal { if( buildDescr ) { $result = new AtomicExprDescr( $literal.text, true ); } } - //| this_key ({!helper.validateSpecialID(2)}? DOT IDENTIFIER)* ({helper.validateIdentifierSufix()}? identifierSuffix)? + | this_key (DOT drlIdentifier)* identifierSuffix? | super_key superSuffix | new_key creator | primitiveType (LBRACK RBRACK)* DOT class_key From 2c374bc8351a4e7565c3c7e5174106bec4b8fb28 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 19 Mar 2024 11:39:52 +0900 Subject: [PATCH 068/141] [incubator-kie-drools#5706] Grouped accessors for nested objects broken (#5790) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools#5706] Grouped accessors for nested objects broken * Update drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java Co-authored-by: Jiří Locker * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker --------- Co-authored-by: Jiří Locker --- .../drl/parser/antlr4/MiscDRLParserTest.java | 34 +++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- ...tils.java => Antlr4ParserStringUtils.java} | 8 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 47 +++++++++--- .../drools/drl/parser/lang/DRL6Parser.java | 41 +--------- .../drl/parser/util/ParserStringUtils.java | 74 +++++++++++++++++++ .../parser/util/ParserStringUtilsTest.java | 66 +++++++++++++++++ 7 files changed, 220 insertions(+), 52 deletions(-) rename drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/{ParserStringUtils.java => Antlr4ParserStringUtils.java} (93%) create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java create mode 100644 drools-drl/drools-drl-parser/src/test/java/org/drools/drl/parser/util/ParserStringUtilsTest.java 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 0b394bbdd3b..9e2d4f9d5b5 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 @@ -3654,4 +3654,38 @@ void nullSafeDereferencingMethodCallBindVariable() { ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("$containsL : address!.city.contains(\"L\")"); } + + @Test + void groupedConstraints() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person( address.(city.startsWith(\"I\") && city.length() == 5 ) )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + assertThat(constraintDescr.toString()) + .as("prefix should be appended to each element") + .isEqualToIgnoringWhitespace("address.city.startsWith(\"I\") && address.city.length() == 5"); + } + + @Test + void groupedConstraintsWithNullSafeDereferencing() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person( address!.(city!.startsWith(\"I\") && city!.length() == 5 ) )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + assertThat(constraintDescr.toString()) + .as("prefix should be appended to each element") + .isEqualToIgnoringWhitespace("address!.city!.startsWith(\"I\") && address!.city!.length() == 5"); + } } 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/DRLParser.g4 index c358c663094..7523592f985 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/DRLParser.g4 @@ -128,7 +128,7 @@ lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? positionalConstraints : constraint (COMMA constraint)* SEMI ; constraints : constraint (COMMA constraint)* ; constraint : ( nestedConstraint | conditionalOrExpression ) ; -nestedConstraint : ( IDENTIFIER ( DOT | HASH ) )* IDENTIFIER DOT LPAREN constraints RPAREN ; +nestedConstraint : ( IDENTIFIER ( DOT | NULL_SAFE_DOT | HASH ) )* IDENTIFIER (DOT | NULL_SAFE_DOT ) LPAREN constraints RPAREN ; // TBD: constraint parsing could be delegated to DRL6ExpressionParser conditionalOrExpression : left=conditionalAndExpression (OR right=conditionalAndExpression)* ; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java similarity index 93% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserStringUtils.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java index 22ea2a7fa65..8c874cc3c1b 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserStringUtils.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java @@ -23,12 +23,12 @@ import org.antlr.v4.runtime.misc.Interval; /** - * Collection of String utilities used by DRLParser. - * This may be merged in drools-util + * Collection of String utilities used by antlr4 DRLParser. */ -public class ParserStringUtils { +public class Antlr4ParserStringUtils { - private ParserStringUtils() { + private Antlr4ParserStringUtils() { + // Private constructor to prevent instantiation. } /** 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 c37284fa516..487a09c3eac 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,6 +23,7 @@ import java.util.stream.Collectors; import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.RuleNode; @@ -59,10 +60,11 @@ import org.drools.drl.ast.descr.WindowDeclarationDescr; import static org.drools.drl.parser.antlr4.DRLParserHelper.getTextWithoutErrorNode; -import static org.drools.drl.parser.antlr4.ParserStringUtils.getTextPreservingWhitespace; -import static org.drools.drl.parser.antlr4.ParserStringUtils.getTokenTextPreservingWhitespace; -import static org.drools.drl.parser.antlr4.ParserStringUtils.safeStripStringDelimiters; -import static org.drools.drl.parser.antlr4.ParserStringUtils.trimThen; +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.Antlr4ParserStringUtils.safeStripStringDelimiters; +import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.trimThen; +import static org.drools.drl.parser.util.ParserStringUtils.appendPrefix; import static org.drools.util.StringUtils.unescapeJava; /** @@ -533,7 +535,7 @@ public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { behaviorDescr.setType(ctx.DRL_WINDOW().getText()); behaviorDescr.setSubType(ctx.IDENTIFIER().getText()); List drlExpressionContexts = ctx.expressionList().drlExpression(); - List parameters = drlExpressionContexts.stream().map(ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); + List parameters = drlExpressionContexts.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); behaviorDescr.setParameters(parameters); return behaviorDescr; } @@ -620,17 +622,42 @@ private void populateExprConstraintDescrList(ParserRuleContext ctx, List visitConstraint(DRLParser.ConstraintContext ctx) { + List descrList = new ArrayList<>(); + if (ctx.nestedConstraint() != null) { + // nested constraint requires special string manipulation + return visitNestedConstraint(ctx.nestedConstraint()); + } + // get a simple constraint as String String constraint = visitConstraintChildren(ctx); if (!constraint.isEmpty()) { ExprConstraintDescr constraintDescr = new ExprConstraintDescr(constraint); constraintDescr.setType(ExprConstraintDescr.Type.NAMED); - return constraintDescr; + descrList.add(constraintDescr); + return descrList; } - return null; + return descrList; + } + + /** + * Append a prefix to nested constraints. + * For example, + * address.(city.startsWith("I"), city.length() == 5) + * becomes + * address.city.startsWith("I"), address.city.length() == 5 + */ + @Override + public List visitNestedConstraint(DRLParser.NestedConstraintContext ctx) { + Token prefixStartToken = ctx.start; + Token prefixEndToken = tokenStream.get(ctx.LPAREN().getSymbol().getTokenIndex() - 1); + String prefix = tokenStream.getText(prefixStartToken, prefixEndToken); + List exprConstraintDescr = visitConstraints(ctx.constraints()); + exprConstraintDescr.forEach(d -> d.setText(appendPrefix(prefix, d.getText()))); + return exprConstraintDescr; } @Override @@ -797,6 +824,8 @@ private List visitDescrChildren(RuleNode node) { Object childResult = c.accept(this); if (childResult instanceof BaseDescr) { aggregator.add((BaseDescr) childResult); + } else if (childResult instanceof List) { + aggregator.addAll((List) childResult); } } return aggregator; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java index ebfec99223d..f23b7063e2c 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java @@ -85,6 +85,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.drools.drl.parser.util.ParserStringUtils.appendPrefix; + public class DRL6Parser extends AbstractDRLParser implements DRLParser { private static final Logger LOG = LoggerFactory.getLogger(DRL6Parser.class); @@ -3778,44 +3780,7 @@ private void constraint(PatternDescrBuilder pattern, private String toExpression(String prefix, int first, int last) { String expr = input.toString(first, last); - if (prefix.length() == 0) { - return expr; - } - StringBuilder sb = new StringBuilder(); - toOrExpression(sb, prefix, expr); - return sb.toString(); - } - - private void toOrExpression(StringBuilder sb, String prefix, String expr) { - int start = 0; - int end = expr.indexOf("||"); - do { - if (start > 0) { - sb.append(" || "); - } - toAndExpression(sb, prefix, end > 0 ? expr.substring(start, end) : expr.substring(start)); - start = end + 2; - end = expr.indexOf("||", start); - } while (start > 1); - } - - private void toAndExpression(StringBuilder sb, String prefix, String expr) { - int start = 0; - int end = expr.indexOf("&&"); - do { - if (start > 0) { - sb.append(" && "); - } - sb.append(toExpression(prefix, end > 0 ? expr.substring(start, end) : expr.substring(start))); - start = end + 2; - end = expr.indexOf("&&", start); - } while (start > 1); - } - - private String toExpression(String prefix, String expr) { - expr = expr.trim(); - int colonPos = expr.indexOf(":"); - return colonPos < 0 ? prefix + expr : expr.substring(0, colonPos + 1) + " " + prefix + expr.substring(colonPos + 1).trim(); + return appendPrefix(prefix, expr); } private boolean speculateNestedConstraint() throws RecognitionException { diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java new file mode 100644 index 00000000000..bca3dca91f9 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java @@ -0,0 +1,74 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.util; + +/** + * String utilities used by DRL Parser. Not dependent on ANTLR version. + */ +public class ParserStringUtils { + + private ParserStringUtils() { + // Private constructor to prevent instantiation. + } + + /** + * Append a prefix to a grouped constraint. + * Even if the constraint contains || and/or &&, append the prefix to each element. + */ + public static String appendPrefix(String prefix, String expr) { + if (prefix.length() == 0) { + return expr; + } + StringBuilder sb = new StringBuilder(); + appendPrefixToOrExpression(sb, prefix, expr); + return sb.toString(); + } + + private static void appendPrefixToOrExpression(StringBuilder sb, String prefix, String expr) { + int start = 0; + int end = expr.indexOf("||"); + do { + if (start > 0) { + sb.append(" || "); + } + appendPrefixToAndExpression(sb, prefix, end > 0 ? expr.substring(start, end) : expr.substring(start)); + start = end + 2; + end = expr.indexOf("||", start); + } while (start > 1); + } + + private static void appendPrefixToAndExpression(StringBuilder sb, String prefix, String expr) { + int start = 0; + int end = expr.indexOf("&&"); + do { + if (start > 0) { + sb.append(" && "); + } + sb.append(appendPrefixToExpression(prefix, end > 0 ? expr.substring(start, end) : expr.substring(start))); + start = end + 2; + end = expr.indexOf("&&", start); + } while (start > 1); + } + + private static String appendPrefixToExpression(String prefix, String expr) { + expr = expr.trim(); + int colonPos = expr.indexOf(":"); + return colonPos < 0 ? prefix + expr : expr.substring(0, colonPos + 1) + " " + prefix + expr.substring(colonPos + 1).trim(); + } +} diff --git a/drools-drl/drools-drl-parser/src/test/java/org/drools/drl/parser/util/ParserStringUtilsTest.java b/drools-drl/drools-drl-parser/src/test/java/org/drools/drl/parser/util/ParserStringUtilsTest.java new file mode 100644 index 00000000000..9ef0e6edd5a --- /dev/null +++ b/drools-drl/drools-drl-parser/src/test/java/org/drools/drl/parser/util/ParserStringUtilsTest.java @@ -0,0 +1,66 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.util; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ParserStringUtilsTest { + + @Test + public void appendPrefix() { + String prefix = "prefix."; + String expr = "a == 1"; + String result = ParserStringUtils.appendPrefix(prefix, expr); + assertThat(result).isEqualToIgnoringWhitespace("prefix.a == 1"); + } + + @Test + public void appendPrefixWithAnd() { + String prefix = "prefix."; + String expr = "a == 1 && b.equals(\"foo\")"; + String result = ParserStringUtils.appendPrefix(prefix, expr); + assertThat(result).isEqualToIgnoringWhitespace("prefix.a == 1 && prefix.b.equals(\"foo\")"); + } + + @Test + public void appendPrefixWithOr() { + String prefix = "prefix."; + String expr = "a == 1 || b.equals(\"foo\")"; + String result = ParserStringUtils.appendPrefix(prefix, expr); + assertThat(result).isEqualToIgnoringWhitespace("prefix.a == 1 || prefix.b.equals(\"foo\")"); + } + + @Test + public void appendPrefixWithANDOr() { + String prefix = "prefix."; + String expr = "a == 1 && b.equals(\"foo\") || c == 2 && d.equals(\"bar\")"; + String result = ParserStringUtils.appendPrefix(prefix, expr); + assertThat(result).isEqualToIgnoringWhitespace("prefix.a == 1 && prefix.b.equals(\"foo\") || prefix.c == 2 && prefix.d.equals(\"bar\")"); + } + + @Test + public void appendPrefixWithBindingVariable() { + String prefix = "prefix."; + String expr = "$a : a == 1 && $b : b.equals(\"foo\")"; + String result = ParserStringUtils.appendPrefix(prefix, expr); + assertThat(result).isEqualToIgnoringWhitespace("$a : prefix.a == 1 && $b : prefix.b.equals(\"foo\")"); + } +} From 80f50b9720b82212ad58b8a1392faf049137d3d0 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 21 Mar 2024 17:21:28 +0900 Subject: [PATCH 069/141] [incubator-kie-drools#5709] [new-parser] Some rules do not fire in MultiKieBaseTest (#5794) --- .../java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java | 3 +++ .../main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java | 1 + 2 files changed, 4 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 9e2d4f9d5b5..77640d9df5f 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 @@ -780,6 +780,9 @@ void parse_simpleRuleWithBindings() throws Exception { assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getStartCharacter()).isEqualTo(803); + assertThat(rule.getEndCharacter()).isEqualTo(996); + assertThat(rule.getConsequenceLine()).isEqualTo(22); assertThat(rule.getConsequencePattern()).isEqualTo(2); 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 487a09c3eac..7dd6d8cfdba 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 @@ -270,6 +270,7 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { ruleDescr.setConsequence(trimThen(getTokenTextPreservingWhitespace(ctx.rhs(), tokenStream))); // RHS is just a text } + populateStartEnd(ruleDescr, ctx); return ruleDescr; } From c0e293057180a82b44b08ccbc5afd366202c75af Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 21 Mar 2024 17:23:22 +0900 Subject: [PATCH 070/141] =?UTF-8?q?[incubator-kie-drools#5708]=20[new-pars?= =?UTF-8?q?er]=20function=20definition=20causes=20a=E2=80=A6=20(#5793)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools#5708] [new-parser] function definition causes an error * - enhance getTextPreservingWhitespace to avoid string manipulation --- .../drl/parser/antlr4/MiscDRLParserTest.java | 48 +++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 58 ++++++++++++++++++- .../antlr4/Antlr4ParserStringUtils.java | 11 ++++ .../drl/parser/antlr4/DRLVisitorImpl.java | 4 +- 4 files changed, 117 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 77640d9df5f..1e70906d992 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 @@ -3691,4 +3691,52 @@ void groupedConstraintsWithNullSafeDereferencing() { .as("prefix should be appended to each element") .isEqualToIgnoringWhitespace("address!.city!.startsWith(\"I\") && address!.city!.length() == 5"); } + + @Test + public void functionWithStringLiteral() { + final String text = "function String star(String s) { return \"*\"; }"; + PackageDescr packageDescr = parser.parse(text); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + FunctionDescr function = packageDescr.getFunctions().get( 0 ); + + assertThat(function.getName()).isEqualTo("star"); + assertThat(function.getReturnType()).isEqualTo("String"); + assertThat(function.getParameterTypes().get(0)).isEqualTo("String"); + assertThat(function.getParameterNames().get(0)).isEqualTo("s"); + assertThat(function.getBody()).isEqualToIgnoringWhitespace( "return \"*\";"); + } + + @Test + public void functionWithStringLiteralAddition() { + final String text = "function String addStar(String s) { return s + \"*\"; }"; + PackageDescr packageDescr = parser.parse(text); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + FunctionDescr function = packageDescr.getFunctions().get( 0 ); + + assertThat(function.getName()).isEqualTo("addStar"); + assertThat(function.getReturnType()).isEqualTo("String"); + assertThat(function.getParameterTypes().get(0)).isEqualTo("String"); + assertThat(function.getParameterNames().get(0)).isEqualTo("s"); + assertThat(function.getBody()).isEqualToIgnoringWhitespace( "return s + \"*\";"); + } + + @Test + public void functionWithMultipleBlockStatements() { + final String text = "function String star(String s) {\n" + + " String result = s + \"*\";\n" + + " return result;\n" + + "}"; + PackageDescr packageDescr = parser.parse(text); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + FunctionDescr function = packageDescr.getFunctions().get( 0 ); + + assertThat(function.getName()).isEqualTo("star"); + assertThat(function.getReturnType()).isEqualTo("String"); + assertThat(function.getParameterTypes().get(0)).isEqualTo("String"); + assertThat(function.getParameterNames().get(0)).isEqualTo("s"); + assertThat(function.getBody()).isEqualToIgnoringWhitespace( "String result = s + \"*\"; return result;"); + } } 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/DRLParser.g4 index 7523592f985..7b347a69b81 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/DRLParser.g4 @@ -164,7 +164,7 @@ drlRelationalOperator | DRL_NOT? DRL_STR LBRACK IDENTIFIER RBRACK ; /* function := FUNCTION type? ID parameters(typed) chunk_{_} */ -functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters block ; +functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters drlBlock ; /* extending JavaParser qualifiedName */ @@ -380,7 +380,7 @@ fromAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) RPAREN (SEMI)? ; -blockStatements : blockStatement* ; +blockStatements : drlBlockStatement* ; /* accumulateFunction := label? ID parameters @@ -512,3 +512,57 @@ drlVariableInitializer drlArrayInitializer : LBRACE (drlVariableInitializer (COMMA drlVariableInitializer)* (COMMA)? )? RBRACE ; + +/* extending JavaParser block */ +drlBlock + : LBRACE drlBlockStatement* RBRACE + ; +/* extending JavaParser blockStatement */ +drlBlockStatement + : drlLocalVariableDeclaration SEMI + | drlStatement + | localTypeDeclaration + ; + +/* extending JavaParser statement */ +drlStatement + : blockLabel=drlBlock + | ASSERT drlExpression (COLON drlExpression)? SEMI + | IF parExpression drlStatement (ELSE drlStatement)? + | FOR LPAREN forControl RPAREN drlStatement + | WHILE parExpression drlStatement + | DO drlStatement WHILE parExpression SEMI + | TRY drlBlock (catchClause+ finallyBlock? | finallyBlock) + | TRY resourceSpecification drlBlock catchClause* finallyBlock? + | SWITCH parExpression LBRACE switchBlockStatementGroup* switchLabel* RBRACE + | SYNCHRONIZED parExpression drlBlock + | RETURN drlExpression? SEMI + | THROW drlExpression SEMI + | BREAK drlIdentifier? SEMI + | CONTINUE drlIdentifier? SEMI + | YIELD drlExpression SEMI // Java17 + | SEMI + | statementExpression=drlExpression SEMI + | switchExpression SEMI? // Java17 + | identifierLabel=drlIdentifier COLON drlStatement + ; + +/* extending JavaParser localVariableDeclaration */ +drlLocalVariableDeclaration + : variableModifier* (typeType drlVariableDeclarators | VAR drlIdentifier ASSIGN expression) + ; + +/* extending JavaParser variableDeclarators */ +drlVariableDeclarators + : drlVariableDeclarator (COMMA drlVariableDeclarator)* + ; + +/* extending JavaParser variableDeclarator */ +drlVariableDeclarator + : drlVariableDeclaratorId (ASSIGN drlVariableInitializer)? + ; + +/* extending JavaParser variableDeclaratorId */ +drlVariableDeclaratorId + : drlIdentifier (LBRACK RBRACK)* + ; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java index 8c874cc3c1b..2f200c6abff 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java @@ -18,6 +18,9 @@ */ package org.drools.drl.parser.antlr4; +import java.util.List; +import java.util.stream.Collectors; + import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.misc.Interval; @@ -59,6 +62,13 @@ public static String getTextPreservingWhitespace(ParserRuleContext ctx) { return ctx.start.getTokenSource().getInputStream().getText(interval); } + /** + * Get text from List of ParserRuleContext's CharStream without trimming whitespace + */ + public static String getTextPreservingWhitespace(List ctx) { + return ctx.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.joining()); + } + /** * Get text from ParserRuleContext's CharStream without trimming whitespace * tokenStream is required to get hidden channel token (e.g. whitespace). @@ -78,4 +88,5 @@ public static String trimThen(String rhs) { throw new DRLParserException("rhs has to start with 'then' : rhs = " + rhs); } } + } 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 7dd6d8cfdba..16e398f9465 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 @@ -59,11 +59,11 @@ import org.drools.drl.ast.descr.UnitDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; -import static org.drools.drl.parser.antlr4.DRLParserHelper.getTextWithoutErrorNode; 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.Antlr4ParserStringUtils.safeStripStringDelimiters; import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.trimThen; +import static org.drools.drl.parser.antlr4.DRLParserHelper.getTextWithoutErrorNode; import static org.drools.drl.parser.util.ParserStringUtils.appendPrefix; import static org.drools.util.StringUtils.unescapeJava; @@ -193,7 +193,7 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { functionDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); }); } - functionDescr.setBody(getTextPreservingWhitespace(ctx.block())); + functionDescr.setBody(getTextPreservingWhitespace(ctx.drlBlock().drlBlockStatement())); return functionDescr; } From 3370deff6b94b418347b6a2e90f42f795e1e3913 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Thu, 21 Mar 2024 19:09:41 +0100 Subject: [PATCH 071/141] [new-parser] Support LHS pattern annotations (#5797) * LHS patterns can have annotations * LHS pattern annotations can contain chunks --- .../drl/parser/antlr4/MiscDRLParserTest.java | 16 +++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 4 +-- .../antlr4/Antlr4ParserStringUtils.java | 13 --------- .../drl/parser/antlr4/DRLVisitorImpl.java | 8 ++++-- .../drools/drl/parser/lang/DRL6Parser.java | 27 ++----------------- .../drl/parser/util/ParserStringUtils.java | 25 +++++++++++++++++ 6 files changed, 51 insertions(+), 42 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 1e70906d992..ebc86082aa7 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 @@ -3739,4 +3739,20 @@ public void functionWithMultipleBlockStatements() { assertThat(function.getParameterNames().get(0)).isEqualTo("s"); assertThat(function.getBody()).isEqualToIgnoringWhitespace( "String result = s + \"*\"; return result;"); } + + @Test + void lhsPatternAnnotation() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person( name == \"Mario\" ) @watch(!*, age)\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + AnnotationDescr annotationDescr = patternDescr.getAnnotations().iterator().next(); + assertThat(annotationDescr.getName()).isEqualTo("watch"); + assertThat(annotationDescr.getSingleValueAsString()).isEqualTo("!*, age"); + } } 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/DRLParser.g4 index 7b347a69b81..a218c069b11 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/DRLParser.g4 @@ -124,7 +124,7 @@ lhsPattern : xpathPrimary (OVER patternFilter)? | ( QUESTION? qualifiedIdentifier LPAREN positionalConstraints? constraints? RPAREN (OVER patternFilter)? (FROM patternSource)? ) ; */ -lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN (DRL_OVER patternFilter)? (DRL_FROM patternSource)? ; +lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN drlAnnotation* (DRL_OVER patternFilter)? (DRL_FROM patternSource)? ; positionalConstraints : constraint (COMMA constraint)* SEMI ; constraints : constraint (COMMA constraint)* ; constraint : ( nestedConstraint | conditionalOrExpression ) ; @@ -459,7 +459,7 @@ type : (classOrInterfaceType | primitiveType) typeArguments? ( DOT IDENTIFIER ty drlArguments : LPAREN drlArgument (COMMA drlArgument)* RPAREN ; drlArgument : ( stringId | floatLiteral | BOOL_LITERAL | NULL_LITERAL ) ; -drlAnnotation : AT name=drlQualifiedName (LPAREN ( drlElementValuePairs | drlElementValue )? RPAREN)? ; +drlAnnotation : AT name=drlQualifiedName ((LPAREN ( drlElementValuePairs | drlElementValue )? RPAREN) | chunk)? ; drlElementValuePairs : drlElementValuePair (COMMA drlElementValuePair)* ; drlElementValuePair : key=drlIdentifier ASSIGN value=drlElementValue ; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java index 2f200c6abff..86e841cc128 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java @@ -34,19 +34,6 @@ private Antlr4ParserStringUtils() { // Private constructor to prevent instantiation. } - /** - * Strip string delimiters (e.g. "foo" -> foo) - */ - public static String safeStripStringDelimiters(String value) { - if (value != null) { - value = value.trim(); - if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { - value = value.substring(1, value.length() - 1); - } - } - return value; - } - /** * Get text from ParserRuleContext's CharStream without trimming whitespace */ 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 16e398f9465..42205cebc95 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 @@ -61,10 +61,11 @@ 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.Antlr4ParserStringUtils.safeStripStringDelimiters; import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.trimThen; import static org.drools.drl.parser.antlr4.DRLParserHelper.getTextWithoutErrorNode; import static org.drools.drl.parser.util.ParserStringUtils.appendPrefix; +import static org.drools.drl.parser.util.ParserStringUtils.safeStripDelimiters; +import static org.drools.drl.parser.util.ParserStringUtils.safeStripStringDelimiters; import static org.drools.util.StringUtils.unescapeJava; /** @@ -322,6 +323,8 @@ public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); if (ctx.drlElementValue() != null) { annotationDescr.setValue(getTextPreservingWhitespace(ctx.drlElementValue())); // single value + } else if (ctx.chunk() != null) { + annotationDescr.setValue(safeStripDelimiters(getTextPreservingWhitespace(ctx.chunk()), "(", ")")); } else if (ctx.drlElementValuePairs() != null) { visitDrlElementValuePairs(ctx.drlElementValuePairs(), annotationDescr); // multiple values } @@ -496,6 +499,7 @@ public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { patternSourceDescr.setResource(patternDescr.getResource()); patternDescr.setSource(patternSourceDescr); } + ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(patternDescr::addAnnotation); List constraintDescrList = visitConstraints(ctx.positionalConstraints(), ctx.constraints()); constraintDescrList.forEach(descr -> addToPatternDescr(patternDescr, descr)); return patternDescr; @@ -874,4 +878,4 @@ public ParseTree getNode() { private String visitConstraintChildren(ParserRuleContext ctx) { return getTokenTextPreservingWhitespace(ctx, tokenStream); } -} \ No newline at end of file +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java index f23b7063e2c..f2181a37b86 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java @@ -86,6 +86,8 @@ import org.slf4j.LoggerFactory; import static org.drools.drl.parser.util.ParserStringUtils.appendPrefix; +import static org.drools.drl.parser.util.ParserStringUtils.safeStripDelimiters; +import static org.drools.drl.parser.util.ParserStringUtils.safeStripStringDelimiters; public class DRL6Parser extends AbstractDRLParser implements DRLParser { @@ -5192,29 +5194,4 @@ public boolean mismatchIsMissingToken(TokenStream input, return false; } - private String safeStripDelimiters(String value, - String left, - String right) { - if (value != null) { - value = value.trim(); - if (value.length() >= left.length() + right.length() && - value.startsWith(left) && value.endsWith(right)) { - value = value.substring(left.length(), - value.length() - right.length()); - } - } - return value; - } - - private String safeStripStringDelimiters(String value) { - if (value != null) { - value = value.trim(); - if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { - value = value.substring(1, - value.length() - 1); - } - } - return value; - } - } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java index bca3dca91f9..b67e64dd17a 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java @@ -27,6 +27,31 @@ private ParserStringUtils() { // Private constructor to prevent instantiation. } + /** + * Strip string delimiters (e.g. "foo" -> foo) + */ + public static String safeStripStringDelimiters(String value) { + if (value != null) { + value = value.trim(); + if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { + value = value.substring(1, value.length() - 1); + } + } + return value; + } + + public static String safeStripDelimiters(String value, String left, String right) { + if (value != null) { + value = value.trim(); + if (value.length() >= left.length() + right.length() && + value.startsWith(left) && value.endsWith(right)) { + value = value.substring(left.length(), + value.length() - right.length()); + } + } + return value; + } + /** * Append a prefix to a grouped constraint. * Even if the constraint contains || and/or &&, append the prefix to each element. From 5f0f9df8d349061b3432db0a7aee72844166c972 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 22 Mar 2024 16:57:29 +0900 Subject: [PATCH 072/141] [incubator-kie-drools#5710] [new-parser] Unable to resolve method (from new) in a query (#5795) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 15 +++++++++++++++ .../drools/drl/parser/antlr4/DRLVisitorImpl.java | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) 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 ebc86082aa7..59dadb6598f 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 @@ -3755,4 +3755,19 @@ void lhsPatternAnnotation() { assertThat(annotationDescr.getName()).isEqualTo("watch"); assertThat(annotationDescr.getSingleValueAsString()).isEqualTo("!*, age"); } + + @Test + void fromNew() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person() from new Person(\"John\", 30)\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + FromDescr fromDescr = (FromDescr) patternDescr.getSource(); + assertThat(fromDescr.getDataSource().toString()).isEqualTo("new Person(\"John\", 30)"); + } } 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 42205cebc95..6efefc7e60b 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 @@ -548,7 +548,7 @@ public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { @Override public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { FromDescr fromDescr = new FromDescr(); - fromDescr.setDataSource(new MVELExprDescr(ctx.getText())); + fromDescr.setDataSource(new MVELExprDescr(getTextPreservingWhitespace(ctx))); return fromDescr; } From ac300e35db75b96d24c1eecc81212b0148d4b6dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Sat, 23 Mar 2024 15:25:45 +0100 Subject: [PATCH 073/141] Enable time literal (#5800) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 23 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 1 + 2 files changed, 24 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 59dadb6598f..b7dd6462690 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 @@ -3749,9 +3749,12 @@ void lhsPatternAnnotation() { "then\n" + "end\n"; PackageDescr packageDescr = parser.parse(text); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr ruleDescr = packageDescr.getRules().get(0); PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); AnnotationDescr annotationDescr = patternDescr.getAnnotations().iterator().next(); + assertThat(annotationDescr.getName()).isEqualTo("watch"); assertThat(annotationDescr.getSingleValueAsString()).isEqualTo("!*, age"); } @@ -3770,4 +3773,24 @@ void fromNew() { FromDescr fromDescr = (FromDescr) patternDescr.getSource(); assertThat(fromDescr.getDataSource().toString()).isEqualTo("new Person(\"John\", 30)"); } + + @Test + public void expiresWithTimeLiteralValue() { + String text = "package org.drools\n" + + "declare StockFact\n" + + " @role( value = event )\n" + + " @expires( value = 2s, policy = TIME_SOFT )\n" + + "end"; + + PackageDescr packageDescr = parser.parse(text); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + AnnotationDescr annotationDescr = packageDescr + .getTypeDeclarations().get(0) + .getAnnotation("expires"); + + assertThat(annotationDescr.getSingleValueAsString()).isEqualTo("2s"); + assertThat(annotationDescr.getValueAsString("value")).isEqualTo("2s"); + assertThat(annotationDescr.getValueAsString("policy")).isEqualTo("TIME_SOFT"); + } } 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/DRLParser.g4 index a218c069b11..fab8ee8fac0 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/DRLParser.g4 @@ -321,6 +321,7 @@ drlLiteral | BOOL_LITERAL | NULL_LITERAL | TEXT_BLOCK // Java17 + | TIME_INTERVAL ; inlineListExpression From 51bb4f28f869fa2df32c19841c74f47aa3982e6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Mon, 25 Mar 2024 03:51:10 +0100 Subject: [PATCH 074/141] Improve the chunk rule not to include parentheses (#5801) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 19 +++++++++++++- .../parser/antlr4/rule_timer_attribute.drl | 26 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 6 ++--- .../drl/parser/antlr4/DRLVisitorImpl.java | 6 ++--- 4 files changed, 50 insertions(+), 7 deletions(-) create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_timer_attribute.drl 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 b7dd6462690..1ae6522da09 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 @@ -1907,6 +1907,24 @@ public void parse_Calendars2() throws Exception { assertThat(at.getValue()).isEqualTo("true"); } + @Test + public void parse_Timer() throws Exception { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile("rule_timer_attribute.drl" ); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs.size()).isEqualTo(2); + + AttributeDescr at = (AttributeDescr) attrs.get( "timer" ); + assertThat(at.getName()).isEqualTo("timer"); + assertThat(at.getValue()).isEqualTo("int: 0 1; start=1_000_000, repeat-limit=0"); + + at = (AttributeDescr) attrs.get( "lock-on-active" ); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + @Disabled("Priority : Low | Not written in docs nor other unit tests. Drop the support?") @Test public void parse_Attributes_alternateSyntax() throws Exception { @@ -3157,7 +3175,6 @@ public void parse_FromWithTernaryFollowedByQuery() throws Exception { } - @Disabled("Priority : Low | Implement multi-value annotation. Not written in docs") @Test public void parse_MultiValueAnnotationsBackwardCompatibility() throws Exception { // multiple values with no keys are parsed as a single value diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_timer_attribute.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_timer_attribute.drl new file mode 100644 index 00000000000..fe0377e25f0 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_timer_attribute.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + timer (int: 0 1; start=1_000_000, repeat-limit=0) + lock-on-active true + when + Foo() + then + bar(); +end 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/DRLParser.g4 index fab8ee8fac0..c7596d01443 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/DRLParser.g4 @@ -460,7 +460,7 @@ type : (classOrInterfaceType | primitiveType) typeArguments? ( DOT IDENTIFIER ty drlArguments : LPAREN drlArgument (COMMA drlArgument)* RPAREN ; drlArgument : ( stringId | floatLiteral | BOOL_LITERAL | NULL_LITERAL ) ; -drlAnnotation : AT name=drlQualifiedName ((LPAREN ( drlElementValuePairs | drlElementValue )? RPAREN) | chunk)? ; +drlAnnotation : AT name=drlQualifiedName (LPAREN ( drlElementValuePairs | drlElementValue | chunk )? RPAREN)? ; drlElementValuePairs : drlElementValuePair (COMMA drlElementValuePair)* ; drlElementValuePair : key=drlIdentifier ASSIGN value=drlElementValue ; @@ -475,11 +475,11 @@ attribute : name=( 'salience' | 'enabled' ) conditionalOrExpression #expressionA | name=( 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOL_LITERAL? #booleanAttribute | name=( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) DRL_STRING_LITERAL #stringAttribute | name='calendars' DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* #stringListAttribute - | name='timer' ( DECIMAL_LITERAL | chunk ) #intOrChunkAttribute + | name='timer' ( DECIMAL_LITERAL | LPAREN chunk RPAREN ) #intOrChunkAttribute | name='duration' ( DECIMAL_LITERAL | TIME_INTERVAL | LPAREN TIME_INTERVAL RPAREN ) #durationAttribute ; -chunk : LPAREN .+? RPAREN; +chunk : .+?; assignmentOperator : ASSIGN | ADD_ASSIGN 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 6efefc7e60b..0de2de1239e 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 @@ -64,7 +64,6 @@ import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.trimThen; import static org.drools.drl.parser.antlr4.DRLParserHelper.getTextWithoutErrorNode; import static org.drools.drl.parser.util.ParserStringUtils.appendPrefix; -import static org.drools.drl.parser.util.ParserStringUtils.safeStripDelimiters; import static org.drools.drl.parser.util.ParserStringUtils.safeStripStringDelimiters; import static org.drools.util.StringUtils.unescapeJava; @@ -323,10 +322,11 @@ public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); if (ctx.drlElementValue() != null) { annotationDescr.setValue(getTextPreservingWhitespace(ctx.drlElementValue())); // single value - } else if (ctx.chunk() != null) { - annotationDescr.setValue(safeStripDelimiters(getTextPreservingWhitespace(ctx.chunk()), "(", ")")); } else if (ctx.drlElementValuePairs() != null) { visitDrlElementValuePairs(ctx.drlElementValuePairs(), annotationDescr); // multiple values + } else if (ctx.chunk() != null) { + // A chunk that is neither a single value nor a list of key-value pairs. For example `!*, age` in `@watch(!*, age)`. + annotationDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); } return annotationDescr; } From ce2e24f0837ac61ab9bac95f623c56f8a398b97b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Mon, 25 Mar 2024 12:12:24 +0100 Subject: [PATCH 075/141] Fix window reference (#5802) --- .../org/drools/drl/parser/antlr4/MiscDRLParserTest.java | 1 - .../main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 | 6 +++++- .../java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java | 6 ++++++ 3 files changed, 11 insertions(+), 2 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 1ae6522da09..f4418f1bef0 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 @@ -3391,7 +3391,6 @@ public void parse_WindowDeclaration() throws Exception { assertThat(bd.getParameters().get(1)).isEqualTo("$s.symbol"); } - @Disabled("Priority : Mid | Implement using declared window. Not written in docs, but unit tests found.") @Test public void parse_WindowUsage() throws Exception { final String text = "package org.drools\n" + 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/DRLParser.g4 index c7596d01443..34ebacd4da1 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/DRLParser.g4 @@ -67,7 +67,7 @@ entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* ; // windowDeclaration := WINDOW ID annotation* lhsPatternBind END -windowDeclaration : DRL_WINDOW name=stringId drlAnnotation* lhsPatternBind ; +windowDeclaration : DRL_WINDOW name=IDENTIFIER drlAnnotation* lhsPatternBind ; // field := label fieldType (EQUALS_ASSIGN conditionalExpression)? annotation* SEMICOLON? @@ -361,6 +361,7 @@ patternFilter : DRL_WINDOW COLON IDENTIFIER LPAREN expressionList RPAREN ; patternSource : fromAccumulate | fromCollect | fromEntryPoint + | fromWindow | fromExpression ; @@ -394,6 +395,9 @@ fromCollect : DRL_COLLECT LPAREN lhsPatternBind RPAREN ; fromEntryPoint : DRL_ENTRY_POINT stringId ; +// fromWindow := WINDOW ID +fromWindow : DRL_WINDOW IDENTIFIER ; + /* lhsExists := EXISTS ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or 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 0de2de1239e..9ab53768f72 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 @@ -58,6 +58,7 @@ import org.drools.drl.ast.descr.TypeFieldDescr; import org.drools.drl.ast.descr.UnitDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl.ast.descr.WindowReferenceDescr; import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.getTextPreservingWhitespace; import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.getTokenTextPreservingWhitespace; @@ -591,6 +592,11 @@ public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) return new EntryPointDescr(safeStripStringDelimiters(ctx.stringId().getText())); } + @Override + public WindowReferenceDescr visitFromWindow(DRLParser.FromWindowContext ctx) { + return new WindowReferenceDescr(ctx.IDENTIFIER().getText()); + } + /** * Collect constraints in a Pattern */ From 9affb56a300ad58536c10b36e897037c283192f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Tue, 26 Mar 2024 11:26:15 +0100 Subject: [PATCH 076/141] Populate AST descriptors with line numbers (#5804) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 9 ++-- .../drl/parser/antlr4/DRLVisitorImpl.java | 41 ++++++++++++++++++- 2 files changed, 42 insertions(+), 8 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 f4418f1bef0..53eda685add 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 @@ -864,7 +864,6 @@ void parse_multipleRestrictionsConstraint() throws Exception { // Failing tests are annotated with @Disabled. We can fix issues one by one //------------------------------------------------------------------------- - @Disabled("Priority : Mid | implement Descr lineNumber") @Test public void parse_LineNumberInAST() throws Exception { // also see testSimpleExpander to see how this works with an expander @@ -1687,7 +1686,6 @@ public void parse_NotWithConstraint() throws Exception { assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type == $likes"); } - @Disabled("Priority : Mid | Implement Descr lineNumber") @Test public void parse_Functions() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -1703,7 +1701,7 @@ public void parse_Functions() throws Exception { assertThat(func.getReturnType()).isEqualTo("String"); assertThat(func.getParameterNames().size()).isEqualTo(2); assertThat(func.getParameterTypes().size()).isEqualTo(2); - assertThat(func.getLine()).isEqualTo(19); + assertThat(func.getLine()).isEqualTo(21); assertThat(func.getColumn()).isEqualTo(0); assertThat(func.getParameterTypes().get(0)).isEqualTo("String"); @@ -2070,15 +2068,14 @@ public void parse_EvalWithNewline() throws Exception { assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); } - @Disabled("Priority : Mid | implement Descr lineNumber") @Test public void parse_EndPosition() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "test_EndPosition.drl" ); final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(col.getLine()).isEqualTo(21); - assertThat(col.getEndLine()).isEqualTo(23); + assertThat(col.getLine()).isEqualTo(23); + assertThat(col.getEndLine()).isEqualTo(25); } @Test 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 9ab53768f72..8fa0be743df 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 @@ -93,6 +93,7 @@ public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { } List descrList = visitDescrChildren(ctx); applyChildrenDescrs(packageDescr, descrList); + populateStartEnd(packageDescr, ctx); return packageDescr; } @@ -139,7 +140,9 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc @Override public UnitDescr visitUnitdef(DRLParser.UnitdefContext ctx) { - return new UnitDescr(ctx.name.getText()); + UnitDescr unitDescr = new UnitDescr(ctx.name.getText()); + populateStartEnd(unitDescr, ctx); + return unitDescr; } @Override @@ -170,6 +173,7 @@ public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulate AccumulateImportDescr accumulateImportDescr = new AccumulateImportDescr(); accumulateImportDescr.setTarget(ctx.drlQualifiedName().getText()); accumulateImportDescr.setFunctionName(ctx.IDENTIFIER().getText()); + populateStartEnd(accumulateImportDescr, ctx); return accumulateImportDescr; } @@ -195,6 +199,7 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { }); } functionDescr.setBody(getTextPreservingWhitespace(ctx.drlBlock().drlBlockStatement())); + populateStartEnd(functionDescr, ctx); return functionDescr; } @@ -215,6 +220,7 @@ public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContex ctx.field().stream() .map(this::visitField) .forEach(typeDeclarationDescr::addField); + populateStartEnd(typeDeclarationDescr, ctx); return typeDeclarationDescr; } @@ -225,6 +231,7 @@ public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPoin ctx.drlAnnotation().stream() .map(this::visitDrlAnnotation) .forEach(entryPointDeclarationDescr::addAnnotation); + populateStartEnd(entryPointDeclarationDescr, ctx); return entryPointDeclarationDescr; } @@ -236,6 +243,7 @@ public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclaration .map(this::visitDrlAnnotation) .forEach(windowDeclarationDescr::addAnnotation); windowDeclarationDescr.setPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); + populateStartEnd(windowDeclarationDescr, ctx); return windowDeclarationDescr; } @@ -315,6 +323,7 @@ public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { slimLhsRootDescr(queryDescr.getLhs()); + populateStartEnd(queryDescr, ctx); return queryDescr; } @@ -329,6 +338,7 @@ public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { // A chunk that is neither a single value nor a list of key-value pairs. For example `!*, age` in `@watch(!*, age)`. annotationDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); } + populateStartEnd(annotationDescr, ctx); return annotationDescr; } @@ -343,6 +353,7 @@ public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { ctx.drlAnnotation().stream() .map(this::visitDrlAnnotation) .forEach(typeFieldDescr::addAnnotation); + populateStartEnd(typeFieldDescr, ctx); return typeFieldDescr; } @@ -359,6 +370,7 @@ public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeCont AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); attributeDescr.setValue(getTextPreservingWhitespace(ctx.conditionalOrExpression())); attributeDescr.setType(AttributeDescr.Type.EXPRESSION); + populateStartEnd(attributeDescr, ctx); return attributeDescr; } @@ -367,6 +379,7 @@ public AttributeDescr visitBooleanAttribute(DRLParser.BooleanAttributeContext ct AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); attributeDescr.setValue(ctx.BOOL_LITERAL() != null ? ctx.BOOL_LITERAL().getText() : "true"); attributeDescr.setType(AttributeDescr.Type.BOOLEAN); + populateStartEnd(attributeDescr, ctx); return attributeDescr; } @@ -375,6 +388,7 @@ public AttributeDescr visitStringAttribute(DRLParser.StringAttributeContext ctx) AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.DRL_STRING_LITERAL().getText()))); attributeDescr.setType(AttributeDescr.Type.STRING); + populateStartEnd(attributeDescr, ctx); return attributeDescr; } @@ -386,6 +400,7 @@ public AttributeDescr visitStringListAttribute(DRLParser.StringListAttributeCont .collect(Collectors.toList()); attributeDescr.setValue(createStringList(valueList)); attributeDescr.setType(AttributeDescr.Type.LIST); + populateStartEnd(attributeDescr, ctx); return attributeDescr; } @@ -412,6 +427,7 @@ public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeCont attributeDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); attributeDescr.setType(AttributeDescr.Type.EXPRESSION); } + populateStartEnd(attributeDescr, ctx); return attributeDescr; } @@ -425,6 +441,7 @@ public AttributeDescr visitDurationAttribute(DRLParser.DurationAttributeContext attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.TIME_INTERVAL().getText()))); attributeDescr.setType(AttributeDescr.Type.EXPRESSION); } + populateStartEnd(attributeDescr, ctx); return attributeDescr; } @@ -480,6 +497,7 @@ private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindConte orDescr.addDescr(patternDescr); }); + populateStartEnd(orDescr, ctx); return orDescr; } @@ -500,6 +518,9 @@ public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { patternSourceDescr.setResource(patternDescr.getResource()); patternDescr.setSource(patternSourceDescr); } + + populateStartEnd(patternDescr, ctx); + ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(patternDescr::addAnnotation); List constraintDescrList = visitConstraints(ctx.positionalConstraints(), ctx.constraints()); constraintDescrList.forEach(descr -> addToPatternDescr(patternDescr, descr)); @@ -515,6 +536,7 @@ private void addToPatternDescr(PatternDescr patternDescr, ExprConstraintDescr ex public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { ForallDescr forallDescr = new ForallDescr(); visitDescrChildren(ctx).forEach(forallDescr::addDescr); + populateStartEnd(forallDescr, ctx); return forallDescr; } @@ -532,6 +554,8 @@ public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { patternDescr.setSource(accumulateDescr); List constraintDescrList = visitConstraints(ctx.constraints()); constraintDescrList.forEach(patternDescr::addConstraint); + + populateStartEnd(accumulateDescr, ctx); return patternDescr; } @@ -543,6 +567,7 @@ public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { List drlExpressionContexts = ctx.expressionList().drlExpression(); List parameters = drlExpressionContexts.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); behaviorDescr.setParameters(parameters); + populateStartEnd(behaviorDescr, ctx); return behaviorDescr; } @@ -550,6 +575,7 @@ public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { FromDescr fromDescr = new FromDescr(); fromDescr.setDataSource(new MVELExprDescr(getTextPreservingWhitespace(ctx))); + populateStartEnd(fromDescr, ctx); return fromDescr; } @@ -557,6 +583,7 @@ public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { public CollectDescr visitFromCollect(DRLParser.FromCollectContext ctx) { CollectDescr collectDescr = new CollectDescr(); collectDescr.setInputPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); + populateStartEnd(collectDescr, ctx); return collectDescr; } @@ -576,6 +603,7 @@ public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) // accumulate function accumulateDescr.addFunction(visitAccumulateFunction(ctx.accumulateFunction())); } + populateStartEnd(accumulateDescr, ctx); return accumulateDescr; } @@ -648,6 +676,7 @@ public List visitConstraint(DRLParser.ConstraintContext ctx if (!constraint.isEmpty()) { ExprConstraintDescr constraintDescr = new ExprConstraintDescr(constraint); constraintDescr.setType(ExprConstraintDescr.Type.NAMED); + populateStartEnd(constraintDescr, ctx); descrList.add(constraintDescr); return descrList; } @@ -692,6 +721,7 @@ public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); existsDescr.addDescr(descr); } + populateStartEnd(existsDescr, ctx); return existsDescr; } @@ -711,12 +741,15 @@ public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); notDescr.addDescr(descr); } + populateStartEnd(notDescr, ctx); return notDescr; } @Override public EvalDescr visitLhsEval(DRLParser.LhsEvalContext ctx) { - return new EvalDescr(getTextPreservingWhitespace(ctx.conditionalOrExpression())); + EvalDescr evalDescr = new EvalDescr(getTextPreservingWhitespace(ctx.conditionalOrExpression())); + populateStartEnd(evalDescr, ctx); + return evalDescr; } @Override @@ -744,6 +777,7 @@ public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { // So, we need to flatten it so that OrDescr has A(), B() and C() as children. List flattenedDescrs = flattenOrDescr(descrList); flattenedDescrs.forEach(orDescr::addDescr); + populateStartEnd(orDescr, ctx); return orDescr; } } @@ -786,6 +820,7 @@ private BaseDescr createAndDescr(ParserRuleContext ctx) { // So, we need to flatten it so that AndDescr has A(), B() and C() as children. List flattenedDescrs = flattenAndDescr(descrList); flattenedDescrs.forEach(andDescr::addDescr); + populateStartEnd(andDescr, ctx); return andDescr; } } @@ -820,6 +855,8 @@ private void populateStartEnd(BaseDescr descr, ParserRuleContext ctx) { // TODO: Current DRL6Parser adds +1 for EndCharacter but it doesn't look reasonable. At the moment, I don't add. Instead, I fix unit tests. // I will revisit if this is the right approach. descr.setEndCharacter(ctx.getStop().getStopIndex()); + descr.setLocation(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); + descr.setEndLocation(ctx.getStop().getLine(), ctx.getStop().getCharPositionInLine()); } /** From 225c7d7f1624471349670cca99c2b94503b55dbe Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 27 Mar 2024 17:30:21 +0900 Subject: [PATCH 077/141] [incubator-kie-drools#5711] Broken OOPath expressions (#5805) * [incubator-kie-drools#5711] Broken OOPath expressions * accept mixing OOPath and standard constraint --- .../drl/parser/antlr4/MiscDRLParserTest.java | 94 ++++++++++++++++--- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 13 +++ 2 files changed, 92 insertions(+), 15 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 53eda685add..a65fafec286 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 @@ -3635,9 +3635,7 @@ void nullSafeDereferencing() { "then\n" + "end\n"; PackageDescr packageDescr = parser.parse(text); - RuleDescr ruleDescr = packageDescr.getRules().get(0); - PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); - ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("address!.city == $city"); } @@ -3650,9 +3648,7 @@ void nullSafeDereferencingMethodCall() { "then\n" + "end\n"; PackageDescr packageDescr = parser.parse(text); - RuleDescr ruleDescr = packageDescr.getRules().get(0); - PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); - ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("address!.city!.startsWith(\"M\")"); } @@ -3665,9 +3661,7 @@ void nullSafeDereferencingMethodCallBindVariable() { "then\n" + "end\n"; PackageDescr packageDescr = parser.parse(text); - RuleDescr ruleDescr = packageDescr.getRules().get(0); - PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); - ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("$containsL : address!.city.contains(\"L\")"); } @@ -3680,9 +3674,7 @@ void groupedConstraints() { "then\n" + "end\n"; PackageDescr packageDescr = parser.parse(text); - RuleDescr ruleDescr = packageDescr.getRules().get(0); - PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); - ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()) .as("prefix should be appended to each element") .isEqualToIgnoringWhitespace("address.city.startsWith(\"I\") && address.city.length() == 5"); @@ -3697,9 +3689,7 @@ void groupedConstraintsWithNullSafeDereferencing() { "then\n" + "end\n"; PackageDescr packageDescr = parser.parse(text); - RuleDescr ruleDescr = packageDescr.getRules().get(0); - PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); - ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()) .as("prefix should be appended to each element") .isEqualToIgnoringWhitespace("address!.city!.startsWith(\"I\") && address!.city!.length() == 5"); @@ -3806,4 +3796,78 @@ public void expiresWithTimeLiteralValue() { assertThat(annotationDescr.getValueAsString("value")).isEqualTo("2s"); assertThat(annotationDescr.getValueAsString("policy")).isEqualTo("TIME_SOFT"); } + + @Test + void ooPath() { + final String text = "package org.drools\n" + + "rule R when\n" + + " $man: Man( /wife/children[age > 10] )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .isEqualToIgnoringWhitespace("/wife/children[age > 10]"); + } + + private static ExprConstraintDescr getFirstExprConstraintDescr(PackageDescr packageDescr) { + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + return constraintDescr; + } + + @Test + void ooPathWithBindingInBrackets() { + final String text = "package org.drools\n" + + "rule R when\n" + + " Man( /wife[$age : age] )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .isEqualToIgnoringWhitespace("/wife[$age : age]"); + } + + @Test + void ooPathWithBindingInParentheses() { + final String text = "package org.drools\n" + + "rule R when\n" + + " Man( $toy: /wife/children[age > 10]/toys )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .isEqualToIgnoringWhitespace("$toy: /wife/children[age > 10]/toys"); + } + + @Test + void ooPathWithBackReference() { + final String text = "package org.drools\n" + + "rule R when\n" + + " Man( $toy: /wife/children/toys[ name.length == ../name.length ] )\n" + + "then\n" + + "end\n"; + + PackageDescr packageDescr = parser.parse(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .isEqualToIgnoringWhitespace("$toy: /wife/children/toys[ name.length == ../name.length ]"); + } + + @Test + void ooPathMixedWithStandardConstraint() { + final String text = "package org.drools\n" + + "rule R when\n" + + " Man( /wife[$age : age] && age > $age )\n" + + "then\n" + + "end\n"; + + PackageDescr packageDescr = parser.parse(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .isEqualToIgnoringWhitespace("/wife[$age : age] && age > $age"); + } } 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/DRLParser.g4 index 34ebacd4da1..5891d6eaa90 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/DRLParser.g4 @@ -144,6 +144,12 @@ orRestriction : left=andRestriction (OR right=andRestriction)* ; andRestriction : left=singleRestriction (AND right=singleRestriction)* ; singleRestriction : op=relationalOperator drlExpression ; +// OOPath +xpathSeparator : DIV | QUESTION_DIV ; +xpathPrimary : label? xpathChunk+ ; +xpathChunk : xpathSeparator drlIdentifier (DOT drlIdentifier)* (HASH drlIdentifier)? (LBRACK xpathExpressionList RBRACK)? ; +xpathExpressionList : label? drlExpression (COMMA label? drlExpression)* ; + relationalOperator : EQUAL | NOTEQUAL @@ -284,8 +290,15 @@ drlExpression | drlExpression COLONCOLON typeArguments? drlIdentifier | typeType COLONCOLON (typeArguments? drlIdentifier | NEW) | classType COLONCOLON typeArguments? NEW + + // OOPath + | xpathPrimary + | backReferenceExpression ; +backReferenceExpression : (DOT DOT DIV)+ drlExpression ; + + /* extending JavaParser methodCall in order to accept drl keywords as method name */ drlMethodCall : drlIdentifier LPAREN expressionList? RPAREN From 75996ff8fb4a2255cc612ecd5cb9cf88991f064f Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 28 Mar 2024 18:24:46 +0900 Subject: [PATCH 078/141] [incubator-kie-drools#5742] [new-parser] Broken inline cast (#5806) * [incubator-kie-drools#5742] [new-parser] Broken inline cast * fixed duplicate test --- .../drl/parser/antlr4/MiscDRLParserTest.java | 39 +++++++++++++++++++ .../drl/parser/antlr4/DRL6Expressions.g4 | 2 +- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 5 +++ 3 files changed, 45 insertions(+), 1 deletion(-) 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 a65fafec286..0029602df5a 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 @@ -3870,4 +3870,43 @@ void ooPathMixedWithStandardConstraint() { assertThat(constraintDescr.toString()) .isEqualToIgnoringWhitespace("/wife[$age : age] && age > $age"); } + + @Test + void inlineCast() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $a : ICA( someB#ICB.onlyConcrete() == \"Hello\" )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("someB#ICB.onlyConcrete() == \"Hello\""); + } + + @Test + void inlineCastMultiple() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $a : ICA( someB#ICB.someC#ICC.onlyConcrete() == \"Hello\" )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("someB#ICB.someC#ICC.onlyConcrete() == \"Hello\""); + } + + @Test + void inlineCastThis() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $o : Object( this#Person.name == \"Mark\" )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("this#Person.name == \"Mark\""); + } } 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/DRL6Expressions.g4 index d85859d3bd5..ee5ce23259a 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/DRL6Expressions.g4 @@ -230,6 +230,7 @@ drlIdentifier returns [Token token] | PERMITS | RECORD | VAR + | THIS ; // -------------------------------------------------------- @@ -671,7 +672,6 @@ primary returns [BaseDescr result] : expr=parExpression { if( buildDescr ) { $result = $expr.result; } } | nonWildcardTypeArguments (explicitGenericInvocationSuffix | this_key arguments) | literal { if( buildDescr ) { $result = new AtomicExprDescr( $literal.text, true ); } } - | this_key (DOT drlIdentifier)* identifierSuffix? | super_key superSuffix | new_key creator | primitiveType (LBRACK RBRACK)* DOT class_key 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/DRLParser.g4 index 5891d6eaa90..7eb20980cd3 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/DRLParser.g4 @@ -197,6 +197,7 @@ drlIdentifier | PERMITS | RECORD | VAR + | THIS ; drlKeywords @@ -258,6 +259,7 @@ drlExpression | NEW nonWildcardTypeArguments? innerCreator | SUPER superSuffix | explicitGenericInvocation + | inlineCast ) | drlExpression NULL_SAFE_DOT ( drlIdentifier | drlMethodCall ) | drlExpression LBRACK drlExpression RBRACK @@ -321,8 +323,11 @@ drlPrimary | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) | inlineListExpression | inlineMapExpression + | inlineCast ; +inlineCast : drlIdentifier HASH drlIdentifier ; + /* extending JavaParser literal */ drlLiteral : integerLiteral From 5876a85e7932c1742fffe963952a0021655738d8 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 2 Apr 2024 15:25:12 +0900 Subject: [PATCH 079/141] [incubator-kie-drools-5712] Queries with arguments cannot be parsed (#5811) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 70 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 8 ++- .../drl/parser/antlr4/DRLVisitorImpl.java | 15 ++-- 3 files changed, 84 insertions(+), 9 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 0029602df5a..86beaa4e139 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 @@ -3909,4 +3909,74 @@ void inlineCastThis() { ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("this#Person.name == \"Mark\""); } + + @Test + public void queryArgumentWithoutType() throws Exception { + final String text = "package org.drools\n" + + "query olderThan( $age )\n" + + " $p : Person(age > (Integer)$age)\n" + + "end "; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + assertThat(query.getName()).isEqualTo("olderThan"); + assertThat(query.getParameterTypes()).containsExactly("Object"); + assertThat(query.getParameters()).containsExactly("$age"); + } + + @Test + public void queryMultipleArguments() throws Exception { + final String text = "package org.drools\n" + + "query olderThan( String $name, int $age )\n" + + " $p : Person(age > $age)\n" + + "end "; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + assertThat(query.getName()).isEqualTo("olderThan"); + assertThat(query.getParameterTypes()).containsExactly("String", "int"); + assertThat(query.getParameters()).containsExactly("$name", "$age"); + } + + @Test + public void queryArrayArgument() throws Exception { + final String text = "package org.drools\n" + + "query olderThan( int[] $ages )\n" + + " $p : Person(age > $ages[0])\n" + + "end "; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + assertThat(query.getName()).isEqualTo("olderThan"); + assertThat(query.getParameterTypes()).containsExactly("int[]"); + assertThat(query.getParameters()).containsExactly("$ages"); + } + + @Test + public void queryZeroArgument() throws Exception { + final String text = "package org.drools\n" + + "query olderThan()\n" + + " $p : Person()\n" + + "end "; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + assertThat(query.getName()).isEqualTo("olderThan"); + assertThat(query.getParameterTypes()).isEmpty(); + assertThat(query.getParameters()).isEmpty(); + } + + @Test + public void queryNoArgument() throws Exception { + final String text = "package org.drools\n" + + "query olderThan\n" + + " $p : Person()\n" + + "end "; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + assertThat(query.getName()).isEqualTo("olderThan"); + assertThat(query.getParameterTypes()).isEmpty(); + assertThat(query.getParameters()).isEmpty(); + } } 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/DRLParser.g4 index 7eb20980cd3..8c48c7def46 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/DRLParser.g4 @@ -79,7 +79,13 @@ ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* a // query := QUERY stringId parameters? annotation* lhsExpression END -querydef : DRL_QUERY name=stringId formalParameters? drlAnnotation* lhsExpression+ DRL_END SEMI?; +querydef : DRL_QUERY name=stringId parameters? drlAnnotation* lhsExpression+ DRL_END SEMI?; + +// parameters := LEFT_PAREN ( parameter ( COMMA parameter )* )? RIGHT_PAREN +parameters : LPAREN ( parameter ( COMMA parameter )* )? RPAREN ; + +// parameter := ({requiresType}?=>type)? ID (LEFT_SQUARE RIGHT_SQUARE)* +parameter : type? drlIdentifier ; // type is optional. Removed (LEFT_SQUARE RIGHT_SQUARE)* as it doesn't make sense in the grammar lhs : DRL_WHEN lhsExpression* ; 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 8fa0be743df..292b366e814 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 @@ -304,14 +304,13 @@ private void slimLhsRootDescr(AndDescr root) { public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { QueryDescr queryDescr = new QueryDescr(safeStripStringDelimiters(ctx.name.getText())); - DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); - if (formalParametersContext != null) { - DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); - List formalParameterContexts = formalParameterListContext.formalParameter(); - formalParameterContexts.forEach(formalParameterContext -> { - DRLParser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); - DRLParser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); - queryDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); + DRLParser.ParametersContext parametersContext = ctx.parameters(); + if (parametersContext != null) { + 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(); + queryDescr.addParameter(type, name); }); } From f5363baae41573d1d9dfb73b5c688b193a717d4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Tue, 2 Apr 2024 10:09:58 +0200 Subject: [PATCH 080/141] [new-parser] Complete support for built-in operators (after, before) (#5812) * Improve no viable alternative example * Complete support for built-in operators * Enable soundslike test * Remove obsolete comment Co-authored-by: Toshiya Kobayashi --------- Co-authored-by: Toshiya Kobayashi --- .../drl/parser/antlr4/DRLExprParserTest.java | 47 ++++++++--- .../drl/parser/antlr4/MiscDRLParserTest.java | 1 - .../drl/parser/antlr4/DRL6Expressions.g4 | 80 ++++++++++++------- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 43 ++++++---- 4 files changed, 113 insertions(+), 58 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 e32f287beb2..3f3b256dd50 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 @@ -19,6 +19,10 @@ package org.drools.drl.parser.antlr4; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +import java.util.Arrays; +import java.util.List; import org.drools.drl.ast.descr.AtomicExprDescr; import org.drools.drl.ast.descr.BindingDescr; @@ -27,11 +31,13 @@ import org.drools.drl.ast.descr.RelationalExprDescr; import org.drools.drl.parser.DrlExprParser; import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.impl.Operator; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; 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; @@ -212,9 +218,22 @@ public void testDoubleBinding() throws Exception { assertThat(bind.getExpression()).isEqualTo("y[z].foo"); } - @Test - public void testDrlKeywordMethodCall() throws Exception { - String source = "x.contains( 1, a )"; + private static final List nonKeywordBuiltInOperators = Arrays.asList( + Operator.BuiltInOperator.EQUAL, + Operator.BuiltInOperator.NOT_EQUAL, + Operator.BuiltInOperator.LESS, + Operator.BuiltInOperator.LESS_OR_EQUAL, + Operator.BuiltInOperator.GREATER, + Operator.BuiltInOperator.GREATER_OR_EQUAL + ); + + @ParameterizedTest + @EnumSource(Operator.BuiltInOperator.class) + public void testDrlKeywordMethodCall(Operator.BuiltInOperator operator) throws Exception { + // Skip operators that cannot be used as method names (==, !=, <, etc.). + assumeFalse(nonKeywordBuiltInOperators.contains(operator)); + + String source = String.format("x.%s( 1, a )", operator.getSymbol()); ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); @@ -222,12 +241,18 @@ public void testDrlKeywordMethodCall() throws Exception { assertThat(result.getDescrs().size()).isEqualTo(1); AtomicExprDescr descr = (AtomicExprDescr) result.getDescrs().get( 0 ); - assertThat(descr.getExpression()).isEqualTo("x.contains( 1, a )"); + assertThat(descr.getExpression()).isEqualTo(source); } - @Test - public void testDrlKeywordMethodCallBinding() throws Exception { - String source = "$x : x.contains( 1, a )"; + @ParameterizedTest + @EnumSource(Operator.BuiltInOperator.class) + public void testDrlKeywordMethodCallBinding(Operator.BuiltInOperator operator) throws Exception { + // Skip operators that cannot be used as method names (==, !=, <, etc.). + assumeFalse(nonKeywordBuiltInOperators.contains(operator)); + + String expressionSource = String.format("x.%s( 1, a )", operator.getSymbol()); + String bindingVariableSource = "$x"; + String source = bindingVariableSource + " : " + expressionSource; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); @@ -235,8 +260,8 @@ public void testDrlKeywordMethodCallBinding() throws Exception { assertThat(result.getDescrs().size()).isEqualTo(1); BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); - assertThat(bind.getVariable()).isEqualTo("$x"); - assertThat(bind.getExpression()).isEqualTo("x.contains( 1, a )"); + assertThat(bind.getVariable()).isEqualTo(bindingVariableSource); + assertThat(bind.getExpression()).isEqualTo(expressionSource); } @Test @@ -388,7 +413,7 @@ public void testExtraneousInput() { } @Test public void testNoViableAlt() { - String source = "a~a"; + String source = "x.int"; parser.parse(source); assertThat(parser.hasErrors()).isTrue(); assertThat(parser.getErrors()).hasSize(1); @@ -398,6 +423,6 @@ public void testNoViableAlt() { 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 '.int'"); } } 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 86beaa4e139..fa961b876ab 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 @@ -1980,7 +1980,6 @@ public void parse_ExtraLhsNewline() throws Exception { assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); } - @Disabled("Priority : Low | Implement soundslike") @Test public void parse_SoundsLike() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( 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/DRL6Expressions.g4 index ee5ce23259a..47e01001a65 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/DRL6Expressions.g4 @@ -162,9 +162,32 @@ typeArgument | QUESTION ((extends_key | super_key) type)? ; +// matches any identifiers including acceptable java keywords (defined in JavaParser.g4) and drl keywords +drlIdentifier returns [Token token] + : drlKeywords + | IDENTIFIER + | MODULE + | OPEN + | REQUIRES + | EXPORTS + | OPENS + | TO + | USES + | PROVIDES + | WITH + | TRANSITIVE + | YIELD + | SEALED + | PERMITS + | RECORD + | VAR + | THIS + ; + // matches any drl keywords drlKeywords returns [Token token] - : DRL_UNIT + : builtInOperator + | DRL_UNIT | DRL_FUNCTION | DRL_GLOBAL | DRL_DECLARE @@ -179,12 +202,6 @@ drlKeywords returns [Token token] | DRL_NOT | DRL_IN | DRL_FROM - | DRL_MATCHES - | DRL_MEMBEROF - | DRL_CONTAINS - | DRL_EXCLUDES - | DRL_SOUNDSLIKE - | DRL_STR | DRL_ACCUMULATE | DRL_ACC | DRL_INIT @@ -211,26 +228,26 @@ drlKeywords returns [Token token] | DRL_DURATION ; -// matches any identifiers including acceptable java keywords (defined in JavaParser.g4) and drl keywords -drlIdentifier returns [Token token] - : drlKeywords - | IDENTIFIER - | MODULE - | OPEN - | REQUIRES - | EXPORTS - | OPENS - | TO - | USES - | PROVIDES - | WITH - | TRANSITIVE - | YIELD - | SEALED - | PERMITS - | RECORD - | VAR - | THIS +builtInOperator returns[Token token] + : DRL_CONTAINS + | DRL_EXCLUDES + | DRL_MATCHES + | DRL_MEMBEROF + | DRL_SOUNDSLIKE + | DRL_AFTER + | DRL_BEFORE + | DRL_COINCIDES + | DRL_DURING + | DRL_FINISHED_BY + | DRL_FINISHES + | DRL_INCLUDES + | DRL_MEETS + | DRL_MET_BY + | DRL_OVERLAPPED_BY + | DRL_OVERLAPS + | DRL_STARTED_BY + | DRL_STARTS + | DRL_STR ; // -------------------------------------------------------- @@ -908,11 +925,12 @@ in_key ; operator_key - // At the moment, we list possible DRLLexer tokens here, but we may be able to improve this by isolating lexers. IDENTIFIER is required to accept custom operators - // We need to keep this semantic predicate for custom operators - : {(helper.isPluggableEvaluator(false))}? id=(IDENTIFIER|DRL_MATCHES|DRL_MEMBEROF|DRL_CONTAINS|DRL_EXCLUDES|DRL_SOUNDSLIKE|DRL_STR) { helper.emit($id, DroolsEditorType.KEYWORD); } + // 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); } + | op=builtInOperator { helper.emit($op.token, DroolsEditorType.KEYWORD); } ; neg_operator_key - : {(helper.isPluggableEvaluator(true))}? id=(IDENTIFIER|DRL_MATCHES|DRL_MEMBEROF|DRL_CONTAINS|DRL_EXCLUDES|DRL_SOUNDSLIKE|DRL_STR) { helper.emit($id, DroolsEditorType.KEYWORD); } + : {(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/DRLParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 index 8c48c7def46..90b9801e42d 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/DRLParser.g4 @@ -148,7 +148,7 @@ inExpression : left=relationalExpression ( 'not'? 'in' LPAREN drlExpression (COM relationalExpression : left=drlExpression (right=orRestriction)* ; orRestriction : left=andRestriction (OR right=andRestriction)* ; andRestriction : left=singleRestriction (AND right=singleRestriction)* ; -singleRestriction : op=relationalOperator drlExpression ; +singleRestriction : op=relationalOperator squareArguments? drlExpression ; // OOPath xpathSeparator : DIV | QUESTION_DIV ; @@ -167,13 +167,7 @@ relationalOperator | temporalOperator ; -drlRelationalOperator - : DRL_NOT? DRL_MATCHES - | DRL_NOT? DRL_MEMBEROF - | DRL_NOT? DRL_CONTAINS - | DRL_NOT? DRL_EXCLUDES - | DRL_NOT? DRL_SOUNDSLIKE - | DRL_NOT? DRL_STR LBRACK IDENTIFIER RBRACK ; +drlRelationalOperator : DRL_NOT? builtInOperator ; /* function := FUNCTION type? ID parameters(typed) chunk_{_} */ functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters drlBlock ; @@ -207,7 +201,8 @@ drlIdentifier ; drlKeywords - : DRL_UNIT + : builtInOperator + | DRL_UNIT | DRL_FUNCTION | DRL_GLOBAL | DRL_DECLARE @@ -222,12 +217,6 @@ drlKeywords | DRL_NOT | DRL_IN | DRL_FROM - | DRL_MATCHES - | DRL_MEMBEROF - | DRL_CONTAINS - | DRL_EXCLUDES - | DRL_SOUNDSLIKE - | DRL_STR | DRL_ACCUMULATE | DRL_ACC | DRL_INIT @@ -254,6 +243,28 @@ drlKeywords | DRL_DURATION ; +builtInOperator + : DRL_CONTAINS + | DRL_EXCLUDES + | DRL_MATCHES + | DRL_MEMBEROF + | DRL_SOUNDSLIKE + | DRL_AFTER + | DRL_BEFORE + | DRL_COINCIDES + | DRL_DURING + | DRL_FINISHED_BY + | DRL_FINISHES + | DRL_INCLUDES + | DRL_MEETS + | DRL_MET_BY + | DRL_OVERLAPPED_BY + | DRL_OVERLAPS + | DRL_STARTED_BY + | DRL_STARTS + | DRL_STR + ; + /* extending JavaParser expression */ drlExpression : drlPrimary @@ -348,6 +359,8 @@ drlLiteral | TIME_INTERVAL ; +squareArguments : LBRACK expressionList? RBRACK ; + inlineListExpression : LBRACK expressionList? RBRACK ; From b5adbe02ce70edc32ec24c1313ad674412658f93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 3 Apr 2024 11:01:19 +0200 Subject: [PATCH 081/141] [new-parser] Fix two minor type declaration issues (#5815) * Allow semicolon after type declaration end * Allow DRL keywords to be used as field names in type declarations --- .../main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 | 4 ++-- .../java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) 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/DRLParser.g4 index 90b9801e42d..b71b4ea219e 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/DRLParser.g4 @@ -50,7 +50,7 @@ declaredef : DRL_DECLARE ( | entryPointDeclaration | windowDeclaration | typeDeclaration - ) DRL_END ; + ) DRL_END SEMI?; /* * typeDeclaration := [TYPE] qualifiedIdentifier (EXTENDS qualifiedIdentifier)? @@ -533,7 +533,7 @@ assignmentOperator : ASSIGN | MOD_ASSIGN | LT LT ASSIGN ; -label : IDENTIFIER COLON ; +label : drlIdentifier COLON ; unif : IDENTIFIER DRL_UNIFY ; /* extending JavaParser variableInitializer */ 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 292b366e814..228ea473b29 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 @@ -344,7 +344,7 @@ public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { @Override public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { TypeFieldDescr typeFieldDescr = new TypeFieldDescr(); - typeFieldDescr.setFieldName(ctx.label().IDENTIFIER().getText()); + typeFieldDescr.setFieldName(ctx.label().drlIdentifier().getText()); typeFieldDescr.setPattern(new PatternDescr(ctx.type().getText())); if (ctx.ASSIGN() != null) { typeFieldDescr.setInitExpr(getTextPreservingWhitespace(ctx.initExpr)); @@ -475,7 +475,7 @@ private PatternDescr getSinglePatternDescr(DRLParser.LhsPatternBindContext ctx) PatternDescr patternDescr = (PatternDescr)patternDescrList.get(0); if (ctx.label() != null) { - patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); + patternDescr.setIdentifier(ctx.label().drlIdentifier().getText()); } else if (ctx.unif() != null) { patternDescr.setIdentifier(ctx.unif().IDENTIFIER().getText()); patternDescr.setUnification(true); @@ -491,7 +491,7 @@ private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindConte .map(PatternDescr.class::cast) .forEach(patternDescr -> { if (ctx.label() != null) { - patternDescr.setIdentifier(ctx.label().IDENTIFIER().getText()); + patternDescr.setIdentifier(ctx.label().drlIdentifier().getText()); } orDescr.addDescr(patternDescr); }); @@ -609,7 +609,7 @@ public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) @Override public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLParser.AccumulateFunctionContext ctx) { String function = ctx.IDENTIFIER().getText(); - String bind = ctx.label() == null ? null : ctx.label().IDENTIFIER().getText(); + String bind = ctx.label() == null ? null : ctx.label().drlIdentifier().getText(); String[] params = new String[]{getTextPreservingWhitespace(ctx.drlExpression())}; return new AccumulateDescr.AccumulateFunctionCallDescr(function, bind, false, params); } From eac45f414976257c4b9138796e62c32767e6ba51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 3 Apr 2024 11:02:18 +0200 Subject: [PATCH 082/141] Support trait type declaration (#5820) --- .../src/main/antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 | 1 + .../src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- .../main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java | 3 +++ 3 files changed, 5 insertions(+), 1 deletion(-) 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/DRLLexer.g4 index 79c439586f6..dc974ecac82 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/DRLLexer.g4 @@ -31,6 +31,7 @@ DRL_UNIT : 'unit'; DRL_FUNCTION : 'function'; DRL_GLOBAL : 'global'; DRL_DECLARE : 'declare'; +DRL_TRAIT : 'trait'; DRL_RULE : 'rule'; DRL_QUERY : 'query'; DRL_WHEN : 'when'; 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/DRLParser.g4 index b71b4ea219e..7cc1d584d8b 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/DRLParser.g4 @@ -59,7 +59,7 @@ declaredef : DRL_DECLARE ( * END */ -typeDeclaration : name=drlQualifiedName (EXTENDS superType=drlQualifiedName)? drlAnnotation* field* ; +typeDeclaration : DRL_TRAIT? name=drlQualifiedName (EXTENDS superType=drlQualifiedName)? drlAnnotation* field* ; // entryPointDeclaration := ENTRY-POINT stringId annotation* END 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 228ea473b29..b9564e9a770 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 @@ -211,6 +211,9 @@ public BaseDescr visitDeclaredef(DRLParser.DeclaredefContext ctx) { @Override public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContext ctx) { TypeDeclarationDescr typeDeclarationDescr = new TypeDeclarationDescr(ctx.name.getText()); + if (ctx.DRL_TRAIT() != null) { + typeDeclarationDescr.setTrait(true); + } if (ctx.EXTENDS() != null) { typeDeclarationDescr.addSuperType(ctx.superType.getText()); } From bfee0417f0b776737f958dbee2935f4c6cdcae7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Thu, 4 Apr 2024 16:24:56 +0200 Subject: [PATCH 083/141] Allow traits to inherit multiple traits (#5824) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 19 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 4 +++- 3 files changed, 23 insertions(+), 2 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 fa961b876ab..2d213238287 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 @@ -34,6 +34,7 @@ import org.drools.drl.ast.descr.OrDescr; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.QualifiedName; import org.drools.drl.ast.descr.QueryDescr; import org.drools.drl.ast.descr.RuleDescr; import org.drools.drl.ast.descr.TypeDeclarationDescr; @@ -3978,4 +3979,22 @@ public void queryNoArgument() throws Exception { assertThat(query.getParameterTypes()).isEmpty(); assertThat(query.getParameters()).isEmpty(); } + + @Test + public void traitExtendsMultiple() throws Exception { + final String source = "declare trait FatherTrait extends com.sample.ParentTrait, UncleTrait, org.test.GrandParentTrait end"; + + PackageDescr pkg = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + final List declarations = pkg.getTypeDeclarations(); + + assertThat(declarations).hasSize(1); + TypeDeclarationDescr trait = declarations.get(0); + assertThat(trait.getSuperTypeName()).isEqualTo("ParentTrait"); + assertThat(trait.getSuperTypeNamespace()).isEqualTo("com.sample"); + assertThat(trait.getSuperTypes()) + .map(QualifiedName::getFullName) + .containsExactlyInAnyOrder("com.sample.ParentTrait", "UncleTrait", "org.test.GrandParentTrait"); + } } 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/DRLParser.g4 index 7cc1d584d8b..7d9dd2235fc 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/DRLParser.g4 @@ -59,7 +59,7 @@ declaredef : DRL_DECLARE ( * END */ -typeDeclaration : DRL_TRAIT? name=drlQualifiedName (EXTENDS superType=drlQualifiedName)? drlAnnotation* field* ; +typeDeclaration : DRL_TRAIT? name=drlQualifiedName (EXTENDS superTypes+=drlQualifiedName (COMMA superTypes+=drlQualifiedName)* )? drlAnnotation* field* ; // entryPointDeclaration := ENTRY-POINT stringId annotation* END 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 b9564e9a770..84ebe76f56d 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 @@ -215,7 +215,9 @@ public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContex typeDeclarationDescr.setTrait(true); } if (ctx.EXTENDS() != null) { - typeDeclarationDescr.addSuperType(ctx.superType.getText()); + for (DRLParser.DrlQualifiedNameContext superType : ctx.superTypes) { + typeDeclarationDescr.addSuperType(superType.getText()); + } } ctx.drlAnnotation().stream() .map(this::visitDrlAnnotation) From baa645d4364830cbd38cb53b9289e0b352cc88c7 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 5 Apr 2024 17:19:35 +0900 Subject: [PATCH 084/141] [incubator-kie-drools-5798] [new-parser] Ensure Descr properties (#5827) * [incubator-kie-drools-5798] [new-parser] Ensure Descr properties * [incubator-kie-issues#5798] Proposal * minor fix --------- Co-authored-by: Gabriele-Cardosi --- .../antlr4/DescrCommonPropertyTest.java | 405 ++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 9 +- .../drl/parser/antlr4/BaseDescrFactory.java | 60 +++ .../drl/parser/antlr4/DRLVisitorImpl.java | 198 +++++---- .../drools/drl/parser/antlr4/DescrHelper.java | 70 +++ 5 files changed, 653 insertions(+), 89 deletions(-) create mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrCommonPropertyTest.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/BaseDescrFactory.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DescrHelper.java 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 new file mode 100644 index 00000000000..bc3010e6987 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrCommonPropertyTest.java @@ -0,0 +1,405 @@ +package org.drools.drl.parser.antlr4; + +import org.drools.drl.ast.descr.AccumulateDescr; +import org.drools.drl.ast.descr.AccumulateImportDescr; +import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.BehaviorDescr; +import org.drools.drl.ast.descr.CollectDescr; +import org.drools.drl.ast.descr.EntryPointDeclarationDescr; +import org.drools.drl.ast.descr.EntryPointDescr; +import org.drools.drl.ast.descr.EvalDescr; +import org.drools.drl.ast.descr.ExistsDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.ForallDescr; +import org.drools.drl.ast.descr.FromDescr; +import org.drools.drl.ast.descr.FunctionDescr; +import org.drools.drl.ast.descr.FunctionImportDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.ImportDescr; +import org.drools.drl.ast.descr.NotDescr; +import org.drools.drl.ast.descr.OrDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.PatternSourceDescr; +import org.drools.drl.ast.descr.QueryDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.TypeDeclarationDescr; +import org.drools.drl.ast.descr.TypeFieldDescr; +import org.drools.drl.ast.descr.UnitDescr; +import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl.ast.descr.WindowReferenceDescr; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/* + * This test class is to assert Descr common properties + */ +class DescrCommonPropertyTest { + + private DRLParserWrapper parser; + + @BeforeEach + public void setUp() { + parser = new DRLParserWrapper(); + } + + @AfterEach + public void tearDown() { + } + + private void assertProperties(BaseDescr descr, int startCharacter, int endCharacter, int line, int column, int endLine, int endColumn) { + assertThat(descr.getStartCharacter()).isEqualTo(startCharacter); // first character of the start token. character is 0-based + assertThat(descr.getEndCharacter()).isEqualTo(endCharacter); // last character of the end token. character is 0-based + assertThat(descr.getLine()).isEqualTo(line); // line of the start token. line is 1-based + assertThat(descr.getColumn()).isEqualTo(column); // first column of the start token. column is 0-based + assertThat(descr.getEndLine()).isEqualTo(endLine); // line of the end token. line is 1-based + assertThat(descr.getEndColumn()).isEqualTo(endColumn); // last column of the end token. column is 0-based + } + + @Test + void packageDescr() { + final String source = "package foo.bar.baz"; + final PackageDescr pkg = parser.parse(source); + assertProperties(pkg, 0, 18, 1, 0, 1, 18); + } + + @Test + void ruleDescr() { + final String source = "rule \"MyRule\"\n" + + " when\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + assertProperties(rule, 0, 30, 1, 0, 4, 2); + } + + @Test + void unitDescr() { + final String source = "unit Foo;"; + final PackageDescr pkg = parser.parse(source); + final UnitDescr unit = pkg.getUnit(); + assertProperties(unit, 0, 8, 1, 0, 1, 8); + } + + @Test + void queryDescr() { + final String source = "query \"MyQuery\"\n" + + " Foo()\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final QueryDescr query = (QueryDescr) pkg.getRules().get(0); + assertProperties(query, 0, 26, 1, 0, 3, 2); + } + + @Test + void functionDescr() { + final String source = "function void myFunction(String data) {\n" + + " foo();\n" + + "}"; + final PackageDescr pkg = parser.parse(source); + final FunctionDescr function = pkg.getFunctions().get(0); + assertProperties(function, 0, 49, 1, 0, 3, 0); + } + + @Test + void globalDescr() { + final String source = "global java.util.List myList"; + final PackageDescr pkg = parser.parse(source); + final GlobalDescr global = pkg.getGlobals().get(0); + assertProperties(global, 0, 27, 1, 0, 1, 27); + } + + @Test + void functionImportDescr() { + final String source = "import function org.drools.core.util.DateUtils.*"; + final PackageDescr pkg = parser.parse(source); + final FunctionImportDescr functionImport = pkg.getFunctionImports().get(0); + assertProperties(functionImport, 0, 47, 1, 0, 1, 47); + } + + @Test + void importDescr() { + final String source = "import org.drools.core.util.DateUtils"; + final PackageDescr pkg = parser.parse(source); + final ImportDescr importDescr = pkg.getImports().get(0); + assertProperties(importDescr, 0, 36, 1, 0, 1, 36); + } + + @Test + void accumulateImportDescr() { + final String source = "import accumulate org.example.MyAccUtils.sum mySum"; + final PackageDescr pkg = parser.parse(source); + final AccumulateImportDescr accumulateImport = pkg.getAccumulateImports().get(0); + assertProperties(accumulateImport, 0, 49, 1, 0, 1, 49); + } + + @Test + void typeDeclarationDescr() { + final String source = "declare MyType\n" + + " name : String\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final TypeDeclarationDescr typeDeclaration = pkg.getTypeDeclarations().get(0); + + // startCharacter = 8 looks a little odd ("declare" is not included in the Descr), but it keeps the same as the old implementation. We may change it in the future. + assertProperties(typeDeclaration, 8, 33, 1, 8, 3, 2); + } + + @Test + void entryPointDeclarationDescr() { + final String source = "declare entry-point MyEntryPoint\n" + + " @foo( true )\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final EntryPointDeclarationDescr entryPointDeclaration = pkg.getEntryPointDeclarations().stream().findFirst().get(); + assertProperties(entryPointDeclaration, 8, 50, 1, 8, 3, 2); + } + + @Test + void windowDeclarationDescr() { + final String source = "declare window MyWindow\n" + + " $s : StockTick( source == \"NYSE\" )\n" + + " over window:length( 10, $s.symbol )\n" + + " from entry-point stStream\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final WindowDeclarationDescr windowDeclaration = pkg.getWindowDeclarations().stream().findFirst().get(); + assertProperties(windowDeclaration, 8, 139, 1, 8, 5, 2); + } + + @Test + void annotationDescr() { + final String source = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person( name == \"Mario\" ) @watch(!*, age)\n" + + "then\n" + + "end\n"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + AnnotationDescr annotation = rule.getLhs().getAllPatternDescr().get(0).getAnnotations().stream().findFirst().get(); + assertProperties(annotation, 65, 79, 4, 33, 4, 47); + } + + @Test + void typeFieldDescr() { + final String source = "declare MyType\n" + + " name : String\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final TypeDeclarationDescr typeDeclaration = pkg.getTypeDeclarations().get(0); + TypeFieldDescr typeField = typeDeclaration.getFields().get("name"); + assertProperties(typeField, 17, 29, 2, 2, 2, 14); + } + + @Test + void attributeDescr() { + final String source = "rule R1\n" + + " salience 42\n" + + " agenda-group \"my_group\"\n" + + " when\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + assertProperties(rule.getAttributes().get("salience"), 10, 20, 2, 2, 2, 12); + assertProperties(rule.getAttributes().get("agenda-group"), 24, 46, 3, 2, 3, 24); + } + + @Test + void patternDescr() { + final String source = "rule R1\n" + + " when\n" + + " $p : Person( name == \"Mario\" )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertProperties(pattern, 19, 48, 3, 4, 3, 33); + } + + @Test + void orDescr() { + final String source = "rule R1\n" + + " when\n" + + " ( $p : Person( name == \"Mario\" ) or $p : Person( name == \"Luigi\" ) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertProperties(or, 21, 84, 3, 6, 3, 69); + } + + @Test + void andDescr() { + final String source = "rule R1\n" + + " when\n" + + " ( $p1 : Person( name == \"Mario\" ) and $p2 : Person( name == \"Luigi\" ) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + AndDescr and = rule.getLhs(); + assertProperties(and, 21, 87, 3, 6, 3, 72); + } + + @Test + void forallDescr() { + final String source = "rule R1\n" + + " when\n" + + " forall( $p : Person( name == \"Mario\" ) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0); + assertProperties(forall, 19, 58, 3, 4, 3, 43); + } + + @Test + void accumulateDescr() { + final String source = "rule R1\n" + + " when\n" + + " accumulate( $p : Person( name == \"Mario\" ), $sum : sum($p.getAge()) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + AccumulateDescr accumulate = (AccumulateDescr) pattern.getSource(); + assertProperties(accumulate, 19, 87, 3, 4, 3, 72); + } + + @Test + void behaviorDescr() { + final String source = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end";; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + BehaviorDescr behavior = pattern.getBehaviors().get(0); + + // "over" is not included in BehaviorDescr + assertProperties(behavior, 44, 60, 1, 44, 1, 60); + } + + @Test + void fromDescr() { + final String source = "rule X\n" + + " when\n" + + " Adult( $children : children)\n" + + " Child() from $children\n" + + " then\n" + + "end";; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + FromDescr from = (FromDescr) pattern.getSource(); + + // "from" is not included in FromDescr + assertProperties(from, 64, 72, 4, 17, 4, 25); + } + + @Test + void collectDescr() { + final String source = "rule X\n" + + " when\n" + + " ArrayList() from collect( Person( age > 21 ) );\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + CollectDescr collect = (CollectDescr) pattern.getSource(); + + assertProperties(collect, 35, 63, 3, 21, 3, 49); + } + + @Test + void entryPointDescr() { + final String source = "rule X\n" + + " when\n" + + " StockTick() from entry-point \"stream\"\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + EntryPointDescr entryPoint = (EntryPointDescr) pattern.getSource(); + assertProperties(entryPoint, 35, 54, 3, 21, 3, 40); + } + + @Test + void windowReferenceDescr() { + final String source = "rule X\n" + + " when\n" + + " StockTick() from window MyWindow\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + WindowReferenceDescr windowReference = (WindowReferenceDescr) pattern.getSource(); + assertProperties(windowReference, 35, 49, 3, 21, 3, 35); + } + + @Test + void exprConstraintDescr() { + final String source = "rule X\n" + + " when\n" + + " Person( age > 21 )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraint = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertProperties(exprConstraint, 26, 33, 3, 12, 3, 19); + } + + @Test + void existDescr() { + final String source = "rule X\n" + + " when\n" + + " exists( Person( age > 21 ) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + ExistsDescr exists = (ExistsDescr) rule.getLhs().getDescrs().get(0); + assertProperties(exists, 18, 45, 3, 4, 3, 31); + } + + @Test + void notDescr() { + final String source = "rule X\n" + + " when\n" + + " not( Person( age > 21 ) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(0); + assertProperties(not, 18, 42, 3, 4, 3, 28); + } + + @Test + void evalDescr() { + final String source = "rule X\n" + + " when\n" + + " eval( 1 + 1 == 2 )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parser.parse(source); + final RuleDescr rule = pkg.getRules().get(0); + EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(0); + assertProperties(eval, 18, 35, 3, 4, 3, 21); + } +} 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/DRLParser.g4 index 7d9dd2235fc..6e975bc3fe5 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/DRLParser.g4 @@ -50,7 +50,8 @@ declaredef : DRL_DECLARE ( | entryPointDeclaration | windowDeclaration | typeDeclaration - ) DRL_END SEMI?; + ) + ; // DRL_END belongs to entryPointDeclaration etc. /* * typeDeclaration := [TYPE] qualifiedIdentifier (EXTENDS qualifiedIdentifier)? @@ -59,15 +60,15 @@ declaredef : DRL_DECLARE ( * END */ -typeDeclaration : DRL_TRAIT? name=drlQualifiedName (EXTENDS superTypes+=drlQualifiedName (COMMA superTypes+=drlQualifiedName)* )? drlAnnotation* field* ; +typeDeclaration : DRL_TRAIT? name=drlQualifiedName (EXTENDS superTypes+=drlQualifiedName (COMMA superTypes+=drlQualifiedName)* )? drlAnnotation* field* DRL_END SEMI?; // entryPointDeclaration := ENTRY-POINT stringId annotation* END -entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* ; +entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* DRL_END SEMI?; // windowDeclaration := WINDOW ID annotation* lhsPatternBind END -windowDeclaration : DRL_WINDOW name=IDENTIFIER drlAnnotation* lhsPatternBind ; +windowDeclaration : DRL_WINDOW name=IDENTIFIER drlAnnotation* lhsPatternBind DRL_END SEMI?; // field := label fieldType (EQUALS_ASSIGN conditionalExpression)? annotation* SEMICOLON? diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/BaseDescrFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/BaseDescrFactory.java new file mode 100644 index 00000000000..31fe45747e3 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/BaseDescrFactory.java @@ -0,0 +1,60 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.drools.drl.ast.descr.BaseDescr; + +import static org.drools.drl.parser.antlr4.DescrHelper.populateCommonProperties; + +/** + * Factory class for Descr instantiation. + */ +public class BaseDescrFactory { + + private BaseDescrFactory() { + // Private constructor to prevent instantiation. + } + + public static Builder builder(T toBuild) { + return new Builder<>(toBuild); + } + + public static class Builder { + + T toReturn; + + private Builder(T toBuild) { + this.toReturn = toBuild; + } + + /** + * Initializes a BaseDescr instance with common properties from the given context. + * DRLVisitor implementations should always use this method to initialize BaseDescr instances. + */ + public Builder withParserRuleContext(ParserRuleContext ctx) { + populateCommonProperties(toReturn, ctx); + return this; + } + + public T build() { + return toReturn; + } + } +} 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 84ebe76f56d..846a9bff9e4 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 @@ -87,13 +87,14 @@ public DRLVisitorImpl(TokenStream tokenStream) { */ @Override public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { - PackageDescr packageDescr = new PackageDescr(); + PackageDescr packageDescr = BaseDescrFactory.builder(new PackageDescr()) + .withParserRuleContext(ctx) + .build(); if (ctx.packagedef() != null) { packageDescr.setName(getTextWithoutErrorNode(ctx.packagedef().name)); } List descrList = visitDescrChildren(ctx); applyChildrenDescrs(packageDescr, descrList); - populateStartEnd(packageDescr, ctx); return packageDescr; } @@ -140,46 +141,51 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc @Override public UnitDescr visitUnitdef(DRLParser.UnitdefContext ctx) { - UnitDescr unitDescr = new UnitDescr(ctx.name.getText()); - populateStartEnd(unitDescr, ctx); - return unitDescr; + return BaseDescrFactory.builder(new UnitDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .build(); } @Override public GlobalDescr visitGlobaldef(DRLParser.GlobaldefContext ctx) { - GlobalDescr globalDescr = new GlobalDescr(ctx.drlIdentifier().getText(), ctx.type().getText()); - populateStartEnd(globalDescr, ctx); - return globalDescr; + return BaseDescrFactory.builder(new GlobalDescr(ctx.drlIdentifier().getText(), ctx.type().getText())) + .withParserRuleContext(ctx) + .build(); } @Override public ImportDescr visitImportStandardDef(DRLParser.ImportStandardDefContext ctx) { String target = ctx.drlQualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); if (ctx.DRL_FUNCTION() != null || ctx.STATIC() != null) { - FunctionImportDescr functionImportDescr = new FunctionImportDescr(); + FunctionImportDescr functionImportDescr = BaseDescrFactory.builder(new FunctionImportDescr()) + .withParserRuleContext(ctx) + .build(); functionImportDescr.setTarget(target); - populateStartEnd(functionImportDescr, ctx); return functionImportDescr; } else { - ImportDescr importDescr = new ImportDescr(); + ImportDescr importDescr = BaseDescrFactory.builder(new ImportDescr()) + .withParserRuleContext(ctx) + .build(); importDescr.setTarget(target); - populateStartEnd(importDescr, ctx); return importDescr; } } @Override public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulateDefContext ctx) { - AccumulateImportDescr accumulateImportDescr = new AccumulateImportDescr(); + AccumulateImportDescr accumulateImportDescr = BaseDescrFactory.builder(new AccumulateImportDescr()) + .withParserRuleContext(ctx) + .build(); accumulateImportDescr.setTarget(ctx.drlQualifiedName().getText()); accumulateImportDescr.setFunctionName(ctx.IDENTIFIER().getText()); - populateStartEnd(accumulateImportDescr, ctx); return accumulateImportDescr; } @Override public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { - FunctionDescr functionDescr = new FunctionDescr(); + FunctionDescr functionDescr = BaseDescrFactory.builder(new FunctionDescr()) + .withParserRuleContext(ctx) + .build(); if (ctx.typeTypeOrVoid() != null) { functionDescr.setReturnType(ctx.typeTypeOrVoid().getText()); } else { @@ -199,7 +205,6 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { }); } functionDescr.setBody(getTextPreservingWhitespace(ctx.drlBlock().drlBlockStatement())); - populateStartEnd(functionDescr, ctx); return functionDescr; } @@ -210,7 +215,9 @@ public BaseDescr visitDeclaredef(DRLParser.DeclaredefContext ctx) { @Override public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContext ctx) { - TypeDeclarationDescr typeDeclarationDescr = new TypeDeclarationDescr(ctx.name.getText()); + TypeDeclarationDescr typeDeclarationDescr = BaseDescrFactory.builder(new TypeDeclarationDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .build(); if (ctx.DRL_TRAIT() != null) { typeDeclarationDescr.setTrait(true); } @@ -225,30 +232,31 @@ public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContex ctx.field().stream() .map(this::visitField) .forEach(typeDeclarationDescr::addField); - populateStartEnd(typeDeclarationDescr, ctx); return typeDeclarationDescr; } @Override public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPointDeclarationContext ctx) { - EntryPointDeclarationDescr entryPointDeclarationDescr = new EntryPointDeclarationDescr(); + EntryPointDeclarationDescr entryPointDeclarationDescr = BaseDescrFactory.builder(new EntryPointDeclarationDescr()) + .withParserRuleContext(ctx) + .build(); entryPointDeclarationDescr.setEntryPointId(ctx.name.getText()); ctx.drlAnnotation().stream() .map(this::visitDrlAnnotation) .forEach(entryPointDeclarationDescr::addAnnotation); - populateStartEnd(entryPointDeclarationDescr, ctx); return entryPointDeclarationDescr; } @Override public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclarationContext ctx) { - WindowDeclarationDescr windowDeclarationDescr = new WindowDeclarationDescr(); + WindowDeclarationDescr windowDeclarationDescr = BaseDescrFactory.builder(new WindowDeclarationDescr()) + .withParserRuleContext(ctx) + .build(); windowDeclarationDescr.setName(ctx.name.getText()); ctx.drlAnnotation().stream() .map(this::visitDrlAnnotation) .forEach(windowDeclarationDescr::addAnnotation); windowDeclarationDescr.setPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); - populateStartEnd(windowDeclarationDescr, ctx); return windowDeclarationDescr; } @@ -257,7 +265,9 @@ public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclaration */ @Override public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { - RuleDescr ruleDescr = new RuleDescr(safeStripStringDelimiters(ctx.name.getText())); + RuleDescr ruleDescr = BaseDescrFactory.builder(new RuleDescr(safeStripStringDelimiters(ctx.name.getText()))) + .withParserRuleContext(ctx) + .build(); if (ctx.EXTENDS() != null) { ruleDescr.setParentName(safeStripStringDelimiters(ctx.parentName.getText())); @@ -274,9 +284,11 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { } if (ctx.lhs() != null) { + final AndDescr rootDescr = ruleDescr.getLhs(); List lhsDescrList = visitLhs(ctx.lhs()); - lhsDescrList.forEach(descr -> ruleDescr.getLhs().addDescr(descr)); - slimLhsRootDescr(ruleDescr.getLhs()); + lhsDescrList.forEach(descr -> rootDescr.addDescr(descr)); + slimLhsRootDescr(rootDescr); + DescrHelper.refreshRootProperties(rootDescr); } if (ctx.rhs() != null) { @@ -284,7 +296,6 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { ruleDescr.setConsequence(trimThen(getTokenTextPreservingWhitespace(ctx.rhs(), tokenStream))); // RHS is just a text } - populateStartEnd(ruleDescr, ctx); return ruleDescr; } @@ -307,7 +318,9 @@ private void slimLhsRootDescr(AndDescr root) { @Override public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { - QueryDescr queryDescr = new QueryDescr(safeStripStringDelimiters(ctx.name.getText())); + QueryDescr queryDescr = BaseDescrFactory.builder(new QueryDescr(safeStripStringDelimiters(ctx.name.getText()))) + .withParserRuleContext(ctx) + .build(); DRLParser.ParametersContext parametersContext = ctx.parameters(); if (parametersContext != null) { @@ -327,13 +340,14 @@ public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { slimLhsRootDescr(queryDescr.getLhs()); - populateStartEnd(queryDescr, ctx); return queryDescr; } @Override public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { - AnnotationDescr annotationDescr = new AnnotationDescr(ctx.name.getText()); + AnnotationDescr annotationDescr = BaseDescrFactory.builder(new AnnotationDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .build(); if (ctx.drlElementValue() != null) { annotationDescr.setValue(getTextPreservingWhitespace(ctx.drlElementValue())); // single value } else if (ctx.drlElementValuePairs() != null) { @@ -342,13 +356,14 @@ public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { // A chunk that is neither a single value nor a list of key-value pairs. For example `!*, age` in `@watch(!*, age)`. annotationDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); } - populateStartEnd(annotationDescr, ctx); return annotationDescr; } @Override public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { - TypeFieldDescr typeFieldDescr = new TypeFieldDescr(); + TypeFieldDescr typeFieldDescr = BaseDescrFactory.builder(new TypeFieldDescr()) + .withParserRuleContext(ctx) + .build(); typeFieldDescr.setFieldName(ctx.label().drlIdentifier().getText()); typeFieldDescr.setPattern(new PatternDescr(ctx.type().getText())); if (ctx.ASSIGN() != null) { @@ -357,7 +372,6 @@ public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { ctx.drlAnnotation().stream() .map(this::visitDrlAnnotation) .forEach(typeFieldDescr::addAnnotation); - populateStartEnd(typeFieldDescr, ctx); return typeFieldDescr; } @@ -371,40 +385,44 @@ private void visitDrlElementValuePairs(DRLParser.DrlElementValuePairsContext ctx @Override public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .build(); attributeDescr.setValue(getTextPreservingWhitespace(ctx.conditionalOrExpression())); attributeDescr.setType(AttributeDescr.Type.EXPRESSION); - populateStartEnd(attributeDescr, ctx); return attributeDescr; } @Override public AttributeDescr visitBooleanAttribute(DRLParser.BooleanAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .build(); attributeDescr.setValue(ctx.BOOL_LITERAL() != null ? ctx.BOOL_LITERAL().getText() : "true"); attributeDescr.setType(AttributeDescr.Type.BOOLEAN); - populateStartEnd(attributeDescr, ctx); return attributeDescr; } @Override public AttributeDescr visitStringAttribute(DRLParser.StringAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .build(); attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.DRL_STRING_LITERAL().getText()))); attributeDescr.setType(AttributeDescr.Type.STRING); - populateStartEnd(attributeDescr, ctx); return attributeDescr; } @Override public AttributeDescr visitStringListAttribute(DRLParser.StringListAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .build(); List valueList = ctx.DRL_STRING_LITERAL().stream() .map(ParseTree::getText) .collect(Collectors.toList()); attributeDescr.setValue(createStringList(valueList)); attributeDescr.setType(AttributeDescr.Type.LIST); - populateStartEnd(attributeDescr, ctx); return attributeDescr; } @@ -423,7 +441,9 @@ private static String createStringList(List valueList) { @Override public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .build(); if (ctx.DECIMAL_LITERAL() != null) { attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); attributeDescr.setType(AttributeDescr.Type.NUMBER); @@ -431,13 +451,14 @@ public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeCont attributeDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); attributeDescr.setType(AttributeDescr.Type.EXPRESSION); } - populateStartEnd(attributeDescr, ctx); return attributeDescr; } @Override public AttributeDescr visitDurationAttribute(DRLParser.DurationAttributeContext ctx) { - AttributeDescr attributeDescr = new AttributeDescr(ctx.name.getText()); + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .build(); if (ctx.DECIMAL_LITERAL() != null) { attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); attributeDescr.setType(AttributeDescr.Type.NUMBER); @@ -445,7 +466,6 @@ public AttributeDescr visitDurationAttribute(DRLParser.DurationAttributeContext attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.TIME_INTERVAL().getText()))); attributeDescr.setType(AttributeDescr.Type.EXPRESSION); } - populateStartEnd(attributeDescr, ctx); return attributeDescr; } @@ -485,11 +505,14 @@ private PatternDescr getSinglePatternDescr(DRLParser.LhsPatternBindContext ctx) patternDescr.setIdentifier(ctx.unif().IDENTIFIER().getText()); patternDescr.setUnification(true); } + DescrHelper.refreshPatternDescrProperties(patternDescr, ctx); return patternDescr; } private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindContext ctx) { - OrDescr orDescr = new OrDescr(); + OrDescr orDescr = BaseDescrFactory.builder(new OrDescr()) + .withParserRuleContext(ctx) + .build(); List descrList = visitDescrChildren(ctx); descrList.stream() .filter(PatternDescr.class::isInstance) @@ -501,7 +524,6 @@ private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindConte orDescr.addDescr(patternDescr); }); - populateStartEnd(orDescr, ctx); return orDescr; } @@ -510,7 +532,9 @@ private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindConte */ @Override public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { - PatternDescr patternDescr = new PatternDescr(ctx.objectType.getText()); + PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr(ctx.objectType.getText())) + .withParserRuleContext(ctx) + .build(); if (ctx.QUESTION() != null) { patternDescr.setQuery(true); } @@ -523,8 +547,6 @@ public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { patternDescr.setSource(patternSourceDescr); } - populateStartEnd(patternDescr, ctx); - ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(patternDescr::addAnnotation); List constraintDescrList = visitConstraints(ctx.positionalConstraints(), ctx.constraints()); constraintDescrList.forEach(descr -> addToPatternDescr(patternDescr, descr)); @@ -538,15 +560,18 @@ private void addToPatternDescr(PatternDescr patternDescr, ExprConstraintDescr ex @Override public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { - ForallDescr forallDescr = new ForallDescr(); + ForallDescr forallDescr = BaseDescrFactory.builder(new ForallDescr()) + .withParserRuleContext(ctx) + .build(); visitDescrChildren(ctx).forEach(forallDescr::addDescr); - populateStartEnd(forallDescr, ctx); return forallDescr; } @Override public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { - AccumulateDescr accumulateDescr = new AccumulateDescr(); + AccumulateDescr accumulateDescr = BaseDescrFactory.builder(new AccumulateDescr()) + .withParserRuleContext(ctx) + .build(); accumulateDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); // accumulate function @@ -559,41 +584,45 @@ public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { List constraintDescrList = visitConstraints(ctx.constraints()); constraintDescrList.forEach(patternDescr::addConstraint); - populateStartEnd(accumulateDescr, ctx); return patternDescr; } @Override public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { - BehaviorDescr behaviorDescr = new BehaviorDescr(); + BehaviorDescr behaviorDescr = BaseDescrFactory.builder(new BehaviorDescr()) + .withParserRuleContext(ctx) + .build(); behaviorDescr.setType(ctx.DRL_WINDOW().getText()); behaviorDescr.setSubType(ctx.IDENTIFIER().getText()); List drlExpressionContexts = ctx.expressionList().drlExpression(); List parameters = drlExpressionContexts.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); behaviorDescr.setParameters(parameters); - populateStartEnd(behaviorDescr, ctx); return behaviorDescr; } @Override public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { - FromDescr fromDescr = new FromDescr(); + FromDescr fromDescr = BaseDescrFactory.builder(new FromDescr()) + .withParserRuleContext(ctx) + .build(); fromDescr.setDataSource(new MVELExprDescr(getTextPreservingWhitespace(ctx))); - populateStartEnd(fromDescr, ctx); return fromDescr; } @Override public CollectDescr visitFromCollect(DRLParser.FromCollectContext ctx) { - CollectDescr collectDescr = new CollectDescr(); + CollectDescr collectDescr = BaseDescrFactory.builder(new CollectDescr()) + .withParserRuleContext(ctx) + .build(); collectDescr.setInputPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); - populateStartEnd(collectDescr, ctx); return collectDescr; } @Override public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) { - AccumulateDescr accumulateDescr = new AccumulateDescr(); + AccumulateDescr accumulateDescr = BaseDescrFactory.builder(new AccumulateDescr()) + .withParserRuleContext(ctx) + .build(); accumulateDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); if (ctx.DRL_INIT() != null) { // inline custom accumulate @@ -607,7 +636,6 @@ public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) // accumulate function accumulateDescr.addFunction(visitAccumulateFunction(ctx.accumulateFunction())); } - populateStartEnd(accumulateDescr, ctx); return accumulateDescr; } @@ -621,12 +649,16 @@ public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLPa @Override public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) { - return new EntryPointDescr(safeStripStringDelimiters(ctx.stringId().getText())); + return BaseDescrFactory.builder(new EntryPointDescr(safeStripStringDelimiters(ctx.stringId().getText()))) + .withParserRuleContext(ctx) + .build(); } @Override public WindowReferenceDescr visitFromWindow(DRLParser.FromWindowContext ctx) { - return new WindowReferenceDescr(ctx.IDENTIFIER().getText()); + return BaseDescrFactory.builder(new WindowReferenceDescr(ctx.IDENTIFIER().getText())) + .withParserRuleContext(ctx) + .build(); } /** @@ -678,9 +710,10 @@ public List visitConstraint(DRLParser.ConstraintContext ctx // get a simple constraint as String String constraint = visitConstraintChildren(ctx); if (!constraint.isEmpty()) { - ExprConstraintDescr constraintDescr = new ExprConstraintDescr(constraint); + ExprConstraintDescr constraintDescr = BaseDescrFactory.builder(new ExprConstraintDescr(constraint)) + .withParserRuleContext(ctx) + .build(); constraintDescr.setType(ExprConstraintDescr.Type.NAMED); - populateStartEnd(constraintDescr, ctx); descrList.add(constraintDescr); return descrList; } @@ -711,7 +744,9 @@ public String visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { @Override public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { - ExistsDescr existsDescr = new ExistsDescr(); + ExistsDescr existsDescr = BaseDescrFactory.builder(new ExistsDescr()) + .withParserRuleContext(ctx) + .build(); if (ctx.lhsExpression() != null) { // exists( A() or B() ) List baseDescrs = visitDescrChildren(ctx); @@ -725,13 +760,14 @@ public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); existsDescr.addDescr(descr); } - populateStartEnd(existsDescr, ctx); return existsDescr; } @Override public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { - NotDescr notDescr = new NotDescr(); + NotDescr notDescr = BaseDescrFactory.builder(new NotDescr()) + .withParserRuleContext(ctx) + .build(); if (ctx.lhsExpression() != null) { // not ( A() or B() ) List baseDescrs = visitDescrChildren(ctx); @@ -745,15 +781,14 @@ public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); notDescr.addDescr(descr); } - populateStartEnd(notDescr, ctx); return notDescr; } @Override public EvalDescr visitLhsEval(DRLParser.LhsEvalContext ctx) { - EvalDescr evalDescr = new EvalDescr(getTextPreservingWhitespace(ctx.conditionalOrExpression())); - populateStartEnd(evalDescr, ctx); - return evalDescr; + return BaseDescrFactory.builder(new EvalDescr(getTextPreservingWhitespace(ctx.conditionalOrExpression()))) + .withParserRuleContext(ctx) + .build(); } @Override @@ -770,7 +805,9 @@ public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { // Avoid nested OrDescr return descrList.get(0).getDescr(); } else { - OrDescr orDescr = new OrDescr(); + OrDescr orDescr = BaseDescrFactory.builder(new OrDescr()) + .withParserRuleContext(ctx) + .build(); // For example, in case of A() or B() or C(), // Parser creates AST like this: // lhsOr @@ -781,7 +818,6 @@ public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { // So, we need to flatten it so that OrDescr has A(), B() and C() as children. List flattenedDescrs = flattenOrDescr(descrList); flattenedDescrs.forEach(orDescr::addDescr); - populateStartEnd(orDescr, ctx); return orDescr; } } @@ -813,7 +849,9 @@ private BaseDescr createAndDescr(ParserRuleContext ctx) { // Avoid nested AndDescr return descrList.get(0).getDescr(); } else { - AndDescr andDescr = new AndDescr(); + AndDescr andDescr = BaseDescrFactory.builder(new AndDescr()) + .withParserRuleContext(ctx) + .build(); // For example, in case of A() and B() and C(), // Parser creates AST like this: // lhsAnd @@ -824,7 +862,6 @@ private BaseDescr createAndDescr(ParserRuleContext ctx) { // So, we need to flatten it so that AndDescr has A(), B() and C() as children. List flattenedDescrs = flattenAndDescr(descrList); flattenedDescrs.forEach(andDescr::addDescr); - populateStartEnd(andDescr, ctx); return andDescr; } } @@ -854,15 +891,6 @@ public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { return visitDescrChildren(ctx).get(0); // lhsUnary has only one child } - private void populateStartEnd(BaseDescr descr, ParserRuleContext ctx) { - descr.setStartCharacter(ctx.getStart().getStartIndex()); - // TODO: Current DRL6Parser adds +1 for EndCharacter but it doesn't look reasonable. At the moment, I don't add. Instead, I fix unit tests. - // I will revisit if this is the right approach. - descr.setEndCharacter(ctx.getStop().getStopIndex()); - descr.setLocation(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); - descr.setEndLocation(ctx.getStop().getLine(), ctx.getStop().getCharPositionInLine()); - } - /** * This is a special version of visitChildren(). * This collects children BaseDescr objects and returns them as a list. 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 new file mode 100644 index 00000000000..9cdc65b94dc --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DescrHelper.java @@ -0,0 +1,70 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.List; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.PatternDescr; + +/** + * Helper class for Descr manipulation. + */ +public class DescrHelper { + + private DescrHelper() { + // Private constructor to prevent instantiation. + } + + public static T populateCommonProperties(T descr, ParserRuleContext ctx) { + descr.setStartCharacter(ctx.getStart().getStartIndex()); + // TODO: Current DRL6Parser adds +1 for EndCharacter but it doesn't look reasonable. At the moment, I don't add. Instead, I fix unit tests. + // I will revisit if this is the right approach. + descr.setEndCharacter(ctx.getStop().getStopIndex()); + descr.setLocation(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); + descr.setEndLocation(ctx.getStop().getLine(), ctx.getStop().getCharPositionInLine() + ctx.getStop().getText().length() - 1); // last column of the end token + return descr; + } + + /** + * LHS rootDescr requires special handling for properties, because it rearranges its children. + */ + public static AndDescr refreshRootProperties(AndDescr descr) { + List childDescrs = descr.getDescrs(); + if (childDescrs.isEmpty()) { + return descr; + } + BaseDescr firstChild = childDescrs.get(0); + BaseDescr lastChild = childDescrs.get(childDescrs.size() - 1); + descr.setStartCharacter(firstChild.getStartCharacter()); + descr.setEndCharacter(lastChild.getEndCharacter()); + descr.setLocation(firstChild.getLine(), firstChild.getColumn()); + descr.setEndLocation(lastChild.getEndLine(), lastChild.getEndColumn()); + return descr; + } + + /** + * PatternDescr requires special handling for properties, because it should be updated with PatternBindContext. e.g. label + */ + public static PatternDescr refreshPatternDescrProperties(PatternDescr descr, DRLParser.LhsPatternBindContext ctx) { + return populateCommonProperties(descr, ctx); + } +} From 6578d91c4c87afd4a4e1e0d151722d84e7c6bc61 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 11 Apr 2024 10:56:46 +0900 Subject: [PATCH 085/141] =?UTF-8?q?[incubator-kie-drools-5716]=20[new-pars?= =?UTF-8?q?er]=20mismatched=20input=20'if'/'do'=20(=E2=80=A6=20(#5831)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5716] [new-parser] mismatched input 'if'/'do' (support named consequences) * Update drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 Co-authored-by: Jiří Locker * Update drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java Co-authored-by: Jiří Locker * resolve duplicate difinition --------- Co-authored-by: Jiří Locker --- .../drl/parser/antlr4/MiscDRLParserTest.java | 171 ++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLLexer.g4 | 2 + .../org/drools/drl/parser/antlr4/DRLParser.g4 | 49 +++-- .../antlr4/Antlr4ParserStringUtils.java | 10 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 94 +++++++++- 5 files changed, 302 insertions(+), 24 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 2d213238287..5e3cf7c6afe 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 @@ -19,6 +19,7 @@ import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.BehaviorDescr; import org.drools.drl.ast.descr.CollectDescr; +import org.drools.drl.ast.descr.ConditionalBranchDescr; import org.drools.drl.ast.descr.EntryPointDeclarationDescr; import org.drools.drl.ast.descr.EntryPointDescr; import org.drools.drl.ast.descr.EvalDescr; @@ -30,6 +31,7 @@ import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.ImportDescr; import org.drools.drl.ast.descr.MVELExprDescr; +import org.drools.drl.ast.descr.NamedConsequenceDescr; import org.drools.drl.ast.descr.NotDescr; import org.drools.drl.ast.descr.OrDescr; import org.drools.drl.ast.descr.PackageDescr; @@ -3997,4 +3999,173 @@ public void traitExtendsMultiple() throws Exception { .map(QualifiedName::getFullName) .containsExactlyInAnyOrder("com.sample.ParentTrait", "UncleTrait", "org.test.GrandParentTrait"); } + + @Test + void namedConsequenceDo() { + final String text = + "rule R when\n" + + " $r : Result()\n" + + " $p1 : Person(name == \"Mark\")\n" + + " do[FoundMark]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"Found \" + $p1.getName());\n" + + "end"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMark"); + + assertThat(ruleDescr.getConsequence().toString()).isEqualTo("$r.addValue($p2.getName() + \" is older than \" + $p1.getName());"); + assertThat(ruleDescr.getNamedConsequences().get("FoundMark").toString()).isEqualTo("$r.addValue(\"Found \" + $p1.getName());"); + } + + @Test + void namedConsequenceIfElse() { + final String text = + "rule R1 dialect \"mvel\" when\n" + + " $a: Cheese ( type == \"stilton\" )\n" + + " if ( $a.price > Cheese.BASE_PRICE ) do[t1] else do[t2]\n" + + " $b: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $b.getType() );\n" + + "then[t1]\n" + + " results.add( $a.getType() );\n" + + "then[t2]\n" + + " results.add( $a.getType().toUpperCase() );\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(1); + assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); + assertThat(conditionalBranchDescr.getConsequence().getName()).isEqualTo("t1"); + assertThat(conditionalBranchDescr.getElseBranch().getConsequence().getName()).isEqualTo("t2"); + } + + @Test + void namedConsequenceIfElseBreak() { + final String text = + "rule R1 dialect \"mvel\" when\n" + + " $a: Cheese ( type == \"stilton\" )\n" + + " if ( $a.price > Cheese.BASE_PRICE ) break[t1] else break[t2]\n" + + " $b: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $b.getType() );\n" + + "then[t1]\n" + + " results.add( $a.getType() );\n" + + "then[t2]\n" + + " results.add( $a.getType().toUpperCase() );\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(1); + assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); + assertThat(conditionalBranchDescr.getConsequence().getName()).isEqualTo("t1"); + assertThat(conditionalBranchDescr.getElseBranch().getConsequence().getName()).isEqualTo("t2"); + } + + @Test + void namedConsequenceNestedIf() { + final String text = + "rule R1 dialect \"mvel\" when\n" + + " $a: Cheese ( type == \"stilton\" )\n" + + " if ( $a.price > Cheese.BASE_PRICE ) do[t1] else if ($a.price == Cheese.BASE_PRICE ) do[t2]\n" + + " $b: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $b.getType() );\n" + + "then[t1]\n" + + " results.add( $a.getType() );\n" + + "then[t2]\n" + + " results.add( $a.getType().toUpperCase() );\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(1); + assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); + assertThat(conditionalBranchDescr.getConsequence().getName()).isEqualTo("t1"); + ConditionalBranchDescr elseBranch = conditionalBranchDescr.getElseBranch(); + assertThat(elseBranch.getCondition().getContent().toString()).isEqualTo("$a.price == Cheese.BASE_PRICE"); + assertThat(elseBranch.getConsequence().getName()).isEqualTo("t2"); + } + + @Test + void namedConsequenceAfterExists() { + final String text = + "rule R when\n" + + " $r : Result()\n" + + " exists( Person(name == \"Mark\") )\n" + + " do[FoundMark]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"Found \" + $p1.getName());\n" + + "end"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMark"); + } + + @Test + void namedConsequenceAfterNot() { + final String text = + "rule R when\n" + + " $r : Result()\n" + + " not( Person(name == \"Mark\") )\n" + + " do[NotFoundMark]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"NotFound \" + $p1.getName());\n" + + "end"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(namedConsequenceDescr.getName()).isEqualTo("NotFoundMark"); + } + + @Test + void namedConsequenceIfElseAfterEval() { + final String text = + "rule R1 dialect \"mvel\" when\n" + + " $a: Cheese ( type == \"stilton\" )\n" + + " eval($a.price > 0) if ( $a.price > Cheese.BASE_PRICE ) do[t1] else do[t2]\n" + + " $b: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $b.getType() );\n" + + "then[t1]\n" + + " results.add( $a.getType() );\n" + + "then[t2]\n" + + " results.add( $a.getType().toUpperCase() );\n" + + "end\n"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); + assertThat(conditionalBranchDescr.getConsequence().getName()).isEqualTo("t1"); + assertThat(conditionalBranchDescr.getElseBranch().getConsequence().getName()).isEqualTo("t2"); + } + + @Test + void namedConsequenceAfterEnclosed() { + final String text = + "rule R when\n" + + " $r : Result()\n" + + " ( Person(name == \"Mark\") or Person(name == \"Mario\") )\n" + + " do[FoundMarkOrMario]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"Found \" + $p1.getName());\n" + + "end"; + PackageDescr packageDescr = parser.parse(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMarkOrMario"); + } } 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/DRLLexer.g4 index dc974ecac82..631d2a49a18 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/DRLLexer.g4 @@ -172,6 +172,8 @@ RHS_STRING_LITERAL | ('\'' ( DrlEscapeSequence | ~('\\'|'\'') )* '\'') { setText( normalizeString( getText() ) ); } ; +RHS_NAMED_CONSEQUENCE_THEN : DRL_THEN LBRACK IDENTIFIER RBRACK ; + RHS_CHUNK : ~[ ()[\]{},;\t\r\n\u000C]+ // ;}) could be a delimitter proceding 'end'. ()[]{},; are delimiters to match RHS_STRING_LITERAL | LPAREN 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/DRLParser.g4 index 6e975bc3fe5..e5cfc957cc6 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/DRLParser.g4 @@ -90,12 +90,12 @@ parameter : type? drlIdentifier ; // type is optional. Removed (LEFT_SQUARE RIGH lhs : DRL_WHEN lhsExpression* ; -lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed - | lhsUnary #lhsUnarySingle - | LPAREN DRL_AND lhsExpression+ RPAREN #lhsAnd - | lhsExpression (DRL_AND lhsExpression)+ #lhsAnd - | LPAREN DRL_OR lhsExpression+ RPAREN #lhsOr - | lhsExpression (DRL_OR lhsExpression)+ #lhsOr +lhsExpression : LPAREN lhsExpression RPAREN namedConsequenceInvocation? #lhsExpressionEnclosed + | lhsUnary #lhsUnarySingle + | LPAREN DRL_AND lhsExpression+ RPAREN #lhsAnd + | lhsExpression (DRL_AND lhsExpression)+ #lhsAnd + | LPAREN DRL_OR lhsExpression+ RPAREN #lhsOr + | lhsExpression (DRL_OR lhsExpression)+ #lhsOr ; // lhsAnd is used as a label in lhsExpression rule. But some other rules explicitly use the def, so lhsAndDef is declared. @@ -110,18 +110,19 @@ lhsUnary : ( lhsExists namedConsequence? | lhsEval consequenceInvocation* | lhsForall | lhsAccumulate - | LPAREN lhsOr RPAREN namedConsequence? + | LPAREN lhsOr RPAREN namedConsequence? // this part is handled by #lhsExpressionEnclosed | lhsPatternBind consequenceInvocation* ) SEMI? ; */ lhsUnary : ( - lhsExists - | lhsNot - | lhsEval + lhsExists namedConsequenceInvocation? + | lhsNot namedConsequenceInvocation? + | lhsEval consequenceInvocation* | lhsForall | lhsAccumulate - | lhsPatternBind + | conditionalBranch // not in the above old parser definition, but actually implemented in the old parser + | lhsPatternBind consequenceInvocation* ) SEMI? ; lhsPatternBind : (label|unif)? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; @@ -157,6 +158,25 @@ xpathPrimary : label? xpathChunk+ ; xpathChunk : xpathSeparator drlIdentifier (DOT drlIdentifier)* (HASH drlIdentifier)? (LBRACK xpathExpressionList RBRACK)? ; xpathExpressionList : label? drlExpression (COMMA label? drlExpression)* ; +// named consequence + +// consequenceInvocation := conditionalBranch | namedConsequence +consequenceInvocation : conditionalBranch | namedConsequenceInvocation ; + +// conditionalBranch := IF LEFT_PAREN conditionalExpression RIGHT_PAREN +// ( namedConsequence | breakingNamedConsequence ) +// ( ELSE ( namedConsequence | breakingNamedConsequence | conditionalBranch ) )? +conditionalBranch : IF LPAREN conditionalOrExpression RPAREN + ( do1=namedConsequenceInvocation | break1=breakingNamedConsequenceInvocation ) + ( ELSE ( do2=namedConsequenceInvocation | break2=breakingNamedConsequenceInvocation | conditionalBranch ) )? ; + +// namedConsequence := DO LEFT_SQUARE ID RIGHT_SQUARE BREAK? +namedConsequenceInvocation : DO LBRACK drlIdentifier RBRACK ; // BREAK? is not actually implmented in the old parser + +// breakingNamedConsequence := BREAK LEFT_SQUARE ID RIGHT_SQUARE +breakingNamedConsequenceInvocation : BREAK LBRACK drlIdentifier RBRACK ; + + relationalOperator : EQUAL | NOTEQUAL @@ -488,9 +508,12 @@ lhsAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) RPAREN (SEMI)? ; -rhs : DRL_THEN consequence ; +rhs : DRL_THEN consequenceBody namedConsequence* ; + +consequenceBody : ( RHS_STRING_LITERAL | RHS_CHUNK )* ; -consequence : ( RHS_STRING_LITERAL | RHS_CHUNK )* ; +// THEN LEFT_SQUARE ID RIGHT_SQUARE chunk +namedConsequence : RHS_NAMED_CONSEQUENCE_THEN consequenceBody ; stringId : ( IDENTIFIER | DRL_STRING_LITERAL ) ; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java index 86e841cc128..a33eb143dd8 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java @@ -66,13 +66,13 @@ public static String getTokenTextPreservingWhitespace(ParserRuleContext ctx, Tok } /** - * Just remove leading "then" + * Extract name from "then[name]" of RHS_NAMED_CONSEQUENCE_THEN */ - public static String trimThen(String rhs) { - if (rhs.startsWith("then")) { - return rhs.substring("then".length()); + public static String extractNamedConsequenceName(String namedConsequenceThen) { + if (namedConsequenceThen.toLowerCase().startsWith("then[") && namedConsequenceThen.endsWith("]")) { + return namedConsequenceThen.substring("then[".length(), namedConsequenceThen.length() - 1); } else { - throw new DRLParserException("rhs has to start with 'then' : rhs = " + rhs); + throw new DRLParserException("namedConsequenceThen has to be surrounded by 'then[', ']' : " + namedConsequenceThen); } } 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 846a9bff9e4..ba9157897ec 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 @@ -35,6 +35,7 @@ import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.BehaviorDescr; import org.drools.drl.ast.descr.CollectDescr; +import org.drools.drl.ast.descr.ConditionalBranchDescr; import org.drools.drl.ast.descr.EntryPointDeclarationDescr; import org.drools.drl.ast.descr.EntryPointDescr; import org.drools.drl.ast.descr.EvalDescr; @@ -47,6 +48,7 @@ import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.ImportDescr; import org.drools.drl.ast.descr.MVELExprDescr; +import org.drools.drl.ast.descr.NamedConsequenceDescr; import org.drools.drl.ast.descr.NotDescr; import org.drools.drl.ast.descr.OrDescr; import org.drools.drl.ast.descr.PackageDescr; @@ -60,9 +62,9 @@ import org.drools.drl.ast.descr.WindowDeclarationDescr; import org.drools.drl.ast.descr.WindowReferenceDescr; +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.Antlr4ParserStringUtils.trimThen; import static org.drools.drl.parser.antlr4.DRLParserHelper.getTextWithoutErrorNode; import static org.drools.drl.parser.util.ParserStringUtils.appendPrefix; import static org.drools.drl.parser.util.ParserStringUtils.safeStripStringDelimiters; @@ -292,8 +294,17 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { } if (ctx.rhs() != null) { + // default consequence ruleDescr.setConsequenceLocation(ctx.rhs().getStart().getLine(), ctx.rhs().getStart().getCharPositionInLine()); // location of "then" - ruleDescr.setConsequence(trimThen(getTokenTextPreservingWhitespace(ctx.rhs(), tokenStream))); // RHS is just a text + ruleDescr.setConsequence(getTokenTextPreservingWhitespace(ctx.rhs().consequenceBody(), tokenStream)); // RHS is just a text + + // named consequences + ctx.rhs().namedConsequence() + .forEach(namedConsequenceCtx -> { + String name = extractNamedConsequenceName(namedConsequenceCtx.RHS_NAMED_CONSEQUENCE_THEN().getText()); + String body = getTokenTextPreservingWhitespace(namedConsequenceCtx.consequenceBody(), tokenStream); + ruleDescr.addNamedConsequences(name, body); + } ); } return ruleDescr; @@ -558,6 +569,74 @@ private void addToPatternDescr(PatternDescr patternDescr, ExprConstraintDescr ex patternDescr.addConstraint(exprConstraintDescr); } + @Override + public NamedConsequenceDescr visitNamedConsequenceInvocation(DRLParser.NamedConsequenceInvocationContext ctx) { + NamedConsequenceDescr namedConsequenceDescr = BaseDescrFactory.builder(new NamedConsequenceDescr(ctx.drlIdentifier().getText())) + .withParserRuleContext(ctx) + .build(); + return namedConsequenceDescr; + } + + @Override + public NamedConsequenceDescr visitBreakingNamedConsequenceInvocation(DRLParser.BreakingNamedConsequenceInvocationContext ctx) { + NamedConsequenceDescr namedConsequenceDescr = BaseDescrFactory.builder(new NamedConsequenceDescr(ctx.drlIdentifier().getText())) + .withParserRuleContext(ctx) + .build(); + namedConsequenceDescr.setBreaking(true); + return namedConsequenceDescr; + } + + /** + * process + * + * if (condition) do[namedConsequence1] else do[namedConsequence2] + * + * into a ConditionalBranchDescr + */ + @Override + public ConditionalBranchDescr visitConditionalBranch(DRLParser.ConditionalBranchContext ctx) { + ConditionalBranchDescr conditionalBranchDescr = BaseDescrFactory.builder(new ConditionalBranchDescr()) + .withParserRuleContext(ctx) + .build(); + EvalDescr evalDescr = BaseDescrFactory.builder(new EvalDescr()) + .withParserRuleContext(ctx.conditionalOrExpression()) + .build(); + evalDescr.setContent(getTextPreservingWhitespace(ctx.conditionalOrExpression())); + conditionalBranchDescr.setCondition(evalDescr); + + // main branch + if (ctx.do1 != null) { + NamedConsequenceDescr namedConsequenceDescr = visitNamedConsequenceInvocation(ctx.do1); + conditionalBranchDescr.setConsequence(namedConsequenceDescr); + } else if (ctx.break1 != null) { + NamedConsequenceDescr namedConsequenceDescr = visitBreakingNamedConsequenceInvocation(ctx.break1); + conditionalBranchDescr.setConsequence(namedConsequenceDescr); + } + + // else branch + if (ctx.do2 != null) { + ConditionalBranchDescr elseBranchDescr = BaseDescrFactory.builder(new ConditionalBranchDescr()) + .withParserRuleContext(ctx.do2) + .build(); + conditionalBranchDescr.setElseBranch(elseBranchDescr); + NamedConsequenceDescr namedConsequenceDescr = visitNamedConsequenceInvocation(ctx.do2); + elseBranchDescr.setConsequence(namedConsequenceDescr); + } else if (ctx.break2 != null) { + ConditionalBranchDescr elseBranchDescr = BaseDescrFactory.builder(new ConditionalBranchDescr()) + .withParserRuleContext(ctx.break2) + .build(); + conditionalBranchDescr.setElseBranch(elseBranchDescr); + NamedConsequenceDescr namedConsequenceDescr = visitBreakingNamedConsequenceInvocation(ctx.break2); + elseBranchDescr.setConsequence(namedConsequenceDescr); + } else if (ctx.conditionalBranch() != null) { + // nested if + ConditionalBranchDescr nestedConditionalBranchDescr = visitConditionalBranch(ctx.conditionalBranch()); + conditionalBranchDescr.setElseBranch(nestedConditionalBranchDescr); + } + + return conditionalBranchDescr; + } + @Override public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { ForallDescr forallDescr = BaseDescrFactory.builder(new ForallDescr()) @@ -792,9 +871,9 @@ public EvalDescr visitLhsEval(DRLParser.LhsEvalContext ctx) { } @Override - public BaseDescr visitLhsExpressionEnclosed(DRLParser.LhsExpressionEnclosedContext ctx) { + public List visitLhsExpressionEnclosed(DRLParser.LhsExpressionEnclosedContext ctx) { // enclosed expression is simply stripped because Descr itself is encapsulated - return (BaseDescr) visit(ctx.lhsExpression()); + return visitDescrChildren(ctx); } @Override @@ -887,8 +966,8 @@ public BaseDescr visitLhsAndDef(DRLParser.LhsAndDefContext ctx) { } @Override - public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { - return visitDescrChildren(ctx).get(0); // lhsUnary has only one child + public List visitLhsUnary(DRLParser.LhsUnaryContext ctx) { + return visitDescrChildren(ctx); // lhsUnary may have consequenceInvocation, so not always a single child } /** @@ -924,6 +1003,9 @@ private List visitDescrChildrenForDescrNodePair(RuleNode node) { Object childResult = c.accept(this); if (childResult instanceof BaseDescr) { aggregator.add(new DescrNodePair((BaseDescr) childResult, c)); // pairing the returned Descr and the parser node + } else if (childResult instanceof List) { + List descrList = (List) childResult; + descrList.forEach(descr -> aggregator.add(new DescrNodePair(descr, c))); // pairing the returned Descr and the parser node } } return aggregator; From 371d5158adfdff600ed2b9f3a8cf776bf7643c4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Mon, 15 Apr 2024 07:33:16 +0200 Subject: [PATCH 086/141] [new-parser] Support pluggable evaluators and class literal (#5834) * Support isA operator and pluggable evaluators in general * Support class literals * Clean up drlPrimary rule --- .../drl/parser/antlr4/MiscDRLParserTest.java | 16 ++++++++++ .../drl/parser/antlr4/DRL6Expressions.g4 | 2 +- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 29 +++++++++++++++++-- 3 files changed, 43 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 5e3cf7c6afe..2f98ddea42c 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 @@ -4000,6 +4000,22 @@ public void traitExtendsMultiple() throws Exception { .containsExactlyInAnyOrder("com.sample.ParentTrait", "UncleTrait", "org.test.GrandParentTrait"); } + @Test + public void pluggableEvaluator() throws Exception { + 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"; + 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/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 index 47e01001a65..348e8907a17 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/DRL6Expressions.g4 @@ -747,7 +747,7 @@ identifierSuffix expression RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } )+ // can also be matched by selector, but do here | arguments -// | DOT class_key + | DOT class_key // | DOT explicitGenericInvocation // | DOT this_key // | DOT super_key arguments 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/DRLParser.g4 index e5cfc957cc6..6afee1260ec 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/DRLParser.g4 @@ -188,7 +188,8 @@ relationalOperator | temporalOperator ; -drlRelationalOperator : DRL_NOT? builtInOperator ; +// IDENTIFIER is required to accept custom operators. +drlRelationalOperator : DRL_NOT? (IDENTIFIER | builtInOperator) ; /* function := FUNCTION type? ID parameters(typed) chunk_{_} */ functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters drlBlock ; @@ -350,13 +351,24 @@ temporalOperator : DRL_NOT? bop=(DRL_AFTER | DRL_BEFORE | DRL_COINCIDES | DRL_DU timeAmount : LBRACK (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL) (COMMA (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL))* RBRACK ; +unaryExpressionNotPlusMinus : (left2=xpathPrimary | left1=drlPrimary) (selector)* ; + +selector + : DOT SUPER superSuffix + | DOT NEW (nonWildcardTypeArguments)? innerCreator + | (DOT | NULL_SAFE_DOT) drlIdentifier (drlArguments)? + | (DOT | NULL_SAFE_DOT) drlMethodCall + | LBRACK drlExpression RBRACK + ; + /* extending JavaParser primary */ drlPrimary : LPAREN drlExpression RPAREN | THIS | SUPER + | NEW drlCreator | drlLiteral - | drlIdentifier + | drlIdentifier drlIdentifierMiddle* identifierSuffix? | typeTypeOrVoid DOT CLASS | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) | inlineListExpression @@ -364,6 +376,17 @@ drlPrimary | inlineCast ; +drlIdentifierMiddle + : (DOT | NULL_SAFE_DOT | HASH) drlIdentifier + | (DOT | NULL_SAFE_DOT) LPAREN drlExpression (COMMA drlExpression)* RPAREN + ; + +identifierSuffix + : (LBRACK RBRACK)+ DOT CLASS + | (LBRACK drlExpression RBRACK)+ + | arguments + ; + inlineCast : drlIdentifier HASH drlIdentifier ; /* extending JavaParser literal */ @@ -423,7 +446,7 @@ patternSource : fromAccumulate | fromExpression ; -fromExpression : conditionalOrExpression ; +fromExpression : unaryExpressionNotPlusMinus ; /* From 7154c0f849171e1173af1671fe219ea629c31029 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 16 Apr 2024 16:13:25 +0900 Subject: [PATCH 087/141] [incubator-kie-drools-5808] [new-parser] Combining DRLParser.g4 and DRL6Expressions.g4 (#5845) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * WIP: import DRL6Expressions.g4 into DRLParser.g4 - Removed conflicting rules to make the antlr4 goal successful. - Java compilation fails because DRL6Expressions's @members section injects a DRL6Expression constructor and method overrides into DRLParser.java. * [incubator-kie-drools-5808] [new-parser] Combining DRLParser.g4 and DRL6Expressions.g4 - Modified DRL6Expressions.g4 @members to work with DRLParser - Now DRLParser holds ParserHelper - Fixed BigDecimal/BigInteger literal issues * - Reverted some parser rules which are no longer required after DRL6Expressions.g4 import --------- Co-authored-by: Jiří Locker --- .../drl/parser/antlr4/MiscDRLParserTest.java | 5 + .../drl/parser/antlr4/DRL6Expressions.g4 | 10 +- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 147 +----------------- .../drl/parser/antlr4/DRLParserHelper.java | 6 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 6 +- .../parser/antlr4/Drl6ExprParserAntlr4.java | 3 +- 6 files changed, 25 insertions(+), 152 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 2f98ddea42c..14c30ca67cf 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 @@ -42,6 +42,7 @@ import org.drools.drl.ast.descr.TypeDeclarationDescr; import org.drools.drl.ast.descr.TypeFieldDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl.parser.impl.Operator; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -4010,6 +4011,10 @@ public void pluggableEvaluator() throws Exception { " 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) 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/DRL6Expressions.g4 index 348e8907a17..138f79ede26 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/DRL6Expressions.g4 @@ -30,12 +30,7 @@ options { @members { private ParserHelper helper; - public DRL6Expressions(TokenStream input, - ParserHelper helper ) { - this( input ); - this.helper = helper; - } - + public void setHelper( ParserHelper helper ) { this.helper = helper; } public ParserHelper getHelper() { return helper; } public boolean hasErrors() { return helper.hasErrors(); } public List getErrors() { return helper.getErrors(); } @@ -59,7 +54,6 @@ options { public void setHasBindings( boolean value ) { this.hasBindings = value; } public boolean hasBindings() { return this.hasBindings; } - @Override public final BaseDescr conditionalOrExpressionDescr() throws RecognitionException { return conditionalOrExpression().result; } @@ -101,8 +95,10 @@ literal : STRING_LITERAL { helper.emit($STRING_LITERAL, DroolsEditorType.STRING_CONST); } | DRL_STRING_LITERAL { helper.emit($DRL_STRING_LITERAL, DroolsEditorType.STRING_CONST); } | DECIMAL_LITERAL { helper.emit($DECIMAL_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | DRL_BIG_INTEGER_LITERAL { helper.emit($DRL_BIG_INTEGER_LITERAL, DroolsEditorType.NUMERIC_CONST); } | HEX_LITERAL { helper.emit($HEX_LITERAL, DroolsEditorType.NUMERIC_CONST); } | FLOAT_LITERAL { helper.emit($FLOAT_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | DRL_BIG_DECIMAL_LITERAL { helper.emit($DRL_BIG_DECIMAL_LITERAL, DroolsEditorType.NUMERIC_CONST); } | BOOL_LITERAL { helper.emit($BOOL_LITERAL, DroolsEditorType.BOOLEAN_CONST); } | NULL_LITERAL { helper.emit($NULL_LITERAL, DroolsEditorType.NULL_CONST); } | TIME_INTERVAL { helper.emit($TIME_INTERVAL, DroolsEditorType.NULL_CONST); } 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/DRLParser.g4 index 6afee1260ec..0d6c42b8d72 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/DRLParser.g4 @@ -2,7 +2,7 @@ parser grammar DRLParser; options { tokenVocab=DRLLexer; } -import JavaParser; +import DRL6Expressions, JavaParser; /* * statement := importStatement @@ -138,26 +138,6 @@ constraints : constraint (COMMA constraint)* ; constraint : ( nestedConstraint | conditionalOrExpression ) ; nestedConstraint : ( IDENTIFIER ( DOT | NULL_SAFE_DOT | HASH ) )* IDENTIFIER (DOT | NULL_SAFE_DOT ) LPAREN constraints RPAREN ; -// TBD: constraint parsing could be delegated to DRL6ExpressionParser -conditionalOrExpression : left=conditionalAndExpression (OR right=conditionalAndExpression)* ; -conditionalAndExpression : left=inclusiveOrExpression (AND right=inclusiveOrExpression)* ; -inclusiveOrExpression : left=exclusiveOrExpression (BITOR right=exclusiveOrExpression)* ; -exclusiveOrExpression : left=andExpression (CARET right=andExpression)* ; -andExpression : left=equalityExpression (BITAND right=equalityExpression)* ; -equalityExpression : label? left=instanceOfExpression ( ( op=EQUAL | op=NOTEQUAL ) right=instanceOfExpression )* ; -instanceOfExpression : left=inExpression ( 'instanceof' right=type )? ; -inExpression : left=relationalExpression ( 'not'? 'in' LPAREN drlExpression (COMMA drlExpression)* RPAREN )? ; -relationalExpression : left=drlExpression (right=orRestriction)* ; -orRestriction : left=andRestriction (OR right=andRestriction)* ; -andRestriction : left=singleRestriction (AND right=singleRestriction)* ; -singleRestriction : op=relationalOperator squareArguments? drlExpression ; - -// OOPath -xpathSeparator : DIV | QUESTION_DIV ; -xpathPrimary : label? xpathChunk+ ; -xpathChunk : xpathSeparator drlIdentifier (DOT drlIdentifier)* (HASH drlIdentifier)? (LBRACK xpathExpressionList RBRACK)? ; -xpathExpressionList : label? drlExpression (COMMA label? drlExpression)* ; - // named consequence // consequenceInvocation := conditionalBranch | namedConsequence @@ -188,8 +168,7 @@ relationalOperator | temporalOperator ; -// IDENTIFIER is required to accept custom operators. -drlRelationalOperator : DRL_NOT? (IDENTIFIER | builtInOperator) ; +drlRelationalOperator : DRL_NOT? builtInOperator ; /* function := FUNCTION type? ID parameters(typed) chunk_{_} */ functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters drlBlock ; @@ -200,93 +179,6 @@ drlQualifiedName : drlIdentifier (DOT drlIdentifier)* ; -/* extending JavaParser identifier */ -drlIdentifier - : drlKeywords - | IDENTIFIER - | MODULE - | OPEN - | REQUIRES - | EXPORTS - | OPENS - | TO - | USES - | PROVIDES - | WITH - | TRANSITIVE - | YIELD - | SEALED - | PERMITS - | RECORD - | VAR - | THIS - ; - -drlKeywords - : builtInOperator - | DRL_UNIT - | DRL_FUNCTION - | DRL_GLOBAL - | DRL_DECLARE - | DRL_RULE - | DRL_QUERY - | DRL_WHEN - | DRL_THEN - | DRL_END - | DRL_AND - | DRL_OR - | DRL_EXISTS - | DRL_NOT - | DRL_IN - | DRL_FROM - | DRL_ACCUMULATE - | DRL_ACC - | DRL_INIT - | DRL_ACTION - | DRL_REVERSE - | DRL_RESULT - | DRL_ENTRY_POINT - | DRL_EVAL - | DRL_SALIENCE - | DRL_ENABLED - | DRL_NO_LOOP - | DRL_AUTO_FOCUS - | DRL_LOCK_ON_ACTIVE - | DRL_REFRACT - | DRL_DIRECT - | DRL_AGENDA_GROUP - | DRL_ACTIVATION_GROUP - | DRL_RULEFLOW_GROUP - | DRL_DATE_EFFECTIVE - | DRL_DATE_EXPIRES - | DRL_DIALECT - | DRL_CALENDARS - | DRL_TIMER - | DRL_DURATION - ; - -builtInOperator - : DRL_CONTAINS - | DRL_EXCLUDES - | DRL_MATCHES - | DRL_MEMBEROF - | DRL_SOUNDSLIKE - | DRL_AFTER - | DRL_BEFORE - | DRL_COINCIDES - | DRL_DURING - | DRL_FINISHED_BY - | DRL_FINISHES - | DRL_INCLUDES - | DRL_MEETS - | DRL_MET_BY - | DRL_OVERLAPPED_BY - | DRL_OVERLAPS - | DRL_STARTED_BY - | DRL_STARTS - | DRL_STR - ; - /* extending JavaParser expression */ drlExpression : drlPrimary @@ -351,16 +243,6 @@ temporalOperator : DRL_NOT? bop=(DRL_AFTER | DRL_BEFORE | DRL_COINCIDES | DRL_DU timeAmount : LBRACK (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL) (COMMA (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL))* RBRACK ; -unaryExpressionNotPlusMinus : (left2=xpathPrimary | left1=drlPrimary) (selector)* ; - -selector - : DOT SUPER superSuffix - | DOT NEW (nonWildcardTypeArguments)? innerCreator - | (DOT | NULL_SAFE_DOT) drlIdentifier (drlArguments)? - | (DOT | NULL_SAFE_DOT) drlMethodCall - | LBRACK drlExpression RBRACK - ; - /* extending JavaParser primary */ drlPrimary : LPAREN drlExpression RPAREN @@ -368,7 +250,7 @@ drlPrimary | SUPER | NEW drlCreator | drlLiteral - | drlIdentifier drlIdentifierMiddle* identifierSuffix? + | drlIdentifier | typeTypeOrVoid DOT CLASS | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) | inlineListExpression @@ -376,17 +258,6 @@ drlPrimary | inlineCast ; -drlIdentifierMiddle - : (DOT | NULL_SAFE_DOT | HASH) drlIdentifier - | (DOT | NULL_SAFE_DOT) LPAREN drlExpression (COMMA drlExpression)* RPAREN - ; - -identifierSuffix - : (LBRACK RBRACK)+ DOT CLASS - | (LBRACK drlExpression RBRACK)+ - | arguments - ; - inlineCast : drlIdentifier HASH drlIdentifier ; /* extending JavaParser literal */ @@ -403,16 +274,10 @@ drlLiteral | TIME_INTERVAL ; -squareArguments : LBRACK expressionList? RBRACK ; - inlineListExpression : LBRACK expressionList? RBRACK ; -expressionList - : drlExpression (COMMA drlExpression)* - ; - inlineMapExpression : LBRACK mapExpressionList RBRACK ; @@ -446,7 +311,7 @@ patternSource : fromAccumulate | fromExpression ; -fromExpression : unaryExpressionNotPlusMinus ; +fromExpression : conditionalOrExpression ; /* @@ -559,7 +424,7 @@ drlElementValue ; attributes : attribute ( COMMA? attribute )* ; -attribute : name=( 'salience' | 'enabled' ) conditionalOrExpression #expressionAttribute +attribute : name=( 'salience' | 'enabled' ) conditionalAttributeValue #expressionAttribute | name=( 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOL_LITERAL? #booleanAttribute | name=( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) DRL_STRING_LITERAL #stringAttribute | name='calendars' DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* #stringListAttribute @@ -567,6 +432,8 @@ attribute : name=( 'salience' | 'enabled' ) conditionalOrExpression #expressionA | name='duration' ( DECIMAL_LITERAL | TIME_INTERVAL | LPAREN TIME_INTERVAL RPAREN ) #durationAttribute ; +conditionalAttributeValue : ( LPAREN conditionalExpression RPAREN | conditionalExpression ) ; + chunk : .+?; assignmentOperator : ASSIGN 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/DRLParserHelper.java index 3d91f782a48..9c8fef57d0d 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/DRLParserHelper.java @@ -32,6 +32,7 @@ import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.PackageDescr; +import org.kie.internal.builder.conf.LanguageLevelOption; /** * Collection of static helper methods for DRLParser @@ -76,7 +77,10 @@ public static DRLParser createDrlParser(Reader reader) { private static DRLParser createDrlParser(CharStream charStream) { DRLLexer drlLexer = new DRLLexer(charStream); CommonTokenStream commonTokenStream = new CommonTokenStream(drlLexer); - return new DRLParser(commonTokenStream); + DRLParser parser = new DRLParser(commonTokenStream); + ParserHelper helper = new ParserHelper(commonTokenStream, LanguageLevelOption.DRL6); + parser.setHelper(helper); + return parser; } /** 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 ba9157897ec..526aaddf24e 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 @@ -399,7 +399,7 @@ public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeCont AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) .build(); - attributeDescr.setValue(getTextPreservingWhitespace(ctx.conditionalOrExpression())); + attributeDescr.setValue(getTextPreservingWhitespace(ctx.conditionalAttributeValue())); attributeDescr.setType(AttributeDescr.Type.EXPRESSION); return attributeDescr; } @@ -673,8 +673,8 @@ public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { .build(); behaviorDescr.setType(ctx.DRL_WINDOW().getText()); behaviorDescr.setSubType(ctx.IDENTIFIER().getText()); - List drlExpressionContexts = ctx.expressionList().drlExpression(); - List parameters = drlExpressionContexts.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); + List expressionContexts = ctx.expressionList().expression(); + List parameters = expressionContexts.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); behaviorDescr.setParameters(parameters); return behaviorDescr; } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java index 4505ca428ae..29102a0f7d0 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java @@ -52,7 +52,8 @@ public ConstraintConnectiveDescr parse(final String text) { DRLLexer lexer = new DRLLexer(CharStreams.fromString(text)); CommonTokenStream input = new CommonTokenStream(lexer); helper = new ParserHelper(input, languageLevel); - DRLExpressions parser = new DRL6Expressions(input, helper); + DRL6Expressions parser = new DRL6Expressions(input); + parser.setHelper(helper); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { From a19a2c8b0126d828ff0ebe3b5ecf569eb81ff71e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Tue, 23 Apr 2024 08:40:59 +0200 Subject: [PATCH 088/141] Add missing DRL soft keywords to the drlIdentfier rule (#5861) --- .../antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 | 5 +++++ .../main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) 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/DRL6Expressions.g4 index 138f79ede26..f17ed639366 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/DRL6Expressions.g4 @@ -187,6 +187,7 @@ drlKeywords returns [Token token] | DRL_FUNCTION | DRL_GLOBAL | DRL_DECLARE + | DRL_TRAIT | DRL_RULE | DRL_QUERY | DRL_WHEN @@ -198,6 +199,7 @@ drlKeywords returns [Token token] | DRL_NOT | DRL_IN | DRL_FROM + | DRL_COLLECT | DRL_ACCUMULATE | DRL_ACC | DRL_INIT @@ -206,6 +208,8 @@ drlKeywords returns [Token token] | DRL_RESULT | DRL_ENTRY_POINT | DRL_EVAL + | DRL_FORALL + | DRL_OVER | DRL_SALIENCE | DRL_ENABLED | DRL_NO_LOOP @@ -222,6 +226,7 @@ drlKeywords returns [Token token] | DRL_CALENDARS | DRL_TIMER | DRL_DURATION + | DRL_WINDOW ; builtInOperator returns[Token token] 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/DRLParser.g4 index 0d6c42b8d72..f4358ccf701 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/DRLParser.g4 @@ -403,7 +403,7 @@ consequenceBody : ( RHS_STRING_LITERAL | RHS_CHUNK )* ; // THEN LEFT_SQUARE ID RIGHT_SQUARE chunk namedConsequence : RHS_NAMED_CONSEQUENCE_THEN consequenceBody ; -stringId : ( IDENTIFIER | DRL_STRING_LITERAL ) ; +stringId : ( drlIdentifier | DRL_STRING_LITERAL ) ; type : (classOrInterfaceType | primitiveType) typeArguments? ( DOT IDENTIFIER typeArguments? )* (LBRACK RBRACK)* ; From 77e6476b2c3f3c0293cfff72c79f7b48311679f5 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 23 Apr 2024 17:50:08 +0900 Subject: [PATCH 089/141] [incubator-kie-drools-5792] [new-parser] improve drools-drl-parser-tests (#5855) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5854] [new-parser] improve drools-drl-parser-testsa to test with old and new parsers - Old and new parser coverage using 2 surefire test executions - Fixed Descr common property issues to keep backward compatibility - A few test cases remaining without backward compatibility ("Backward Compatibility Notes" left) because the old parser seems to be wrong. - A few expr test cases remaining without backward compatibility ("Backward Compatibility Notes" left). Error code/message don't seem to be important. Also the new parser ones are better. * Update drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java Co-authored-by: Jiří Locker * - removed unused import --------- Co-authored-by: Jiří Locker --- drools-drl/drools-drl-parser-tests/pom.xml | 38 ++ .../drl/parser/antlr4/DRLExprParserTest.java | 91 ++-- .../drl/parser/antlr4/DRLParserTest.java | 3 + .../antlr4/DescrCommonPropertyTest.java | 197 +++++--- .../drl/parser/antlr4/DescrDumperTest.java | 3 +- .../drl/parser/antlr4/MiscDRLParserTest.java | 422 ++++++++++-------- .../drl/parser/antlr4/ParserTestUtils.java | 35 ++ .../org/drools/drl/parser/antlr4/DRLLexer.g4 | 9 +- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 30 +- .../java/org/drools/drl/parser/DrlParser.java | 4 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 9 +- .../drools/drl/parser/antlr4/DescrHelper.java | 48 +- .../drools/drl/parser/antlr4/LexerHelper.java | 161 +++++++ .../drl/parser/antlr4/ParserHelper.java | 2 +- 14 files changed, 745 insertions(+), 307 deletions(-) create mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java create mode 100644 drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java diff --git a/drools-drl/drools-drl-parser-tests/pom.xml b/drools-drl/drools-drl-parser-tests/pom.xml index 4f3a19c8127..1e26095a3bd 100644 --- a/drools-drl/drools-drl-parser-tests/pom.xml +++ b/drools-drl/drools-drl-parser-tests/pom.xml @@ -83,4 +83,42 @@ + + + default + + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + default-test + + + true + + + + + old-parser-test + + + false + + + + test + + + + + + + + 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 3f3b256dd50..30a316e24b7 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 @@ -30,6 +30,8 @@ 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; import org.junit.jupiter.api.AfterEach; @@ -49,17 +51,17 @@ public class DRLExprParserTest { DrlExprParser parser; @BeforeEach - public void setUp() throws Exception { - this.parser = new Drl6ExprParserAntlr4(LanguageLevelOption.DRL6); + public void setUp() { + this.parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { this.parser = null; } @Test - public void testSimpleExpression() throws Exception { + public void testSimpleExpression() { String source = "a > b"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); @@ -387,13 +389,26 @@ public void testMismatchedInput() { assertThat(parser.hasErrors()).isTrue(); assertThat(parser.getErrors()).hasSize(1); DroolsParserException exception = parser.getErrors().get(0); - assertThat(exception.getErrorCode()).isEqualTo("ERR 102"); - assertThat(exception.getLineNumber()).isEqualTo(1); - assertThat(exception.getColumn()).isEqualTo(1); - assertThat(exception.getOffset()).isEqualTo(1); - assertThat(exception.getMessage()) - .startsWithIgnoringCase("[ERR 102] Line 1:1 mismatched input '' expecting ") - .contains("TIME_INTERVAL", "DRL_STRING_LITERAL", "?/", "boolean", "byte", "char", "double", "float", "int", "long", "new", "short", "super", "DECIMAL_LITERAL", "HEX_LITERAL", "FLOAT_LITERAL", "BOOL_LITERAL", "STRING_LITERAL", "null", "(", "[", ".", "<", "!", "~", "++", "--", "+", "-", "*", "/", "IDENTIFIER"); + + // Backward Compatibility Notes: + // Antlr4 gives a different error code/message from antlr3 for this case. + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertThat(exception.getErrorCode()).isEqualTo("ERR 102"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(1); + assertThat(exception.getOffset()).isEqualTo(1); + assertThat(exception.getMessage()) + .startsWithIgnoringCase("[ERR 102] Line 1:1 mismatched input '' expecting ") + .contains("TIME_INTERVAL", "DRL_STRING_LITERAL", "?/", "boolean", "byte", "char", "double", "float", "int", "long", "new", "short", "super", "DECIMAL_LITERAL", "HEX_LITERAL", "FLOAT_LITERAL", "BOOL_LITERAL", "STRING_LITERAL", "null", "(", "[", ".", "<", "!", "~", "++", "--", "+", "-", "*", "/", "IDENTIFIER"); + } else { + assertThat(exception.getErrorCode()).isEqualTo("ERR 101"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(1); + assertThat(exception.getOffset()).isEqualTo(1); + assertThat(exception.getMessage()) + .isEqualToIgnoringCase("[ERR 101] Line 1:1 no viable alternative at input ''"); + } } @Test @@ -403,26 +418,48 @@ public void testExtraneousInput() { assertThat(parser.hasErrors()).isTrue(); assertThat(parser.getErrors()).hasSize(1); DroolsParserException exception = parser.getErrors().get(0); - assertThat(exception.getErrorCode()).isEqualTo("ERR 109"); - assertThat(exception.getLineNumber()).isEqualTo(1); - assertThat(exception.getColumn()).isEqualTo(3); - assertThat(exception.getOffset()).isEqualTo(3); - assertThat(exception.getMessage()) - .startsWithIgnoringCase("[ERR 109] Line 1:3 extraneous input ';' expecting ") - .contains("TIME_INTERVAL", "DRL_STRING_LITERAL", "?/", "boolean", "byte", "char", "double", "float", "int", "long", "new", "short", "super", "DECIMAL_LITERAL", "HEX_LITERAL", "FLOAT_LITERAL", "BOOL_LITERAL", "STRING_LITERAL", "null", "(", "[", ".", "<", "!", "~", "++", "--", "+", "-", "*", "/", "IDENTIFIER"); + + // Backward Compatibility Notes: + // Antlr4 gives a different error code/message from antlr3 for this case. + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertThat(exception.getErrorCode()).isEqualTo("ERR 109"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(3); + assertThat(exception.getOffset()).isEqualTo(3); + assertThat(exception.getMessage()) + .startsWithIgnoringCase("[ERR 109] Line 1:3 extraneous input ';' expecting ") + .contains("TIME_INTERVAL", "DRL_STRING_LITERAL", "?/", "boolean", "byte", "char", "double", "float", "int", "long", "new", "short", "super", "DECIMAL_LITERAL", "HEX_LITERAL", "FLOAT_LITERAL", "BOOL_LITERAL", "STRING_LITERAL", "null", "(", "[", ".", "<", "!", "~", "++", "--", "+", "-", "*", "/", "IDENTIFIER"); + } else { + assertThat(exception.getErrorCode()).isEqualTo("ERR 101"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(3); + assertThat(exception.getOffset()).isEqualTo(3); + assertThat(exception.getMessage()) + .isEqualToIgnoringCase("[ERR 101] Line 1:3 no viable alternative at input ';'"); + } } + @Test public void testNoViableAlt() { String source = "x.int"; parser.parse(source); - assertThat(parser.hasErrors()).isTrue(); - assertThat(parser.getErrors()).hasSize(1); - DroolsParserException exception = parser.getErrors().get(0); - assertThat(exception.getErrorCode()).isEqualTo("ERR 101"); - assertThat(exception.getLineNumber()).isEqualTo(1); - assertThat(exception.getColumn()).isEqualTo(2); - assertThat(exception.getOffset()).isEqualTo(2); - assertThat(exception.getMessage()) - .isEqualToIgnoringCase("[ERR 101] Line 1:2 no viable alternative at input '.int'"); + + // Backward Compatibility Notes: + // Old expr parser (DRL6Expressions) allows this expression because it's too tolerant (fail at runtime anyway). + // Backward compatibility doesn't seem to be required in this case. (But we may align with the old tolerant behavior.) + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertThat(parser.hasErrors()).isTrue(); + assertThat(parser.getErrors()).hasSize(1); + DroolsParserException exception = parser.getErrors().get(0); + assertThat(exception.getErrorCode()).isEqualTo("ERR 101"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(2); + assertThat(exception.getOffset()).isEqualTo(2); + assertThat(exception.getMessage()) + .isEqualToIgnoringCase("[ERR 101] Line 1:2 no viable alternative at input '.int'"); + } else { + assertThat(parser.hasErrors()).isFalse(); + } } } 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/DRLParserTest.java index 8aecc0fb056..f792effd235 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/DRLParserTest.java @@ -17,6 +17,9 @@ import static org.drools.drl.parser.antlr4.DRLParserHelper.createDrlParser; import static org.drools.drl.parser.antlr4.DRLParserHelper.parse; +/** + * This test class is specific to new antlr4 parser. + */ class DRLParserTest { private static final String drl = 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 bc3010e6987..25c51ca9b7f 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 @@ -1,3 +1,21 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.drools.drl.parser.antlr4; import org.drools.drl.ast.descr.AccumulateDescr; @@ -22,7 +40,6 @@ import org.drools.drl.ast.descr.OrDescr; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.ast.descr.PatternDescr; -import org.drools.drl.ast.descr.PatternSourceDescr; import org.drools.drl.ast.descr.QueryDescr; import org.drools.drl.ast.descr.RuleDescr; import org.drools.drl.ast.descr.TypeDeclarationDescr; @@ -30,7 +47,8 @@ import org.drools.drl.ast.descr.UnitDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; import org.drools.drl.ast.descr.WindowReferenceDescr; -import org.junit.jupiter.api.AfterEach; +import org.drools.drl.parser.DrlParser; +import org.drools.drl.parser.DroolsParserException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -41,15 +59,21 @@ */ class DescrCommonPropertyTest { - private DRLParserWrapper parser; + private DrlParser parser; @BeforeEach public void setUp() { - parser = new DRLParserWrapper(); + parser = ParserTestUtils.getParser(); } - @AfterEach - public void tearDown() { + private PackageDescr parseAndGetPackageDescr(String drl) { + try { + PackageDescr pkg = parser.parse(null, drl); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + return pkg; + } catch (DroolsParserException e) { + throw new RuntimeException(e); + } } private void assertProperties(BaseDescr descr, int startCharacter, int endCharacter, int line, int column, int endLine, int endColumn) { @@ -64,8 +88,8 @@ private void assertProperties(BaseDescr descr, int startCharacter, int endCharac @Test void packageDescr() { final String source = "package foo.bar.baz"; - final PackageDescr pkg = parser.parse(source); - assertProperties(pkg, 0, 18, 1, 0, 1, 18); + final PackageDescr pkg = parseAndGetPackageDescr(source); + assertProperties(pkg, 0, 19, 1, 0, 1, 18); } @Test @@ -74,17 +98,18 @@ void ruleDescr() { " when\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); - assertProperties(rule, 0, 30, 1, 0, 4, 2); + assertProperties(rule, 0, 31, 1, 0, 4, 2); } @Test void unitDescr() { - final String source = "unit Foo;"; - final PackageDescr pkg = parser.parse(source); + final String source = "package abc;\n" + + "unit Foo;"; + final PackageDescr pkg = parseAndGetPackageDescr(source); final UnitDescr unit = pkg.getUnit(); - assertProperties(unit, 0, 8, 1, 0, 1, 8); + assertProperties(unit, 13, 22, 2, 0, 2, 8); } @Test @@ -92,9 +117,9 @@ void queryDescr() { final String source = "query \"MyQuery\"\n" + " Foo()\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final QueryDescr query = (QueryDescr) pkg.getRules().get(0); - assertProperties(query, 0, 26, 1, 0, 3, 2); + assertProperties(query, 0, 27, 1, 0, 3, 2); } @Test @@ -102,41 +127,41 @@ void functionDescr() { final String source = "function void myFunction(String data) {\n" + " foo();\n" + "}"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final FunctionDescr function = pkg.getFunctions().get(0); - assertProperties(function, 0, 49, 1, 0, 3, 0); + assertProperties(function, 0, 50, 1, 0, 3, 0); } @Test void globalDescr() { final String source = "global java.util.List myList"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final GlobalDescr global = pkg.getGlobals().get(0); - assertProperties(global, 0, 27, 1, 0, 1, 27); + assertProperties(global, 0, 28, 1, 0, 1, 27); } @Test void functionImportDescr() { final String source = "import function org.drools.core.util.DateUtils.*"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final FunctionImportDescr functionImport = pkg.getFunctionImports().get(0); - assertProperties(functionImport, 0, 47, 1, 0, 1, 47); + assertProperties(functionImport, 0, 48, 1, 0, 1, 47); } @Test void importDescr() { final String source = "import org.drools.core.util.DateUtils"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final ImportDescr importDescr = pkg.getImports().get(0); - assertProperties(importDescr, 0, 36, 1, 0, 1, 36); + assertProperties(importDescr, 0, 37, 1, 0, 1, 36); } @Test void accumulateImportDescr() { final String source = "import accumulate org.example.MyAccUtils.sum mySum"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final AccumulateImportDescr accumulateImport = pkg.getAccumulateImports().get(0); - assertProperties(accumulateImport, 0, 49, 1, 0, 1, 49); + assertProperties(accumulateImport, 0, 50, 1, 0, 1, 49); } @Test @@ -144,11 +169,11 @@ void typeDeclarationDescr() { final String source = "declare MyType\n" + " name : String\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final TypeDeclarationDescr typeDeclaration = pkg.getTypeDeclarations().get(0); // startCharacter = 8 looks a little odd ("declare" is not included in the Descr), but it keeps the same as the old implementation. We may change it in the future. - assertProperties(typeDeclaration, 8, 33, 1, 8, 3, 2); + assertProperties(typeDeclaration, 8, 34, 1, 8, 3, 2); } @Test @@ -156,9 +181,9 @@ void entryPointDeclarationDescr() { final String source = "declare entry-point MyEntryPoint\n" + " @foo( true )\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final EntryPointDeclarationDescr entryPointDeclaration = pkg.getEntryPointDeclarations().stream().findFirst().get(); - assertProperties(entryPointDeclaration, 8, 50, 1, 8, 3, 2); + assertProperties(entryPointDeclaration, 8, 51, 1, 8, 3, 2); } @Test @@ -168,9 +193,9 @@ void windowDeclarationDescr() { " over window:length( 10, $s.symbol )\n" + " from entry-point stStream\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final WindowDeclarationDescr windowDeclaration = pkg.getWindowDeclarations().stream().findFirst().get(); - assertProperties(windowDeclaration, 8, 139, 1, 8, 5, 2); + assertProperties(windowDeclaration, 8, 140, 1, 8, 5, 2); } @Test @@ -181,10 +206,10 @@ void annotationDescr() { " $p : Person( name == \"Mario\" ) @watch(!*, age)\n" + "then\n" + "end\n"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); AnnotationDescr annotation = rule.getLhs().getAllPatternDescr().get(0).getAnnotations().stream().findFirst().get(); - assertProperties(annotation, 65, 79, 4, 33, 4, 47); + assertProperties(annotation, 65, 80, 4, 33, 4, 47); } @Test @@ -192,10 +217,17 @@ void typeFieldDescr() { final String source = "declare MyType\n" + " name : String\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final TypeDeclarationDescr typeDeclaration = pkg.getTypeDeclarations().get(0); TypeFieldDescr typeField = typeDeclaration.getFields().get("name"); - assertProperties(typeField, 17, 29, 2, 2, 2, 14); + // Backward Compatibility Notes: + // The old DRL6Parser uses only the attribute value token for common properties (seem to be wrong), so startCharacter and column are different between old and new parser. + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertProperties(typeField, 17, 30, 2, 2, 2, 14); + } else { + assertProperties(typeField, 24, 30, 2, 9, 2, 14); + } } @Test @@ -206,10 +238,19 @@ void attributeDescr() { " when\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); - assertProperties(rule.getAttributes().get("salience"), 10, 20, 2, 2, 2, 12); - assertProperties(rule.getAttributes().get("agenda-group"), 24, 46, 3, 2, 3, 24); + + // Backward Compatibility Notes: + // The old DRL6Parser uses only the attribute value token for common properties (seem to be wrong), so startCharacter and column are different between old and new parser. + // 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); + } else { + assertProperties(rule.getAttributes().get("salience"), 19, 21, 2, 11, 2, 12); + assertProperties(rule.getAttributes().get("agenda-group"), 37, 47, 3, 15, 3, 24); + } } @Test @@ -219,10 +260,10 @@ void patternDescr() { " $p : Person( name == \"Mario\" )\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); - assertProperties(pattern, 19, 48, 3, 4, 3, 33); + assertProperties(pattern, 19, 49, 3, 4, 3, 33); } @Test @@ -232,10 +273,10 @@ void orDescr() { " ( $p : Person( name == \"Mario\" ) or $p : Person( name == \"Luigi\" ) )\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); - assertProperties(or, 21, 84, 3, 6, 3, 69); + assertProperties(or, 21, 85, 3, 6, 3, 69); } @Test @@ -245,10 +286,10 @@ void andDescr() { " ( $p1 : Person( name == \"Mario\" ) and $p2 : Person( name == \"Luigi\" ) )\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); AndDescr and = rule.getLhs(); - assertProperties(and, 21, 87, 3, 6, 3, 72); + assertProperties(and, 19, 90, 3, 4, 3, 74); } @Test @@ -258,10 +299,10 @@ void forallDescr() { " forall( $p : Person( name == \"Mario\" ) )\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0); - assertProperties(forall, 19, 58, 3, 4, 3, 43); + assertProperties(forall, 19, 59, 3, 4, 3, 43); } @Test @@ -271,23 +312,23 @@ void accumulateDescr() { " accumulate( $p : Person( name == \"Mario\" ), $sum : sum($p.getAge()) )\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); AccumulateDescr accumulate = (AccumulateDescr) pattern.getSource(); - assertProperties(accumulate, 19, 87, 3, 4, 3, 72); + assertProperties(accumulate, 19, 88, 3, 4, 3, 72); } @Test void behaviorDescr() { final String source = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end";; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); BehaviorDescr behavior = pattern.getBehaviors().get(0); // "over" is not included in BehaviorDescr - assertProperties(behavior, 44, 60, 1, 44, 1, 60); + assertProperties(behavior, 44, 61, 1, 44, 1, 60); } @Test @@ -298,13 +339,20 @@ void fromDescr() { " Child() from $children\n" + " then\n" + "end";; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); FromDescr from = (FromDescr) pattern.getSource(); - // "from" is not included in FromDescr - assertProperties(from, 64, 72, 4, 17, 4, 25); + // Backward Compatibility Notes: + // The old DRL6Parser doesn't populate common properties of FromDescr (seem to be wrong). + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + // "from" is not included in FromDescr + assertProperties(from, 64, 73, 4, 17, 4, 25); + } else { + assertProperties(from, -1, -1, -1, -1, -1, -1); + } } @Test @@ -314,12 +362,12 @@ void collectDescr() { " ArrayList() from collect( Person( age > 21 ) );\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); CollectDescr collect = (CollectDescr) pattern.getSource(); - assertProperties(collect, 35, 63, 3, 21, 3, 49); + assertProperties(collect, 35, 64, 3, 21, 3, 49); } @Test @@ -329,11 +377,19 @@ void entryPointDescr() { " StockTick() from entry-point \"stream\"\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); EntryPointDescr entryPoint = (EntryPointDescr) pattern.getSource(); - assertProperties(entryPoint, 35, 54, 3, 21, 3, 40); + + // Backward Compatibility Notes: + // The old DRL6Parser doesn't populate common properties of EntryPointDescr (seem to be wrong). + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertProperties(entryPoint, 35, 55, 3, 21, 3, 40); + } else { + assertProperties(entryPoint, -1, -1, -1, -1, -1, -1); + } } @Test @@ -343,11 +399,18 @@ void windowReferenceDescr() { " StockTick() from window MyWindow\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); WindowReferenceDescr windowReference = (WindowReferenceDescr) pattern.getSource(); - assertProperties(windowReference, 35, 49, 3, 21, 3, 35); + // Backward Compatibility Notes: + // The old DRL6Parser doesn't populate common properties of WindowReferenceDescr (seem to be wrong). + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertProperties(windowReference, 35, 50, 3, 21, 3, 35); + } else { + assertProperties(windowReference, -1, -1, -1, -1, -1, -1); + } } @Test @@ -357,11 +420,11 @@ void exprConstraintDescr() { " Person( age > 21 )\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); ExprConstraintDescr exprConstraint = (ExprConstraintDescr) pattern.getDescrs().get(0); - assertProperties(exprConstraint, 26, 33, 3, 12, 3, 19); + assertProperties(exprConstraint, 26, 33, 3, 12, 3, 18); } @Test @@ -371,10 +434,10 @@ void existDescr() { " exists( Person( age > 21 ) )\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); ExistsDescr exists = (ExistsDescr) rule.getLhs().getDescrs().get(0); - assertProperties(exists, 18, 45, 3, 4, 3, 31); + assertProperties(exists, 18, 46, 3, 4, 3, 31); } @Test @@ -384,10 +447,10 @@ void notDescr() { " not( Person( age > 21 ) )\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(0); - assertProperties(not, 18, 42, 3, 4, 3, 28); + assertProperties(not, 18, 43, 3, 4, 3, 28); } @Test @@ -397,9 +460,9 @@ void evalDescr() { " eval( 1 + 1 == 2 )\n" + " then\n" + "end"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(0); - assertProperties(eval, 18, 35, 3, 4, 3, 21); + assertProperties(eval, 18, 36, 3, 4, 3, 21); } } 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 ab644f7dafb..1d038907c89 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 @@ -26,6 +26,7 @@ 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; @@ -358,7 +359,7 @@ public void testProcessImplicitConstraints() throws Exception { } public ConstraintConnectiveDescr parse( final String constraint ) { - DrlExprParser parser = new Drl6ExprParserAntlr4(LanguageLevelOption.DRL6); + DrlExprParser parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); 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/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java index 14c30ca67cf..e617a4dfb49 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 @@ -2,6 +2,8 @@ import java.io.BufferedReader; import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -42,6 +44,8 @@ import org.drools.drl.ast.descr.TypeDeclarationDescr; import org.drools.drl.ast.descr.TypeFieldDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl.parser.DrlParser; +import org.drools.drl.parser.DroolsParserException; import org.drools.drl.parser.impl.Operator; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -57,19 +61,20 @@ */ class MiscDRLParserTest { - private DRLParserWrapper parser; + private DrlParser parser; @BeforeEach public void setUp() { - parser = new DRLParserWrapper(); + parser = ParserTestUtils.getParser(); } - @AfterEach - public void tearDown() { - } - - private String readResource(final String filename) throws Exception { - Path path = Paths.get(getClass().getResource(filename).toURI()); + private String readResource(final String filename) { + Path path; + try { + path = Paths.get(getClass().getResource(filename).toURI()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } final StringBuilder sb = new StringBuilder(); try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { for (String line; (line = br.readLine()) != null; ) { @@ -77,67 +82,82 @@ private String readResource(final String filename) throws Exception { sb.append("\n"); } } catch (IOException e) { - e.printStackTrace(); + throw new UncheckedIOException(e); } return sb.toString(); } + private PackageDescr parseAndGetPackageDescr(String drl) { + try { + PackageDescr pkg = parser.parse(null, drl); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + return pkg; + } catch (DroolsParserException e) { + throw new RuntimeException(e); + } + } + + private PackageDescr parseAndGetPackageDescrWithoutErrorCheck(String drl) { + try { + return parser.parse(null, drl); + } catch (DroolsParserException e) { + throw new RuntimeException(e); + } + } + private RuleDescr parseAndGetFirstRuleDescr(String drl) { - PackageDescr pkg = parser.parse(drl); - assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(drl); assertThat(pkg.getRules()).isNotEmpty(); return pkg.getRules().get(0); } - private RuleDescr parseAndGetFirstRuleDescrFromFile(String filename) throws Exception { - return parseAndGetFirstRuleDescr(readResource(filename)); + private PackageDescr parseAndGetPackageDescrFromFile(String filename) { + return parseAndGetPackageDescr(readResource(filename)); } - private PackageDescr parseAndGetPackageDescrFromFile(String filename) throws Exception { - return parser.parse(readResource(filename)); + private RuleDescr parseAndGetFirstRuleDescrFromFile(String filename) { + return parseAndGetFirstRuleDescr(readResource(filename)); } private QueryDescr parseAndGetFirstQueryDescr(String drl) { - PackageDescr pkg = parser.parse(drl); - assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(drl); assertThat(pkg.getRules()).isNotEmpty(); Optional optQuery = pkg.getRules().stream().filter(QueryDescr.class::isInstance).map(QueryDescr.class::cast).findFirst(); assertThat(optQuery).isPresent(); return optQuery.get(); } - private QueryDescr parseAndGetFirstQueryDescrFromFile(String filename) throws Exception { + private QueryDescr parseAndGetFirstQueryDescrFromFile(String filename) { return parseAndGetFirstQueryDescr(readResource(filename)); } @Test void parse_validPackage() { final String source = "package foo.bar.baz"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); } @Test void parse_packageWithErrorNode() { final String source = "package 12 foo.bar.baz"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescrWithoutErrorCheck(source); assertThat(parser.hasErrors()).isTrue(); - assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); + assertThat(pkg).isNull(); } @Test void parse_packageWithAllErrorNode() { final String source = "package 12 12312 231"; - final PackageDescr pkg = parser.parse(source); + final PackageDescr pkg = parseAndGetPackageDescrWithoutErrorCheck(source); assertThat(parser.hasErrors()).isTrue(); - assertThat(pkg.getName()).isEmpty(); + assertThat(pkg).isNull(); } @Test void parse_import() { final String source = "package foo; import com.foo.Bar; import com.foo.Baz;"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg =parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("foo"); assertThat(pkg.getImports()).hasSize(2); ImportDescr impdescr = pkg.getImports().get(0); @@ -158,26 +178,25 @@ void parse_functionImport() { "import function java.lang.Math.min;\n" + "import foo.bar.*\n" + "import baz.Baz"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("foo"); assertThat(pkg.getImports()).hasSize(2); ImportDescr impdescr = pkg.getImports().get(0); assertThat(impdescr.getTarget()).isEqualTo("foo.bar.*"); assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); impdescr = pkg.getImports().get(1); assertThat(impdescr.getTarget()).isEqualTo("baz.Baz"); assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); assertThat(pkg.getFunctionImports()).hasSize(2); impdescr = pkg.getFunctionImports().get(0); assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.max"); assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget())); - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length() - 1); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length()); impdescr = pkg.getFunctionImports().get(1); assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.min"); @@ -191,15 +210,14 @@ void parse_globalWithComplexType() { "import com.foo.Bar\n" + "global java.util.List> aList;\n" + "global Integer aNumber"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); assertThat(pkg.getImports()).hasSize(1); ImportDescr impdescr = pkg.getImports().get(0); assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); - assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length() - 1); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); assertThat(pkg.getGlobals()).hasSize(2); @@ -215,13 +233,13 @@ void parse_globalWithComplexType() { assertThat(global.getIdentifier()).isEqualTo("aNumber"); assertThat(global.getStartCharacter()).isEqualTo(source.indexOf("global " + global.getType())); assertThat(global.getEndCharacter()).isEqualTo(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + - ("global " + global.getType() + " " + global.getIdentifier()).length() - 1); + ("global " + global.getType() + " " + global.getIdentifier()).length()); } @Test void parse_globalWithOrWithoutSemi() throws Exception { String source = readResource("globals.drl"); - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getRules()).hasSize(1); @@ -242,7 +260,7 @@ void parse_globalWithOrWithoutSemi() throws Exception { @Test void parse_functionImportWithNotExist() throws Exception { String source = readResource("test_FunctionImport.drl"); - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getFunctionImports()).hasSize(2); @@ -265,9 +283,7 @@ void parse_fromComplexAccessor() { "\n" + " o.addError(\"Invalid customer id\"); \n" + "end \n"; - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrorMessages().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("Invalid customer id"); @@ -291,8 +307,7 @@ void parse_fromWithInlineList() { " System.err.println(\"Invalid customer id found!\"); \n" + " o.addError(\"Invalid customer id\"); \n" + "end \n"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("XYZ"); @@ -311,13 +326,11 @@ void parse_fromWithInlineListMethod() { " System.err.println(\"Invalid customer id found!\"); \n" + " o.addError(\"Invalid customer id\"); \n" + "end \n"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("XYZ"); - assertThat(parser.hasErrors()).isFalse(); PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3].sublist(1, 2)"); @@ -333,14 +346,11 @@ void parse_fromWithInlineListIndex() { " System.err.println(\"Invalid customer id found!\"); \n" + " o.addError(\"Invalid customer id\"); \n" + "end \n"; - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("XYZ"); - assertThat(parser.hasErrors()).isFalse(); PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3][1]"); } @@ -352,7 +362,7 @@ void parse_ruleWithoutEnd() { " o: Order( ) \n" + " then \n" + " System.err.println(\"Invalid customer id found!\"); \n"; - parser.parse(source); + parseAndGetPackageDescrWithoutErrorCheck(source); assertThat(parser.hasErrors()).isTrue(); } @@ -367,8 +377,7 @@ void parse_orWithSpecialBind() { " then \n" + " System.out.println( \"Rule: A and (B or C or D) Fired. pdo1: \" + pdo1 + \" pdo2: \"+ pdo2); \n" + "end\n"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); RuleDescr rule = pkg.getRules().get(0); AndDescr lhs = rule.getLhs(); @@ -387,7 +396,7 @@ void parse_orWithSpecialBind() { @Test void parse_compatibleRestriction() { String source = "package com.sample rule test when Test( ( text == null || text2 matches \"\" ) ) then end"; - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("com.sample"); RuleDescr rule = pkg.getRules().get(0); @@ -399,7 +408,7 @@ void parse_compatibleRestriction() { @Test void parse_simpleConstraint() { String source = "package com.sample rule test when Cheese( type == 'stilton', price > 10 ) then end"; - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("com.sample"); RuleDescr rule = pkg.getRules().get(0); @@ -417,7 +426,7 @@ void parse_simpleConstraint() { @Test void parse_stringEscapes() { String source = "package com.sample rule test when Cheese( type matches \"\\..*\\\\.\" ) then end"; - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("com.sample"); RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("test"); @@ -433,7 +442,7 @@ void parse_stringEscapes() { @Test void parse_dialectWithSingleQuotation() { final String source = "dialect 'mvel'"; - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); AttributeDescr attr = pkg.getAttributes().get(0); assertThat(attr.getName()).isEqualTo("dialect"); assertThat(attr.getValue()).isEqualTo("mvel"); @@ -442,7 +451,7 @@ void parse_dialectWithSingleQuotation() { @Test void parse_dialectWithDoubleQuotation() { final String source = "dialect \"mvel\""; - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); AttributeDescr attr = pkg.getAttributes().get(0); assertThat(attr.getName()).isEqualTo("dialect"); assertThat(attr.getValue()).isEqualTo("mvel"); @@ -451,11 +460,13 @@ void parse_dialectWithDoubleQuotation() { @Test void parse_emptyRuleWithoutWhen() throws Exception { String source = readResource("empty_rule.drl"); // without WHEN - parser.parse(source); + RuleDescr ruleDescr = parseAndGetFirstRuleDescr(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isTrue(); + assertThat(ruleDescr).isNotNull(); - // Note : RuleParserTest.testEmptyRule allows this DRL, but I think is doesn't make sense to pass this DRL + assertThat(ruleDescr.getName()).isEqualTo("empty"); + assertThat(ruleDescr.getLhs()).isNotNull(); + assertThat(ruleDescr.getConsequence()).isNotNull(); } @Test @@ -465,17 +476,15 @@ void parse_keywordCollisions() throws Exception { // Note: eol_funny_business.drl is modified from the one under drools-test-coverage to be more realistic. // e.g. "package" is not allowed in a package value in Java, so it doesn't make sense to test. (Right to raise a parser error) - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - + PackageDescr pkg = parseAndGetPackageDescr(source); + assertThat(pkg.getRules()).hasSize(1); } @Test void parse_ternaryExpression() throws Exception { String source = readResource("ternary_expression.drl"); - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); assertThat(pkg.getRules()).hasSize(1); @@ -491,7 +500,7 @@ void parse_functionWithArrays() throws Exception { // new String[3] {"a","b","c"} is invalid in Java (Cannot define dimension expressions when an array initializer is provided) // , so it doesn't make sense to test. (Right to raise a parser error) - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("foo"); assertThat(pkg.getRules()).hasSize(1); @@ -510,9 +519,8 @@ void parse_functionWithArrays() throws Exception { @Test void parse_almostEmptyRule() throws Exception { String source = readResource("almost_empty_rule.drl"); - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(pkg).isNotNull(); RuleDescr rule = pkg.getRules().get(0); @@ -525,9 +533,7 @@ void parse_almostEmptyRule() throws Exception { @Test void parse_quotedStringNameRule() throws Exception { String source = readResource("quoted_string_name_rule.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); RuleDescr rule = pkg.getRules().get(0); assertThat(rule).isNotNull(); @@ -540,9 +546,7 @@ void parse_quotedStringNameRule() throws Exception { @Test void parse_noLoop() throws Exception { String source = readResource("no-loop.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); RuleDescr rule = pkg.getRules().get(0); assertThat(rule).isNotNull(); @@ -556,9 +560,7 @@ void parse_noLoop() throws Exception { @Test void parse_autofocus() throws Exception { String source = readResource("autofocus.drl"); - PackageDescr pkg = parser.parse(source); - - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); RuleDescr rule = pkg.getRules().get(0); assertThat(rule).isNotNull(); @@ -572,9 +574,9 @@ void parse_autofocus() throws Exception { @Test void parse_ruleFlowGroup() throws Exception { String source = readResource("ruleflowgroup.drl"); - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); + - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); RuleDescr rule = pkg.getRules().get(0); assertThat(rule).isNotNull(); @@ -588,12 +590,12 @@ void parse_ruleFlowGroup() throws Exception { @Test void parse_consequenceWithDeclaration() throws Exception { String source = readResource("declaration-in-consequence.drl"); - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); // Note : Removed "i\i;" from the original declaration-in-consequence.drl under drools-test-coverage // because it's not a valid java expression and doesn't make sense to test. (Right to raise a parser error) - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = pkg.getRules().get(0); assertThat(rule).isNotNull(); @@ -619,10 +621,10 @@ void parse_consequenceWithDeclaration() throws Exception { @Test void parse_or() { final String text = "rule X when Person(age < 42, location==\"atlanta\") \nor\nPerson(name==\"bob\") then end"; - PackageDescr pkg = parser.parse(text); + PackageDescr pkg = parseAndGetPackageDescr(text); RuleDescr rule = pkg.getRules().get(0); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(rule).isNotNull(); @@ -634,10 +636,10 @@ void parse_or() { @Test void parse_lhsWithStringQuotes() { final String text = "rule X when Person( location==\"atlanta\\\"\") then end\n"; - PackageDescr pkg = parser.parse(text); + PackageDescr pkg = parseAndGetPackageDescr(text); RuleDescr rule = pkg.getRules().get(0); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(rule).isNotNull(); @@ -650,9 +652,9 @@ void parse_lhsWithStringQuotes() { @Test void parse_lhsWithStringQuotesEscapeChars() { final String text = "rule X when Cheese( $x: type, type == \"s\\tti\\\"lto\\nn\" ) then end\n"; - PackageDescr pkg = parser.parse(text); + PackageDescr pkg = parseAndGetPackageDescr(text); RuleDescr rule = pkg.getRules().get(0); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(rule).isNotNull(); @@ -702,9 +704,9 @@ void parse_literalBoolAndNegativeNumbersRule() throws Exception { @Test void parse_emptyPattern() throws Exception { String source = readResource("test_EmptyPattern.drl"); - PackageDescr pkg = parser.parse(source); + PackageDescr pkg = parseAndGetPackageDescr(source); + - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(pkg.getRules()).hasSize(1); final RuleDescr ruleDescr = pkg.getRules().get(0); @@ -913,7 +915,7 @@ public void parse_LineNumberIncludingCommentsInRHS() throws Exception { PackageDescr pkg = parseAndGetPackageDescrFromFile( "test_CommentLineNumbersInConsequence.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + final String rhs = (String) ((RuleDescr) pkg.getRules().get( 0 )).getConsequence(); String expected = "\\s*//woot$\\s*first;$\\s*$\\s*//$\\s*$\\s*/\\* lala$\\s*$\\s*\\*/$\\s*second;$\\s*"; @@ -926,7 +928,7 @@ public void parse_LhsSemicolonDelim() throws Exception { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( "lhs_semicolon_delim.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(rule).isNotNull(); @@ -977,7 +979,7 @@ public void parse_NotNode() throws Exception { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( "rule_not.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(rule).isNotNull(); assertThat(rule.getName()).isEqualTo("simple_rule"); @@ -1003,7 +1005,7 @@ public void parse_NotExistWithBrackets() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "not_exist_with_brackets.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); @@ -1430,7 +1432,7 @@ void parenthesesAndOrOr() { " (Foo(x == 1) and Bar(x == 2)) or (Foo(x == 3) or Bar(x == 4))\n" + " then\n" + "end"; - PackageDescr pkg = parser.parse(drl); + PackageDescr pkg = parseAndGetPackageDescr(drl); assertThat(pkg.getRules()).hasSize(1); final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); @@ -1462,7 +1464,7 @@ void parenthesesOrAndAnd() { " (Foo(x == 1) or Bar(x == 2)) and (Foo(x == 3) and Bar(x == 4))\n" + " then\n" + "end"; - PackageDescr pkg = parser.parse(drl); + PackageDescr pkg = parseAndGetPackageDescr(drl); assertThat(pkg.getRules()).hasSize(1); final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); @@ -1491,7 +1493,7 @@ void multipleLevelNestAndOrOrOrAnd() throws Exception { " (Foo(x == 1) and (Bar(x == 2) or Foo(x == 3))) or (Bar(x == 4) or (Foo(x == 5) and Bar(x == 6)))\n" + " then\n" + "end"; - PackageDescr pkg = parser.parse(drl); + PackageDescr pkg = parseAndGetPackageDescr(drl); assertThat(pkg.getRules()).hasSize(1); final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); @@ -1531,7 +1533,7 @@ void multipleLevelNestWithThreeOrSiblings() throws Exception { " (A() or (B() or C() or (D() and E())))\n" + " then\n" + "end"; - PackageDescr pkg = parser.parse(drl); + PackageDescr pkg = parseAndGetPackageDescr(drl); assertThat(pkg.getRules()).hasSize(1); final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); @@ -1566,7 +1568,7 @@ public void existsMultipleLevelNestWithThreeOrSiblings() throws Exception { " exists(A() or (B() or C() or (D() and E())))\n" + " then\n" + "end"; - PackageDescr pkg = parser.parse(drl); + PackageDescr pkg = parseAndGetPackageDescr(drl); assertThat(pkg.getRules()).hasSize(1); final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); @@ -1770,7 +1772,7 @@ public void parse_Attributes() throws Exception { public void parse_Attributes2() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "rule_attributes2.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + List rules = pkg.getRules(); assertThat(rules.size()).isEqualTo(3); @@ -1813,10 +1815,10 @@ public void parse_Attributes2() throws Exception { public void parse_AttributeRefract() throws Exception { final String source = "rule Test refract when Person() then end"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); assertThat(rule.getName()).isEqualTo("Test"); @@ -1893,7 +1895,7 @@ public void parse_Calendars() throws Exception { public void parse_Calendars2() throws Exception { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( "rule_calendars_attribute2.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(rule.getName()).isEqualTo("simple_rule"); assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); @@ -1981,7 +1983,7 @@ public void parse_Enumeration() throws Exception { public void parse_ExtraLhsNewline() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "extra_lhs_newline.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + } @Test @@ -2068,7 +2070,7 @@ public void parse_RuleNamesStartingWithNumbers() throws Exception { public void parse_EvalWithNewline() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "eval_with_newline.drl"); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + } @Test @@ -2401,7 +2403,7 @@ public void parse_Semicolon() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "semicolon.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); assertThat(pkg.getGlobals().size()).isEqualTo(1); @@ -2559,7 +2561,7 @@ public void parse_AccumulateMnemonic() throws Exception { " $a1 : average( $price ) )\n" + "then\n" + "end\n"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( drl ); assertThat(pkg.getRules().size()).isEqualTo(1); @@ -2591,7 +2593,7 @@ public void parse_AccumulateMnemonic2() throws Exception { " average( $price ) )\n" + "then\n" + "end\n"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( drl ); assertThat(pkg.getRules().size()).isEqualTo(1); @@ -2625,7 +2627,7 @@ public void parse_ImportAccumulate() throws Exception { " $v2 : baz2( $price ) )\n" + "then\n" + "end\n"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( drl ); assertThat(pkg.getAccumulateImports().size()).isEqualTo(2); @@ -2799,7 +2801,7 @@ public void parse_PluggableOperators() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "pluggable_operators.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + assertThat(pkg.getRules().size()).isEqualTo(1); final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); @@ -2845,7 +2847,7 @@ public void parse_PluggableOperators() throws Exception { public void parse_RuleMetadata() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "Rule_with_Metadata.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + // @fooAttribute(barValue) // @fooAtt2(barVal2) @@ -2863,7 +2865,7 @@ public void parse_RuleExtends() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "Rule_with_Extends.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = pkg.getRules().get( 0 ); assertThat(rule.getParentName() != null).isTrue(); @@ -2883,7 +2885,7 @@ public void parse_RuleExtends() throws Exception { public void parse_TypeDeclarationWithFields() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "declare_type_with_fields.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + List td = pkg.getTypeDeclarations(); assertThat(td.size()).isEqualTo(3); @@ -2933,7 +2935,7 @@ public void parse_TypeDeclarationWithFields() throws Exception { public void parenthesesOneLevelNestWithThreeSiblings() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "Rule_with_nested_LHS.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = pkg.getRules().get( 0 ); assertThat(rule.getName()).isEqualTo("test"); @@ -2974,9 +2976,9 @@ public void parenthesesOneLevelNestWithThreeSiblings() throws Exception { public void parse_EntryPoint() throws Exception { final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point StreamA then end"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( text ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = pkg.getRules().get( 0 ); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); @@ -2994,9 +2996,9 @@ public void parse_EntryPoint() throws Exception { public void parse_EntryPoint2() throws Exception { final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point \"StreamA\" then end"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( text ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = pkg.getRules().get( 0 ); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); @@ -3014,8 +3016,8 @@ public void parse_EntryPoint2() throws Exception { public void parse_SlidingWindow() throws Exception { final String text = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end"; - PackageDescr pkg = parser.parse( text ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr( text ); + RuleDescr rule = pkg.getRules().get( 0 ); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); @@ -3037,10 +3039,10 @@ public void parse_SlidingWindow() throws Exception { public void parse_RuleOldSyntax1() throws Exception { final String source = "rule \"Test\" when ( not $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); assertThat(rule.getName()).isEqualTo("Test"); @@ -3058,10 +3060,10 @@ public void parse_RuleOldSyntax1() throws Exception { public void parse_RuleOldSyntax2() throws Exception { final String source = "rule \"Test\" when ( $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( source ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); assertThat(rule.getName()).isEqualTo("Test"); @@ -3079,7 +3081,7 @@ public void parse_TypeWithMetaData() throws Exception { PackageDescr pkg = parseAndGetPackageDescrFromFile( "type_with_meta.drl" ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + final List declarations = pkg.getTypeDeclarations(); @@ -3142,7 +3144,7 @@ public void parse_FromFollowedByQuery() throws Exception { final String text = "rule X when Cheese() from $cheesery ?person( \"Mark\", 42; ) then end"; RuleDescr rule = parseAndGetFirstRuleDescr( text ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); assertThat(pattern.getObjectType()).isEqualTo("Cheese"); @@ -3162,7 +3164,7 @@ public void parse_FromWithTernaryFollowedByQuery() throws Exception { final String text = "rule X when Cheese() from (isFull ? $cheesery : $market) ?person( \"Mark\", 42; ) then end"; RuleDescr rule = parseAndGetFirstRuleDescr( text ); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); assertThat(pattern.getObjectType()).isEqualTo("Cheese"); @@ -3341,7 +3343,7 @@ public void parse_EntryPointDeclaration() throws Exception { " @source(\"jndi://queues/events\")\n" + " @foo( true )\n" + "end"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( text ); assertThat(pkg.getName()).isEqualTo("org.drools"); @@ -3364,7 +3366,7 @@ public void parse_WindowDeclaration() throws Exception { " over window:length( 10, $s.symbol )\n" + " from entry-point stStream\n" + "end"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( text ); assertThat(pkg.getName()).isEqualTo("org.drools"); @@ -3399,7 +3401,7 @@ public void parse_WindowUsage() throws Exception { " StockTick() from window Y\n" + "then\n" + "end\n"; - PackageDescr pkg = parser.parse( + PackageDescr pkg = parseAndGetPackageDescr( text ); assertThat(pkg.getName()).isEqualTo("org.drools"); @@ -3425,7 +3427,7 @@ public void endInRhs() throws Exception { "then\n" + " System.out.println($s.endsWith(\"xyz\"));\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text ); + PackageDescr packageDescr = parseAndGetPackageDescr(text ); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("System.out.println($s.endsWith(\"xyz\"));"); @@ -3440,7 +3442,7 @@ public void endTokenInRhs() throws Exception { "then\n" + " int end = 10;\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text ); + PackageDescr packageDescr = parseAndGetPackageDescr(text ); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int end = 10;"); @@ -3455,7 +3457,7 @@ public void ruleTokenInRhs() throws Exception { "then\n" + " int rule = 10;\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text ); + PackageDescr packageDescr = parseAndGetPackageDescr(text ); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int rule = 10;"); @@ -3469,7 +3471,7 @@ void semicolonEnd() { " $s : String()\n" + "then\n" + " delete($s);end\n"; // no space after semicolon - PackageDescr packageDescr = parser.parse(text ); + PackageDescr packageDescr = parseAndGetPackageDescr(text ); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("delete($s);"); @@ -3483,7 +3485,7 @@ void braceEnd() { " $p : Person()\n" + "then\n" + " modify($p) { setAge(2) }end\n"; // no space after right brace - PackageDescr packageDescr = parser.parse(text ); + PackageDescr packageDescr = parseAndGetPackageDescr(text ); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("modify($p) { setAge(2) }"); @@ -3497,12 +3499,86 @@ void parenthesisEnd() { " $p : Person()\n" + "then\n" + " retract($p)end\n"; // no space after right parenthesis - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("retract($p)"); } + @Test + void endAndRuleInSameLine() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p)\n" + + "end rule R2 when Person() then end"; // 'rule' after 'end' in the same line + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndAttributeAndRuleInSameLine() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p)\n" + + "end no-loop true rule R2 when Person() then end"; // 'end', attribute, 'rule' in the same line + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + assertThat(packageDescr.getAttributes().get(0).getName()).isEqualTo("no-loop"); // package level attribute + } + + @Test + void endAndSingleLineCommentAndRule() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p)\n" + + "end\n" + + "// comment\n" + + "rule R2 when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndMultiLineCommentAndRule() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p)\n" + + "end\n" + + "/* comment\n" + + "comment */\n" + + "rule R2 when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + @Test void singleQuoteInRhsWithSpace() { String consequence = getResultConsequence(" System.out.println( 'singleQuoteInRhs' );\n"); @@ -3535,7 +3611,7 @@ private String getResultConsequence(String rhs) { "then\n" + rhs + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); return ruleDescr.getConsequence().toString(); @@ -3551,7 +3627,7 @@ void ruleDescrProperties() { " retract($p);\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); @@ -3588,7 +3664,7 @@ void constraintOperators(String constraint) { "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); AndDescr lhs = ruleDescr.getLhs(); @@ -3620,7 +3696,7 @@ void halfConstraintOperators(String constraint) { "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); AndDescr lhs = ruleDescr.getLhs(); @@ -3637,7 +3713,7 @@ void nullSafeDereferencing() { " $p : Person(address!.city == $city)\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("address!.city == $city"); } @@ -3650,7 +3726,7 @@ void nullSafeDereferencingMethodCall() { " $p : Person(address!.city!.startsWith(\"M\"))\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("address!.city!.startsWith(\"M\")"); } @@ -3663,7 +3739,7 @@ void nullSafeDereferencingMethodCallBindVariable() { " $p : Person( $containsL : address!.city.contains(\"L\") )\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("$containsL : address!.city.contains(\"L\")"); } @@ -3676,7 +3752,7 @@ void groupedConstraints() { " $p : Person( address.(city.startsWith(\"I\") && city.length() == 5 ) )\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()) .as("prefix should be appended to each element") @@ -3691,7 +3767,7 @@ void groupedConstraintsWithNullSafeDereferencing() { " $p : Person( address!.(city!.startsWith(\"I\") && city!.length() == 5 ) )\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()) .as("prefix should be appended to each element") @@ -3701,8 +3777,8 @@ void groupedConstraintsWithNullSafeDereferencing() { @Test public void functionWithStringLiteral() { final String text = "function String star(String s) { return \"*\"; }"; - PackageDescr packageDescr = parser.parse(text); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr packageDescr = parseAndGetPackageDescr(text); + FunctionDescr function = packageDescr.getFunctions().get( 0 ); @@ -3716,8 +3792,8 @@ public void functionWithStringLiteral() { @Test public void functionWithStringLiteralAddition() { final String text = "function String addStar(String s) { return s + \"*\"; }"; - PackageDescr packageDescr = parser.parse(text); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr packageDescr = parseAndGetPackageDescr(text); + FunctionDescr function = packageDescr.getFunctions().get( 0 ); @@ -3734,8 +3810,8 @@ public void functionWithMultipleBlockStatements() { " String result = s + \"*\";\n" + " return result;\n" + "}"; - PackageDescr packageDescr = parser.parse(text); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr packageDescr = parseAndGetPackageDescr(text); + FunctionDescr function = packageDescr.getFunctions().get( 0 ); @@ -3754,8 +3830,8 @@ void lhsPatternAnnotation() { " $p : Person( name == \"Mario\" ) @watch(!*, age)\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); @@ -3773,7 +3849,7 @@ void fromNew() { " $p : Person() from new Person(\"John\", 30)\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); FromDescr fromDescr = (FromDescr) patternDescr.getSource(); @@ -3788,8 +3864,7 @@ public void expiresWithTimeLiteralValue() { " @expires( value = 2s, policy = TIME_SOFT )\n" + "end"; - PackageDescr packageDescr = parser.parse(text); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr packageDescr = parseAndGetPackageDescr(text); AnnotationDescr annotationDescr = packageDescr .getTypeDeclarations().get(0) @@ -3807,7 +3882,7 @@ void ooPath() { " $man: Man( /wife/children[age > 10] )\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()) .isEqualToIgnoringWhitespace("/wife/children[age > 10]"); @@ -3827,7 +3902,7 @@ void ooPathWithBindingInBrackets() { " Man( /wife[$age : age] )\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()) .isEqualToIgnoringWhitespace("/wife[$age : age]"); @@ -3840,7 +3915,7 @@ void ooPathWithBindingInParentheses() { " Man( $toy: /wife/children[age > 10]/toys )\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()) .isEqualToIgnoringWhitespace("$toy: /wife/children[age > 10]/toys"); @@ -3854,7 +3929,7 @@ void ooPathWithBackReference() { "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()) .isEqualToIgnoringWhitespace("$toy: /wife/children/toys[ name.length == ../name.length ]"); @@ -3868,7 +3943,7 @@ void ooPathMixedWithStandardConstraint() { "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()) .isEqualToIgnoringWhitespace("/wife[$age : age] && age > $age"); @@ -3882,7 +3957,7 @@ void inlineCast() { " $a : ICA( someB#ICB.onlyConcrete() == \"Hello\" )\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("someB#ICB.onlyConcrete() == \"Hello\""); } @@ -3895,7 +3970,7 @@ void inlineCastMultiple() { " $a : ICA( someB#ICB.someC#ICC.onlyConcrete() == \"Hello\" )\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("someB#ICB.someC#ICC.onlyConcrete() == \"Hello\""); } @@ -3908,7 +3983,7 @@ void inlineCastThis() { " $o : Object( this#Person.name == \"Mark\" )\n" + "then\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("this#Person.name == \"Mark\""); } @@ -3987,8 +4062,7 @@ public void queryNoArgument() throws Exception { public void traitExtendsMultiple() throws Exception { final String source = "declare trait FatherTrait extends com.sample.ParentTrait, UncleTrait, org.test.GrandParentTrait end"; - PackageDescr pkg = parser.parse(source); - assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + PackageDescr pkg = parseAndGetPackageDescr(source); final List declarations = pkg.getTypeDeclarations(); @@ -4034,13 +4108,13 @@ void namedConsequenceDo() { "then[FoundMark]\n" + " $r.addValue(\"Found \" + $p1.getName());\n" + "end"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMark"); - assertThat(ruleDescr.getConsequence().toString()).isEqualTo("$r.addValue($p2.getName() + \" is older than \" + $p1.getName());"); - assertThat(ruleDescr.getNamedConsequences().get("FoundMark").toString()).isEqualTo("$r.addValue(\"Found \" + $p1.getName());"); + assertThat(ruleDescr.getConsequence().toString().trim()).isEqualTo("$r.addValue($p2.getName() + \" is older than \" + $p1.getName());"); + assertThat(ruleDescr.getNamedConsequences().get("FoundMark").toString().trim()).isEqualTo("$r.addValue(\"Found \" + $p1.getName());"); } @Test @@ -4057,7 +4131,7 @@ void namedConsequenceIfElse() { "then[t2]\n" + " results.add( $a.getType().toUpperCase() );\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(1); assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); @@ -4079,7 +4153,7 @@ void namedConsequenceIfElseBreak() { "then[t2]\n" + " results.add( $a.getType().toUpperCase() );\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(1); assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); @@ -4101,7 +4175,7 @@ void namedConsequenceNestedIf() { "then[t2]\n" + " results.add( $a.getType().toUpperCase() );\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(1); assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); @@ -4124,7 +4198,7 @@ void namedConsequenceAfterExists() { "then[FoundMark]\n" + " $r.addValue(\"Found \" + $p1.getName());\n" + "end"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMark"); @@ -4143,7 +4217,7 @@ void namedConsequenceAfterNot() { "then[FoundMark]\n" + " $r.addValue(\"NotFound \" + $p1.getName());\n" + "end"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); assertThat(namedConsequenceDescr.getName()).isEqualTo("NotFoundMark"); @@ -4163,7 +4237,7 @@ void namedConsequenceIfElseAfterEval() { "then[t2]\n" + " results.add( $a.getType().toUpperCase() );\n" + "end\n"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(2); assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); @@ -4184,7 +4258,7 @@ void namedConsequenceAfterEnclosed() { "then[FoundMark]\n" + " $r.addValue(\"Found \" + $p1.getName());\n" + "end"; - PackageDescr packageDescr = parser.parse(text); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMarkOrMario"); 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 new file mode 100644 index 00000000000..f0d1f854d26 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java @@ -0,0 +1,35 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import org.drools.drl.parser.DrlParser; + +public class ParserTestUtils { + + private ParserTestUtils() { + // It is a utility class, so it should not be instantiated. + } + + /** + * Returns a DrlParser which encapsulates an old or new parser depending on system property + */ + public static DrlParser getParser() { + return new DrlParser(); + } +} 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/DRLLexer.g4 index 631d2a49a18..52716591ad9 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/DRLLexer.g4 @@ -12,6 +12,10 @@ import JavaLexer; } return input; } + + public boolean isRhsDrlEnd() { + return new LexerHelper(_input).isRhsDrlEnd(); + } } ///////////////// @@ -164,7 +168,8 @@ DrlUnicodeEscape mode RHS; RHS_WS : [ \t\r\n\u000C]+ -> channel(HIDDEN); -DRL_RHS_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) {setText("end");} -> popMode; +//DRL_RHS_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) { setText("end"); } -> popMode; +DRL_RHS_END : {isRhsDrlEnd()}? DRL_END -> popMode; RHS_STRING_LITERAL // cannot reuse DRL_STRING_LITERAL because Actions are ignored in referenced rules @@ -184,4 +189,4 @@ RHS_CHUNK | RBRACE | COMMA | SEMI - ; + ; \ No newline at end of file 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/DRLParser.g4 index f4358ccf701..2bc5e37f5eb 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/DRLParser.g4 @@ -17,24 +17,24 @@ import DRL6Expressions, JavaParser; compilationUnit : packagedef? unitdef? drlStatementdef* ; drlStatementdef - : importdef - | globaldef - | declaredef - | ruledef - | attributes - | functiondef - | querydef + : importdef SEMI? + | globaldef SEMI? + | declaredef SEMI? + | ruledef SEMI? + | attributes SEMI? + | functiondef SEMI? + | querydef SEMI? ; packagedef : PACKAGE name=drlQualifiedName SEMI? ; unitdef : DRL_UNIT name=drlQualifiedName SEMI? ; -importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? SEMI? #importStandardDef - | IMPORT (DRL_ACCUMULATE|DRL_ACC) drlQualifiedName IDENTIFIER SEMI? #importAccumulateDef +importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? #importStandardDef + | IMPORT (DRL_ACCUMULATE|DRL_ACC) drlQualifiedName IDENTIFIER #importAccumulateDef ; -globaldef : DRL_GLOBAL type drlIdentifier SEMI? ; +globaldef : DRL_GLOBAL type drlIdentifier ; /** * declare := DECLARE @@ -60,15 +60,15 @@ declaredef : DRL_DECLARE ( * END */ -typeDeclaration : DRL_TRAIT? name=drlQualifiedName (EXTENDS superTypes+=drlQualifiedName (COMMA superTypes+=drlQualifiedName)* )? drlAnnotation* field* DRL_END SEMI?; +typeDeclaration : DRL_TRAIT? name=drlQualifiedName (EXTENDS superTypes+=drlQualifiedName (COMMA superTypes+=drlQualifiedName)* )? drlAnnotation* field* DRL_END ; // entryPointDeclaration := ENTRY-POINT stringId annotation* END -entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* DRL_END SEMI?; +entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* DRL_END ; // windowDeclaration := WINDOW ID annotation* lhsPatternBind END -windowDeclaration : DRL_WINDOW name=IDENTIFIER drlAnnotation* lhsPatternBind DRL_END SEMI?; +windowDeclaration : DRL_WINDOW name=IDENTIFIER drlAnnotation* lhsPatternBind DRL_END ; // field := label fieldType (EQUALS_ASSIGN conditionalExpression)? annotation* SEMICOLON? @@ -76,11 +76,11 @@ field : label type (ASSIGN initExpr=conditionalOrExpression)? drlAnnotation* SEM // rule := RULE stringId (EXTENDS stringId)? annotation* attributes? lhs? rhs END -ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* attributes? lhs rhs DRL_RHS_END ; +ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* attributes? lhs? rhs DRL_RHS_END ; // query := QUERY stringId parameters? annotation* lhsExpression END -querydef : DRL_QUERY name=stringId parameters? drlAnnotation* lhsExpression+ DRL_END SEMI?; +querydef : DRL_QUERY name=stringId parameters? drlAnnotation* lhsExpression+ DRL_END ; // parameters := LEFT_PAREN ( parameter ( COMMA parameter )* )? RIGHT_PAREN parameters : LPAREN ( parameter ( COMMA parameter )* )? RPAREN ; 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 4bad571401f..5e6fb78c6f2 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 @@ -60,7 +60,9 @@ public class DrlParser { private Resource resource = null; public static final String ANTLR4_PARSER_ENABLED_PROPERTY = "drools.drl.antlr4.parser.enabled"; - public static final boolean ANTLR4_PARSER_ENABLED = Boolean.parseBoolean(System.getProperty(ANTLR4_PARSER_ENABLED_PROPERTY, "true")); // default is true + + // TODO: temporarily removed 'final' for testing purposes. This should be final + public static boolean ANTLR4_PARSER_ENABLED = Boolean.parseBoolean(System.getProperty(ANTLR4_PARSER_ENABLED_PROPERTY, "true")); // default is true public static final LanguageLevelOption DEFAULT_LANGUAGE_LEVEL = LanguageLevelOption.DRL6; private final LanguageLevelOption languageLevel; 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 526aaddf24e..83452cdc43c 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 @@ -148,6 +148,11 @@ public UnitDescr visitUnitdef(DRLParser.UnitdefContext ctx) { .build(); } + @Override + public BaseDescr visitDrlStatementdef(DRLParser.DrlStatementdefContext ctx) { + return visitDescrChildren(ctx).get(0); // only one child. Ignore SEMICOLON + } + @Override public GlobalDescr visitGlobaldef(DRLParser.GlobaldefContext ctx) { return BaseDescrFactory.builder(new GlobalDescr(ctx.drlIdentifier().getText(), ctx.type().getText())) @@ -290,7 +295,9 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { List lhsDescrList = visitLhs(ctx.lhs()); lhsDescrList.forEach(descr -> rootDescr.addDescr(descr)); slimLhsRootDescr(rootDescr); - DescrHelper.refreshRootProperties(rootDescr); + DescrHelper.populateCommonProperties(rootDescr, ctx.lhs().lhsExpression()); + } else { + ruleDescr.setLhs(new AndDescr()); } if (ctx.rhs() != null) { 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 9cdc65b94dc..b091b8f588f 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 @@ -21,8 +21,11 @@ import java.util.List; import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; import org.drools.drl.ast.descr.PatternDescr; /** @@ -35,29 +38,38 @@ private DescrHelper() { } public static T populateCommonProperties(T descr, ParserRuleContext ctx) { - descr.setStartCharacter(ctx.getStart().getStartIndex()); - // TODO: Current DRL6Parser adds +1 for EndCharacter but it doesn't look reasonable. At the moment, I don't add. Instead, I fix unit tests. - // I will revisit if this is the right approach. - descr.setEndCharacter(ctx.getStop().getStopIndex()); - descr.setLocation(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); - descr.setEndLocation(ctx.getStop().getLine(), ctx.getStop().getCharPositionInLine() + ctx.getStop().getText().length() - 1); // last column of the end token + + if (descr instanceof ExprConstraintDescr) { + // Backward Compatibility Notes: + // Old DRL6Parser.constraint() has slightly different behavior for ExprConstraintDescr. Keep it for backward compatibility + // When we will update LanguageLevel, we can align this with other Descr. + descr.setStartCharacter(ctx.getStart().getStartIndex()); + descr.setEndCharacter(ctx.getStop().getStopIndex()); + descr.setLocation(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); + descr.setEndLocation(ctx.getStop().getLine(), ctx.getStop().getCharPositionInLine()); + } else { + descr.setStartCharacter(ctx.getStart().getStartIndex()); + // Backward Compatibility Notes: + // Old DRL6Parser adds +1 for EndCharacter (except ExprConstraintDescr). This new parser follows the same to keep the backward compatibility. + // However, it doesn't look reasonable. When we will update LanguageLevel, we can remove this +1. + descr.setEndCharacter(ctx.getStop().getStopIndex() + 1); + descr.setLocation(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); + descr.setEndLocation(ctx.getStop().getLine(), ctx.getStop().getCharPositionInLine() + ctx.getStop().getText().length() - 1); // last column of the end token + } return descr; } - /** - * LHS rootDescr requires special handling for properties, because it rearranges its children. - */ - public static AndDescr refreshRootProperties(AndDescr descr) { - List childDescrs = descr.getDescrs(); - if (childDescrs.isEmpty()) { + public static T populateCommonProperties(T descr, List ctxList) { + if (ctxList.isEmpty()) { return descr; } - BaseDescr firstChild = childDescrs.get(0); - BaseDescr lastChild = childDescrs.get(childDescrs.size() - 1); - descr.setStartCharacter(firstChild.getStartCharacter()); - descr.setEndCharacter(lastChild.getEndCharacter()); - descr.setLocation(firstChild.getLine(), firstChild.getColumn()); - descr.setEndLocation(lastChild.getEndLine(), lastChild.getEndColumn()); + ParserRuleContext firstCtx = ctxList.get(0); + ParserRuleContext lastCtx = ctxList.get(ctxList.size() - 1); + + descr.setStartCharacter(firstCtx.getStart().getStartIndex()); + descr.setEndCharacter(lastCtx.getStop().getStopIndex() + 1); + descr.setLocation(firstCtx.getStart().getLine(), firstCtx.getStart().getCharPositionInLine()); + descr.setEndLocation(lastCtx.getStop().getLine(), lastCtx.getStop().getCharPositionInLine() + lastCtx.getStop().getText().length() - 1); // last column of the end token return descr; } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java new file mode 100644 index 00000000000..479eebce85e --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java @@ -0,0 +1,161 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.List; + +import org.antlr.v4.runtime.CharStream; +import org.antlr.v4.runtime.IntStream; +import org.drools.drl.parser.lang.DroolsSoftKeywords; + +/** + * Helper class for lexer. It requires instance creation to keep track of the lookahead counter. + */ +public class LexerHelper { + + private static final List semiAndWS = List.of(';', ' ', '\t', '\n', '\r'); + private static final List statementKeywordsList = List.of(ParserHelper.statementKeywords); + private static final List attributeKeywordsList = List.of(DroolsSoftKeywords.SALIENCE, + DroolsSoftKeywords.ENABLED, + DroolsSoftKeywords.NO + "-" + DroolsSoftKeywords.LOOP, + DroolsSoftKeywords.AUTO + "-" + DroolsSoftKeywords.FOCUS, + DroolsSoftKeywords.LOCK + "-" + DroolsSoftKeywords.ON + "-" + DroolsSoftKeywords.ACTIVE, + DroolsSoftKeywords.AGENDA + "-" + DroolsSoftKeywords.GROUP, + DroolsSoftKeywords.ACTIVATION + "-" + DroolsSoftKeywords.GROUP, + DroolsSoftKeywords.RULEFLOW + "-" + DroolsSoftKeywords.GROUP, + DroolsSoftKeywords.DATE + "-" + DroolsSoftKeywords.EFFECTIVE, + DroolsSoftKeywords.DATE + "-" + DroolsSoftKeywords.EXPIRES, + DroolsSoftKeywords.DIALECT, + DroolsSoftKeywords.CALENDARS, + DroolsSoftKeywords.TIMER, + DroolsSoftKeywords.DURATION, + DroolsSoftKeywords.REFRACT, + DroolsSoftKeywords.DIRECT); + + private final CharStream input; + private int lookAheadCounter; + + public LexerHelper(CharStream input) { + this.input = input; + this.lookAheadCounter = 1; + } + + /** + * Determine if the current token is the end of a RHS DRL by lookahead. + * 1. 'end' + * 2. skip semi, WS, and comment + * 3. next token should be EOF or statement or attribute keyword + * + * TODO: This method is low-level and may be too complex in order to keep backward compatibility. + * This could be refactored by going back to a parser rather than the lexer island mode. + */ + boolean isRhsDrlEnd() { + if (!validateDrlEnd()) { + return false; + } + skipSemiAndWSAndComment(); + + return validateEOForNextStatement(); + } + + private boolean validateDrlEnd() { + return captureNextToken().equals(DroolsSoftKeywords.END); + } + + private String captureNextToken() { + StringBuilder sb = new StringBuilder(); + while (true) { + int la = input.LA(lookAheadCounter); + if (semiAndWS.contains((char) la) || la == IntStream.EOF) { + break; + } + sb.append((char) la); + lookAheadCounter++; + } + return sb.toString(); // never null + } + + private void skipSemiAndWSAndComment() { + do { + // skip semi and WS, and repeat that so long as it's followed by a valid and skipped comment + skipSemiAndWS(); + } while (skipComment()); + } + + private void skipSemiAndWS() { + while (true) { + int la = input.LA(lookAheadCounter); + if (!semiAndWS.contains((char) la)) { + break; + } + lookAheadCounter++; + } + } + + // if comment is found, skip it and return true + private boolean skipComment() { + boolean skipped = false; + // skip single line comment + int la1 = input.LA(lookAheadCounter); + int la2 = input.LA(lookAheadCounter + 1); + if (la1 == '/' && la2 == '/') { + // skip single line comment + skipSingleLineComment(); + skipped = true; + } else if (la1 == '/' && la2 == '*') { + // skip multi line comment + skipMultiLineComment(); + skipped = true; + } + + return skipped; + } + + private void skipSingleLineComment() { + while (true) { + int la = input.LA(lookAheadCounter); + if (la == '\n' || la == IntStream.EOF) { // this can handle `\r\n` as well + break; + } + lookAheadCounter++; + } + } + + private void skipMultiLineComment() { + while (true) { + int la = input.LA(lookAheadCounter); + if (la == IntStream.EOF) { + break; + } + if (la == '*' && input.LA(lookAheadCounter + 1) == '/') { + lookAheadCounter += 2; + break; + } + lookAheadCounter++; + } + } + + private boolean validateEOForNextStatement() { + if (input.LA(lookAheadCounter) == IntStream.EOF) { + return true; + } + String nextToken = captureNextToken(); + return statementKeywordsList.contains(nextToken) || attributeKeywordsList.contains(nextToken); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java index 504233edee7..fed7024c20c 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java @@ -91,7 +91,7 @@ * by the DRL parser */ public class ParserHelper { - public final String[] statementKeywords = new String[]{ + public static final String[] statementKeywords = new String[]{ DroolsSoftKeywords.PACKAGE, DroolsSoftKeywords.UNIT, DroolsSoftKeywords.IMPORT, From 25d7d6d8598f39fa01e266495eb73622ca4b76f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 24 Apr 2024 18:53:57 +0200 Subject: [PATCH 090/141] Reuse DRL6Expressions' fullAnnotation rule in DRLParser (#5865) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 23 +++++++++++++++- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 13 +++------- .../drl/parser/antlr4/DRLVisitorImpl.java | 26 +++++++++---------- 3 files changed, 38 insertions(+), 24 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 e617a4dfb49..d561ca0b676 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 @@ -8,6 +8,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -47,7 +48,6 @@ import org.drools.drl.parser.DrlParser; import org.drools.drl.parser.DroolsParserException; import org.drools.drl.parser.impl.Operator; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -3191,6 +3191,7 @@ public void parse_MultiValueAnnotationsBackwardCompatibility() throws Exception ann = rule.getAnnotation( "ann2" ); assertThat(ann).isNotNull(); assertThat(ann.getValue()).isEqualTo("\"val1\", \"val2\""); + assertThat(ann.getSingleValueAsString()).isEqualTo("\"val1\", \"val2\""); } @Test @@ -3838,9 +3839,29 @@ void lhsPatternAnnotation() { AnnotationDescr annotationDescr = patternDescr.getAnnotations().iterator().next(); assertThat(annotationDescr.getName()).isEqualTo("watch"); + assertThat(annotationDescr.getValue()).isEqualTo("!*, age"); assertThat(annotationDescr.getSingleValueAsString()).isEqualTo("!*, age"); } + @Test + void annotationWithEmptyParentheses() { + final String text = "package org.drools;\n" + + "import java.util.*;\n" + + "import org.drools.base.factmodel.traits.*;\n" + + "declare HashMap @Traitable() end \n" + + "declare trait PersonMap\n" + + "@propertyReactive \n" + + " age : Integer @Alias( \"years\" ) \n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + AnnotationDescr annotationDescr = packageDescr.getTypeDeclarations().get(0).getAnnotations().iterator().next(); + + assertThat(annotationDescr.getName()).isEqualTo("Traitable"); + assertThat(annotationDescr.getValue()).isEqualTo(Collections.emptyMap()); + assertThat(annotationDescr.getSingleValueAsString()).isNull(); + } + @Test void fromNew() { final String text = "package org.drools\n" + 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/DRLParser.g4 index 2bc5e37f5eb..093c2133225 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/DRLParser.g4 @@ -413,15 +413,10 @@ type : (classOrInterfaceType | primitiveType) typeArguments? ( DOT IDENTIFIER ty drlArguments : LPAREN drlArgument (COMMA drlArgument)* RPAREN ; drlArgument : ( stringId | floatLiteral | BOOL_LITERAL | NULL_LITERAL ) ; -drlAnnotation : AT name=drlQualifiedName (LPAREN ( drlElementValuePairs | drlElementValue | chunk )? RPAREN)? ; - -drlElementValuePairs : drlElementValuePair (COMMA drlElementValuePair)* ; -drlElementValuePair : key=drlIdentifier ASSIGN value=drlElementValue ; - -drlElementValue - : drlExpression - | drlArrayInitializer - ; +drlAnnotation + // TODO actions can be removed once there is a DRL6ExpressionsVisitorImpl. + : {boolean buildState = buildDescr; buildDescr = true;} anno=fullAnnotation[null] {buildDescr = buildState;} // either standard Java annotation + | AT name=drlQualifiedName (LPAREN chunk RPAREN)? ; // or support @watch(!*, age) etc. attributes : attribute ( COMMA? attribute )* ; attribute : name=( 'salience' | 'enabled' ) conditionalAttributeValue #expressionAttribute 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 83452cdc43c..2febb2f08dd 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 @@ -363,15 +363,21 @@ public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { @Override public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { + // Full Java-style annotation. + if (ctx.anno != null) { + if (ctx.anno.result == null) { + throw new IllegalStateException("anno.result must not be null!"); + } + return BaseDescrFactory.builder(ctx.anno.result) + .withParserRuleContext(ctx) + .build(); + } + + // A chunk that is neither a single value nor a list of key-value pairs. For example `!*, age` in `@watch(!*, age)`. AnnotationDescr annotationDescr = BaseDescrFactory.builder(new AnnotationDescr(ctx.name.getText())) .withParserRuleContext(ctx) .build(); - if (ctx.drlElementValue() != null) { - annotationDescr.setValue(getTextPreservingWhitespace(ctx.drlElementValue())); // single value - } else if (ctx.drlElementValuePairs() != null) { - visitDrlElementValuePairs(ctx.drlElementValuePairs(), annotationDescr); // multiple values - } else if (ctx.chunk() != null) { - // A chunk that is neither a single value nor a list of key-value pairs. For example `!*, age` in `@watch(!*, age)`. + if (ctx.chunk() != null) { annotationDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); } return annotationDescr; @@ -393,14 +399,6 @@ public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { return typeFieldDescr; } - private void visitDrlElementValuePairs(DRLParser.DrlElementValuePairsContext ctx, AnnotationDescr annotationDescr) { - ctx.drlElementValuePair().forEach(pairCtx -> { - String key = pairCtx.key.getText(); - String value = getTextPreservingWhitespace(pairCtx.value); - annotationDescr.setKeyValue(key, value); - }); - } - @Override public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) From c939992832fe34d3d6cd2e80e4f7e5198df551fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 24 Apr 2024 18:54:48 +0200 Subject: [PATCH 091/141] Allow soft keywords in chained method calls (#5864) --- .../java/org/drools/drl/parser/antlr4/DRLExprParserTest.java | 4 ++-- .../antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 | 4 ++-- 2 files changed, 4 insertions(+), 4 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 30a316e24b7..7a866ec2846 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 @@ -248,11 +248,11 @@ public void testDrlKeywordMethodCall(Operator.BuiltInOperator operator) throws E @ParameterizedTest @EnumSource(Operator.BuiltInOperator.class) - public void testDrlKeywordMethodCallBinding(Operator.BuiltInOperator operator) throws Exception { + public void testDrlKeywordInChainedMethodCallWithBinding(Operator.BuiltInOperator operator) throws Exception { // Skip operators that cannot be used as method names (==, !=, <, etc.). assumeFalse(nonKeywordBuiltInOperators.contains(operator)); - String expressionSource = String.format("x.%s( 1, a )", operator.getSymbol()); + String expressionSource = String.format("x.%s( 1, a ).%s(\"\")", operator.getSymbol(), operator.getSymbol()); String bindingVariableSource = "$x"; String source = bindingVariableSource + " : " + expressionSource; ConstraintConnectiveDescr result = parser.parse( source ); 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/DRL6Expressions.g4 index f17ed639366..190bceee75d 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/DRL6Expressions.g4 @@ -807,10 +807,10 @@ selector : DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } super_key superSuffix | DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } new_key (nonWildcardTypeArguments)? innerCreator | DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } - IDENTIFIER { helper.emit($IDENTIFIER, DroolsEditorType.IDENTIFIER); } + id=drlIdentifier { helper.emit($id.token, DroolsEditorType.IDENTIFIER); } (arguments)? | NULL_SAFE_DOT { helper.emit($NULL_SAFE_DOT, DroolsEditorType.SYMBOL); } - IDENTIFIER { helper.emit($IDENTIFIER, DroolsEditorType.IDENTIFIER); } + id=drlIdentifier { helper.emit($id.token, DroolsEditorType.IDENTIFIER); } (arguments)? //| DOT this_key | LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } From 13f5ec7e3e2887b89495d9f422232967c52fecda Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 25 Apr 2024 13:33:00 +0900 Subject: [PATCH 092/141] =?UTF-8?q?[incubator-kie-drools-5714]=20Broken=20?= =?UTF-8?q?QueryTest#testRecursiveQueryWithBa=E2=80=A6=20(#5866)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5714] Broken QueryTest#testRecursiveQueryWithBatchCommand * removed redandunt slimdown and toString --- .../drl/parser/antlr4/MiscDRLParserTest.java | 76 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 4 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 41 +++++----- 3 files changed, 96 insertions(+), 25 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 d561ca0b676..c30164d0f48 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 @@ -4284,4 +4284,80 @@ void namedConsequenceAfterEnclosed() { NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMarkOrMario"); } + + @Test + public void queryComplexLhs() { + final String text = "query isContainedIn(String x, String y)\n" + + " Location (x, y;)\n" + + " or\n" + + " ( Location (z, y;) and ?isContainedIn(x, z;))\n" + + "end\n"; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + AndDescr lhs = query.getLhs(); + assertThat(lhs.getDescrs()).hasSize(1); + + assertThat(lhs.getDescrs().get(0)) + .as("Top level node is OR") + .isInstanceOfSatisfying(OrDescr.class, orDescr -> { + assertThat(orDescr.getDescrs()).hasSize(2); + assertThat(orDescr.getDescrs().get(0)) + .as("Left node of OR is Pattern") + .isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Location"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("x"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(0); + }); + assertThat(patternDescr.getConstraint().getDescrs().get(1)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("y"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(1); + }); + }); + assertThat(orDescr.getDescrs().get(1)) + .as("Right node of OR is AND") + .isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs().get(0)) + .as("Left node of AND is Pattern") + .isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Location"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("z"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(0); + }); + assertThat(patternDescr.getConstraint().getDescrs().get(1)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("y"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(1); + }); + }); + assertThat(andDescr.getDescrs().get(1)) + .as("Right node of AND is Query Pattern") + .isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.isQuery()).isTrue(); + assertThat(patternDescr.getObjectType()).isEqualTo("isContainedIn"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("x"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(0); + }); + assertThat(patternDescr.getConstraint().getDescrs().get(1)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("z"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(1); + }); + }); + }); + }); + } } 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/DRLParser.g4 index 093c2133225..071a3202e36 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/DRLParser.g4 @@ -80,7 +80,7 @@ ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* a // query := QUERY stringId parameters? annotation* lhsExpression END -querydef : DRL_QUERY name=stringId parameters? drlAnnotation* lhsExpression+ DRL_END ; +querydef : DRL_QUERY name=stringId parameters? drlAnnotation* queryLhs DRL_END ; // parameters := LEFT_PAREN ( parameter ( COMMA parameter )* )? RIGHT_PAREN parameters : LPAREN ( parameter ( COMMA parameter )* )? RPAREN ; @@ -90,6 +90,8 @@ parameter : type? drlIdentifier ; // type is optional. Removed (LEFT_SQUARE RIGH lhs : DRL_WHEN lhsExpression* ; +queryLhs : lhsExpression+ ; + lhsExpression : LPAREN lhsExpression RPAREN namedConsequenceInvocation? #lhsExpressionEnclosed | lhsUnary #lhsUnarySingle | LPAREN DRL_AND lhsExpression+ RPAREN #lhsAnd 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 2febb2f08dd..03b9621787f 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 @@ -293,8 +293,19 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { if (ctx.lhs() != null) { final AndDescr rootDescr = ruleDescr.getLhs(); List lhsDescrList = visitLhs(ctx.lhs()); - lhsDescrList.forEach(descr -> rootDescr.addDescr(descr)); - slimLhsRootDescr(rootDescr); + // Root Descr is always AndDescr. + // For example, if there are nested AndDescr like + // AndDescr + // /\ + // P AndDescr + // /\ + // P P + // is slimmed down to + // AndDescr + // / | \ + // P P P + // by addOrMerge() method. + lhsDescrList.forEach(rootDescr::addOrMerge); DescrHelper.populateCommonProperties(rootDescr, ctx.lhs().lhsExpression()); } else { ruleDescr.setLhs(new AndDescr()); @@ -317,23 +328,6 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { return ruleDescr; } - private void slimLhsRootDescr(AndDescr root) { - // Root Descr is always AndDescr. - // For example, if there are nested AndDescr like - // AndDescr - // /\ - // P AndDescr - // /\ - // P P - // is slimmed down to - // AndDescr - // / | \ - // P P P - List descrList = new ArrayList<>(root.getDescrs()); - root.getDescrs().clear(); - descrList.forEach(root::addOrMerge); - } - @Override public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { QueryDescr queryDescr = BaseDescrFactory.builder(new QueryDescr(safeStripStringDelimiters(ctx.name.getText()))) @@ -352,11 +346,10 @@ public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(queryDescr::addAnnotation); - ctx.lhsExpression().stream() - .flatMap(lhsExpressionContext -> visitDescrChildren(lhsExpressionContext).stream()) - .forEach(descr -> queryDescr.getLhs().addDescr(descr)); - - slimLhsRootDescr(queryDescr.getLhs()); + final AndDescr rootDescr = queryDescr.getLhs(); + List lhsDescrList = visitDescrChildren(ctx.queryLhs()); // queryLhs never be null + lhsDescrList.forEach(rootDescr::addOrMerge); + DescrHelper.populateCommonProperties(rootDescr, ctx.queryLhs()); return queryDescr; } From de9b048a2674eeb14792045fe844b6a1aec90480 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 26 Apr 2024 10:20:17 +0900 Subject: [PATCH 093/141] [incubator-kie-drools-5741] [new-parser] Broken enum declaration (#5870) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 35 ++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 11 ++++++ .../drl/parser/antlr4/DRLVisitorImpl.java | 36 +++++++++++++++++++ 3 files changed, 82 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 c30164d0f48..84228270315 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 @@ -25,6 +25,8 @@ import org.drools.drl.ast.descr.ConditionalBranchDescr; import org.drools.drl.ast.descr.EntryPointDeclarationDescr; import org.drools.drl.ast.descr.EntryPointDescr; +import org.drools.drl.ast.descr.EnumDeclarationDescr; +import org.drools.drl.ast.descr.EnumLiteralDescr; import org.drools.drl.ast.descr.EvalDescr; import org.drools.drl.ast.descr.ExistsDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; @@ -4360,4 +4362,37 @@ public void queryComplexLhs() { }); }); } + + @Test + public void enumDeclaration() { + final String text = + "declare enum PersonAge\n" + + " @doc(author=\"Bob\")\n" + + " ELEVEN(11, \"XI\"), TWELVE(12, \"XII\");\n" + + "\n" + + " key: int\n" + + " romanStr : String\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr(text); + + List descrList = pkg.getEnumDeclarations(); + EnumDeclarationDescr enumDeclarationDescr = descrList.get(0); + assertThat(enumDeclarationDescr.getTypeName()).isEqualTo("PersonAge"); + + assertThat(enumDeclarationDescr.getAnnotation("doc").getValue("author")).isEqualTo("\"Bob\""); + + List literals = enumDeclarationDescr.getLiterals(); + EnumLiteralDescr enumLiteralDescr0 = literals.get(0); + assertThat(enumLiteralDescr0.getName()).isEqualTo("ELEVEN"); + assertThat(enumLiteralDescr0.getConstructorArgs()).containsExactly("11", "\"XI\""); + EnumLiteralDescr enumLiteralDescr1 = literals.get(1); + assertThat(enumLiteralDescr1.getName()).isEqualTo("TWELVE"); + assertThat(enumLiteralDescr1.getConstructorArgs()).containsExactly("12", "\"XII\""); + + TypeFieldDescr key = enumDeclarationDescr.getFields().get("key"); + assertThat(key.getPattern().getObjectType()).isEqualTo("int"); + + TypeFieldDescr romanStr = enumDeclarationDescr.getFields().get("romanStr"); + assertThat(romanStr.getPattern().getObjectType()).isEqualTo("String"); + } } 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/DRLParser.g4 index 071a3202e36..fb6a9bf68c6 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/DRLParser.g4 @@ -50,6 +50,7 @@ declaredef : DRL_DECLARE ( | entryPointDeclaration | windowDeclaration | typeDeclaration + | enumDeclaration ) ; // DRL_END belongs to entryPointDeclaration etc. @@ -70,6 +71,16 @@ entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* DRL_END ; windowDeclaration : DRL_WINDOW name=IDENTIFIER drlAnnotation* lhsPatternBind DRL_END ; +// (enum)typeDeclaration := [ENUM] qualifiedIdentifier annotation* enumerative+ field* END + +enumDeclaration : ENUM name=drlQualifiedName drlAnnotation* enumeratives SEMI field* DRL_END ; + +enumeratives : enumerative (COMMA enumerative)* ; + +// enumerative := ID ( LEFT_PAREN expression (COMMA expression)* RIGHT_PAREN )? + +enumerative: drlIdentifier ( LPAREN expression ( COMMA expression )* RPAREN )? ; + // field := label fieldType (EQUALS_ASSIGN conditionalExpression)? annotation* SEMICOLON? field : label type (ASSIGN initExpr=conditionalOrExpression)? drlAnnotation* SEMI? ; 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 03b9621787f..f568256b8ee 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 @@ -38,6 +38,8 @@ import org.drools.drl.ast.descr.ConditionalBranchDescr; import org.drools.drl.ast.descr.EntryPointDeclarationDescr; import org.drools.drl.ast.descr.EntryPointDescr; +import org.drools.drl.ast.descr.EnumDeclarationDescr; +import org.drools.drl.ast.descr.EnumLiteralDescr; import org.drools.drl.ast.descr.EvalDescr; import org.drools.drl.ast.descr.ExistsDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; @@ -130,6 +132,8 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc packageDescr.addEntryPointDeclaration((EntryPointDeclarationDescr) descr); } else if (descr instanceof WindowDeclarationDescr) { packageDescr.addWindowDeclaration((WindowDeclarationDescr) descr); + } else if (descr instanceof EnumDeclarationDescr) { + packageDescr.addEnumDeclaration((EnumDeclarationDescr) descr); } else if (descr instanceof AttributeDescr) { packageDescr.addAttribute((AttributeDescr) descr); } else if (descr instanceof RuleDescr) { // QueryDescr extends RuleDescr @@ -242,6 +246,38 @@ public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContex return typeDeclarationDescr; } + @Override + public EnumDeclarationDescr visitEnumDeclaration(DRLParser.EnumDeclarationContext ctx) { + EnumDeclarationDescr enumDeclarationDescr = BaseDescrFactory.builder(new EnumDeclarationDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .build(); + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(enumDeclarationDescr::addAnnotation); + + List descrList = visitDescrChildren(ctx.enumeratives()); + descrList.stream() + .filter(EnumLiteralDescr.class::isInstance) + .map(EnumLiteralDescr.class::cast) + .forEach(enumDeclarationDescr::addLiteral); + + ctx.field().stream() + .map(this::visitField) + .forEach(enumDeclarationDescr::addField); + return enumDeclarationDescr; + } + + @Override + public EnumLiteralDescr visitEnumerative(DRLParser.EnumerativeContext ctx) { + EnumLiteralDescr enumLiteralDescr = BaseDescrFactory.builder(new EnumLiteralDescr(ctx.drlIdentifier().getText())) + .withParserRuleContext(ctx) + .build(); + ctx.expression().stream() + .map(Antlr4ParserStringUtils::getTextPreservingWhitespace) + .forEach(enumLiteralDescr::addConstructorArg); + return enumLiteralDescr; + } + @Override public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPointDeclarationContext ctx) { EntryPointDeclarationDescr entryPointDeclarationDescr = BaseDescrFactory.builder(new EntryPointDeclarationDescr()) From 8aaaec97fc25f176aa4bccf9bba970cac4c77e97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Tue, 30 Apr 2024 07:38:34 +0200 Subject: [PATCH 094/141] [new-parser] Fix AccumulateTest and add groupBy support (#5876) * Fix AccumulateTest * Add GroupBy support --- .../drl/parser/antlr4/MiscDRLParserTest.java | 102 +++++++++++++++++- .../org/drools/drl/parser/antlr4/groupBy.drl | 26 +++++ .../org/drools/drl/parser/antlr4/DRLLexer.g4 | 3 +- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 21 +++- .../drl/parser/antlr4/DRLVisitorImpl.java | 34 +++++- 5 files changed, 178 insertions(+), 8 deletions(-) create mode 100755 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/groupBy.drl 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 84228270315..d400c7b00fe 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 @@ -34,6 +34,7 @@ import org.drools.drl.ast.descr.FromDescr; import org.drools.drl.ast.descr.FunctionDescr; import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.GroupByDescr; import org.drools.drl.ast.descr.ImportDescr; import org.drools.drl.ast.descr.MVELExprDescr; import org.drools.drl.ast.descr.NamedConsequenceDescr; @@ -479,7 +480,7 @@ void parse_keywordCollisions() throws Exception { // e.g. "package" is not allowed in a package value in Java, so it doesn't make sense to test. (Right to raise a parser error) PackageDescr pkg = parseAndGetPackageDescr(source); - + assertThat(pkg.getRules()).hasSize(1); } @@ -2085,6 +2086,43 @@ public void parse_EndPosition() throws Exception { assertThat(col.getEndLine()).isEqualTo(25); } + @Test + public void parse_GroupBy() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( "groupBy.drl" ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final GroupByDescr groupBy = (GroupByDescr) outPattern.getSource(); + assertThat(groupBy.getGroupingKey()).isEqualToIgnoringWhitespace("$initial"); + assertThat(groupBy.getGroupingFunction()).isEqualToIgnoringWhitespace("$p.getName().substring(0, 1)"); + assertThat(groupBy.getActionCode()).isNull(); + assertThat(groupBy.getReverseCode()).isNull(); + assertThat(groupBy.getFunctions()).hasSize(2); + assertThat(groupBy.getFunctions().get(0).getFunction()).isEqualToIgnoringWhitespace("sum"); + assertThat(groupBy.getFunctions().get(1).getFunction()).isEqualToIgnoringWhitespace("count"); + + assertThat(groupBy.getFunctions().get(0).getParams()).hasSize(1); + assertThat(groupBy.getFunctions().get(0).getParams()[0]).isEqualToIgnoringWhitespace("$age"); + + assertThat(groupBy.getFunctions().get(1).getParams()).hasSize(0); + + assertThat(groupBy.isExternalFunction()).isTrue(); + + final PatternDescr pattern = groupBy.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + assertThat(pattern.getConstraint().getDescrs().get(0).getText()).isEqualToIgnoringWhitespace("$age : age < 30"); + + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + assertThat(pattern.getConstraint().getDescrs().get(0).getText()).isEqualToIgnoringWhitespace("$age : age < 30"); + + assertThat(outPattern.getConstraint().getDescrs()).hasSize(1); + assertThat(outPattern.getConstraint().getDescrs().get(0).getText()).isEqualToIgnoringWhitespace("$sumOfAges > 10"); + } + @Test public void parse_QualifiedClassname() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( @@ -2139,6 +2177,68 @@ public void parse_AccumulateWithBindings() throws Exception { assertThat(pattern.getObjectType()).isEqualTo("Person"); } + /** + * - Optional semicolon at the end of statements (int x = 0). + * - Optional comma delimiting init, action, and result. + */ + @Test + public void accumulateWithoutOptionalDelimiters() throws Exception { + String source = "rule \"AccumulateParserTest\"\n" + + "when\n" + + " $counter:Integer() from accumulate( $person : Person( age > 21 ),\n" + + " init( int x = 0 )\n" + + " action( x++ )\n" + + " result( new Integer(x) ) );\n" + + "then\n" + + "end\n"; + final PackageDescr pkg = parseAndGetPackageDescr( source ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace( "$counter"); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0"); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++"); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + /** + * When the accumulate function (e.g. count()) has no arguments. + */ + @Test + public void accumulateCount() throws Exception { + String source = "rule R when\n" + + " accumulate (\n" + + " Person(), $result : count() " + + " )" + + "then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr( source ); + + assertThat(pkg.getRules().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(accum).isNotNull(); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + + assertThat(accum.getFunctions()).hasSize(1); + AccumulateDescr.AccumulateFunctionCallDescr accumulateFunction = accum.getFunctions().get(0); + assertThat(accumulateFunction.getBind()).isEqualTo("$result"); + assertThat(accumulateFunction.getFunction()).isEqualTo("count"); + assertThat(accumulateFunction.getParams()).isEmpty(); + } + @Test public void parse_Collect() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/groupBy.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/groupBy.drl new file mode 100755 index 00000000000..9ca6ed7e834 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/groupBy.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "GroupByParserTest" +when + groupby( $p: Person ( $age : age < 30 ); // SOURCE_PATTERN + $initial : $p.getName().substring(0, 1); // GROUPING_FUNCTION + $sumOfAges : sum($age), // 2 ACC_FUNCTIONS, one summing the ages of the persons in the group + $countOfPersons : count(); // and the other simply counting them + $sumOfAges > 10 ) // CONSTRAINT filtering away groups +then +end 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/DRLLexer.g4 index 52716591ad9..58719554dec 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/DRLLexer.g4 @@ -60,6 +60,7 @@ DRL_ENTRY_POINT : 'entry-point'; DRL_EVAL : 'eval'; DRL_FORALL : 'forall'; DRL_OVER : 'over'; +DRL_GROUPBY : 'groupby'; // constraint operators DRL_MATCHES : 'matches'; @@ -189,4 +190,4 @@ RHS_CHUNK | RBRACE | COMMA | SEMI - ; \ No newline at end of file + ; 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/DRLParser.g4 index fb6a9bf68c6..b173157c933 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/DRLParser.g4 @@ -134,6 +134,7 @@ lhsUnary : ( | lhsEval consequenceInvocation* | lhsForall | lhsAccumulate + | lhsGroupBy | conditionalBranch // not in the above old parser definition, but actually implemented in the old parser | lhsPatternBind consequenceInvocation* ) SEMI? ; @@ -184,7 +185,7 @@ relationalOperator drlRelationalOperator : DRL_NOT? builtInOperator ; /* function := FUNCTION type? ID parameters(typed) chunk_{_} */ -functiondef : DRL_FUNCTION typeTypeOrVoid? IDENTIFIER formalParameters drlBlock ; +functiondef : DRL_FUNCTION typeTypeOrVoid? drlIdentifier formalParameters drlBlock ; /* extending JavaParser qualifiedName */ @@ -335,7 +336,7 @@ fromAccumulate := ACCUMULATE LEFT_PAREN lhsAnd (COMMA|SEMICOLON) ) RIGHT_PAREN */ fromAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) - ( DRL_INIT LPAREN initBlockStatements=blockStatements RPAREN COMMA DRL_ACTION LPAREN actionBlockStatements=blockStatements RPAREN COMMA ( DRL_REVERSE LPAREN reverseBlockStatements=blockStatements RPAREN COMMA)? DRL_RESULT LPAREN expression RPAREN + ( DRL_INIT LPAREN initBlockStatements=chunk RPAREN COMMA? DRL_ACTION LPAREN actionBlockStatements=chunk RPAREN COMMA? ( DRL_REVERSE LPAREN reverseBlockStatements=chunk RPAREN COMMA?)? DRL_RESULT LPAREN expression RPAREN | accumulateFunction ) RPAREN (SEMI)? @@ -346,7 +347,10 @@ blockStatements : drlBlockStatement* ; /* accumulateFunction := label? ID parameters */ -accumulateFunction : label? IDENTIFIER LPAREN drlExpression RPAREN; +accumulateFunction : label? IDENTIFIER conditionalExpressions ; + +// parameters := LEFT_PAREN (conditionalExpression (COMMA conditionalExpression)* )? RIGHT_PAREN +conditionalExpressions : LPAREN (conditionalExpression (COMMA conditionalExpression)* )? RPAREN ; // fromCollect := COLLECT LEFT_PAREN lhsPatternBind RIGHT_PAREN @@ -409,6 +413,15 @@ lhsAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) RPAREN (SEMI)? ; +lhsGroupBy : DRL_GROUPBY LPAREN lhsAndDef (COMMA|SEMI) + groupByKeyBinding SEMI + accumulateFunction (COMMA accumulateFunction)* + (SEMI constraints)? + RPAREN (SEMI)? + ; + +groupByKeyBinding : label? conditionalExpression ; + rhs : DRL_THEN consequenceBody namedConsequence* ; consequenceBody : ( RHS_STRING_LITERAL | RHS_CHUNK )* ; @@ -483,7 +496,7 @@ drlBlock ; /* extending JavaParser blockStatement */ drlBlockStatement - : drlLocalVariableDeclaration SEMI + : drlLocalVariableDeclaration SEMI? | drlStatement | localTypeDeclaration ; 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 f568256b8ee..5fef1724053 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,6 +23,7 @@ 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; @@ -48,6 +49,7 @@ import org.drools.drl.ast.descr.FunctionDescr; import org.drools.drl.ast.descr.FunctionImportDescr; import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.GroupByDescr; import org.drools.drl.ast.descr.ImportDescr; import org.drools.drl.ast.descr.MVELExprDescr; import org.drools.drl.ast.descr.NamedConsequenceDescr; @@ -202,7 +204,7 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { } else { functionDescr.setReturnType("void"); } - functionDescr.setName(ctx.IDENTIFIER().getText()); + functionDescr.setName(ctx.drlIdentifier().getText()); // add function parameters DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); @@ -700,6 +702,31 @@ public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { return patternDescr; } + @Override + public Object visitLhsGroupBy(DRLParser.LhsGroupByContext ctx) { + GroupByDescr groupByDescr = BaseDescrFactory.builder(new GroupByDescr()) + .withParserRuleContext(ctx) + .build(); + groupByDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); + + if (ctx.groupByKeyBinding().label() != null) { + groupByDescr.setGroupingKey(ctx.groupByKeyBinding().label().drlIdentifier().getText()); + } + groupByDescr.setGroupingFunction(getTextPreservingWhitespace(ctx.groupByKeyBinding().conditionalExpression())); + + // accumulate function + for (DRLParser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { + groupByDescr.addFunction(visitAccumulateFunction(accumulateFunctionContext)); + } + + PatternDescr patternDescr = new PatternDescr("Object"); + patternDescr.setSource(groupByDescr); + List constraintDescrList = visitConstraints(ctx.constraints()); + constraintDescrList.forEach(patternDescr::addConstraint); + + return patternDescr; + } + @Override public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { BehaviorDescr behaviorDescr = BaseDescrFactory.builder(new BehaviorDescr()) @@ -756,7 +783,10 @@ public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLParser.AccumulateFunctionContext ctx) { String function = ctx.IDENTIFIER().getText(); String bind = ctx.label() == null ? null : ctx.label().drlIdentifier().getText(); - String[] params = new String[]{getTextPreservingWhitespace(ctx.drlExpression())}; + + String[] params = ctx.conditionalExpressions().conditionalExpression().stream() + .map(RuleContext::getText) + .toArray(String[]::new); return new AccumulateDescr.AccumulateFunctionCallDescr(function, bind, false, params); } From 3719bba0b110d7bbff723c5d3cf1745f97aefadb Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 30 Apr 2024 17:13:21 +0900 Subject: [PATCH 095/141] =?UTF-8?q?[incubator-kie-drools-5724]=20[new-pars?= =?UTF-8?q?er]=20Broken=20ExisistentialTest#tes=E2=80=A6=20(#5871)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5724] [new-parser] Broken ExisistentialTest#test2NotsWithAnd * - Addtional test for LPAREN lhsExpression RPAREN namedConsequenceInvocation? --- .../drl/parser/antlr4/MiscDRLParserTest.java | 92 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 17 +--- 2 files changed, 97 insertions(+), 12 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 d400c7b00fe..f44b6b5abd9 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 @@ -4387,6 +4387,34 @@ void namedConsequenceAfterEnclosed() { assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMarkOrMario"); } + @Test + void namedConsequenceOrWithBindVariables() { + final String text = + "rule R when\n" + + " $r : Result()\n" + + " ( $p1 : Person(name == \"Mark\") or $p1 : Person(name == \"Mario\") )\n" + + " do[FoundMarkOrMario]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"Found \" + $p1.getName());\n" + + "end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + OrDescr orDescr = (OrDescr) ruleDescr.getLhs().getDescrs().get(1); + PatternDescr patternDescr1 = (PatternDescr) orDescr.getDescrs().get(0); + assertThat(patternDescr1.getIdentifier()).isEqualTo("$p1"); + assertThat(((ExprConstraintDescr)patternDescr1.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("name == \"Mark\""); + PatternDescr patternDescr2 = (PatternDescr) orDescr.getDescrs().get(1); + assertThat(patternDescr2.getIdentifier()).isEqualTo("$p1"); + assertThat(((ExprConstraintDescr)patternDescr2.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("name == \"Mario\""); + + NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMarkOrMario"); + } + @Test public void queryComplexLhs() { final String text = "query isContainedIn(String x, String y)\n" + @@ -4463,6 +4491,70 @@ public void queryComplexLhs() { }); } + @Test + void notWithPrefixAnd() { + final String text = + "package org.drools.compiler\n" + + "rule R when\n" + + " (not (and Integer( $i : intValue )\n" + + " String( length > $i ) \n" + + " )\n" + + " )\n" + + "then\n" + + "end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { + assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs()).hasSize(2); + assertThat(andDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Integer"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("$i : intValue"); + }); + }); + assertThat(andDescr.getDescrs().get(1)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("String"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("length > $i"); + }); + }); + }); + }); + } + + @Test + void existsWithPrefixAnd() { + final String text = + "package org.drools.compiler\n" + + "rule R when\n" + + " (exists (and Integer( $i : intValue )\n" + + " String( length > $i ) \n" + + " )\n" + + " )\n" + + "then\n" + + "end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(ExistsDescr.class, existsDescr -> { + assertThat(existsDescr.getDescrs().get(0)).isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs()).hasSize(2); + assertThat(andDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Integer"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("$i : intValue"); + }); + }); + assertThat(andDescr.getDescrs().get(1)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("String"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("length > $i"); + }); + }); + }); + }); + } + @Test public void enumDeclaration() { final String text = 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/DRLParser.g4 index b173157c933..03d6b20ced9 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/DRLParser.g4 @@ -103,7 +103,7 @@ lhs : DRL_WHEN lhsExpression* ; queryLhs : lhsExpression+ ; -lhsExpression : LPAREN lhsExpression RPAREN namedConsequenceInvocation? #lhsExpressionEnclosed +lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed | lhsUnary #lhsUnarySingle | LPAREN DRL_AND lhsExpression+ RPAREN #lhsAnd | lhsExpression (DRL_AND lhsExpression)+ #lhsAnd @@ -123,7 +123,7 @@ lhsUnary : ( lhsExists namedConsequence? | lhsEval consequenceInvocation* | lhsForall | lhsAccumulate - | LPAREN lhsOr RPAREN namedConsequence? // this part is handled by #lhsExpressionEnclosed + | LPAREN lhsOr RPAREN namedConsequence? | lhsPatternBind consequenceInvocation* ) SEMI? ; */ @@ -135,6 +135,7 @@ lhsUnary : ( | lhsForall | lhsAccumulate | lhsGroupBy + | LPAREN lhsExpression RPAREN namedConsequenceInvocation? | conditionalBranch // not in the above old parser definition, but actually implemented in the old parser | lhsPatternBind consequenceInvocation* ) SEMI? ; @@ -369,11 +370,7 @@ fromWindow : DRL_WINDOW IDENTIFIER ; ) */ // Use lhsExpression instead of lhsOr because lhsExpression has good enough structure -lhsExists : DRL_EXISTS - ( LPAREN lhsExpression RPAREN - | lhsPatternBind - ) - ; +lhsExists : DRL_EXISTS ( lhsPatternBind | lhsExpression ) ; /* lhsNot := NOT @@ -383,11 +380,7 @@ lhsExists : DRL_EXISTS ) */ // Use lhsExpression instead of lhsOr because lhsExpression has good enough structure -lhsNot : DRL_NOT - ( LPAREN lhsExpression RPAREN - | lhsPatternBind - ) - ; +lhsNot : DRL_NOT ( lhsPatternBind | lhsExpression ) ; /** * lhsEval := EVAL LEFT_PAREN conditionalExpression RIGHT_PAREN From fd7f689743b310b18a186e11e431f1ae0b54d6e2 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 30 Apr 2024 18:23:32 +0900 Subject: [PATCH 096/141] =?UTF-8?q?[incubator-kie-drools-5784]=20Review=20?= =?UTF-8?q?DRLParser.g4=20and=20DRL6Expressions.g=E2=80=A6=20(#5875)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5784] Review DRLParser.g4 and DRL6Expressions.g4 to replace IDENTIFIER with drlIdentifier * - Removed unused methods --- .../antlr4/DRLParserIdentifierTest.java | 325 ++++++++++++++++++ .../drl/parser/antlr4/DRLParserTest.java | 18 + .../drl/parser/antlr4/MiscDRLParserTest.java | 18 + .../drl/parser/antlr4/ParserTestUtils.java | 7 + .../drl/parser/antlr4/DRL6Expressions.g4 | 27 +- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 17 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 10 +- 7 files changed, 395 insertions(+), 27 deletions(-) create mode 100644 drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java new file mode 100644 index 00000000000..5e0b60545b2 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java @@ -0,0 +1,325 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import org.drools.drl.ast.descr.AccumulateDescr; +import org.drools.drl.ast.descr.AccumulateImportDescr; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.BehaviorDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.FunctionDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl.ast.descr.WindowReferenceDescr; +import org.drools.drl.parser.DrlParser; +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 static org.assertj.core.api.Assertions.assertThat; + +/* + * This test class is to test parse rules to accept drlIdentifier insteadof IDENTIFIER. (e.g. drl keyword like "contains") + */ +class DRLParserIdentifierTest { + + private DrlParser parser; + + @BeforeEach + public void setUp() { + parser = ParserTestUtils.getParser(); + } + + private PackageDescr parseAndGetPackageDescr(String drl) { + try { + PackageDescr pkg = parser.parse(null, drl); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + return pkg; + } catch (DroolsParserException e) { + throw new RuntimeException(e); + } + } + + private RuleDescr parseAndGetFirstRuleDescr(String drl) { + PackageDescr pkg = parseAndGetPackageDescr(drl); + assertThat(pkg.getRules()).isNotEmpty(); + return pkg.getRules().get(0); + } + + @Test + void importAccumulate() { + final String source = "import accumulate org.example.MyFunction contains;"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + AccumulateImportDescr accumulateImportDescr = pkg.getAccumulateImports().get(0); + assertThat(accumulateImportDescr.getTarget()).isEqualTo("org.example.MyFunction"); + assertThat(accumulateImportDescr.getFunctionName()).isEqualTo("contains"); + } + + @Test + void windowDeclaration() { + final String text = + "declare window contains\n" + + " $s : StockTick( source == \"NYSE\" )\n" + + " over window:length( 10 )\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr(text); + WindowDeclarationDescr windowDeclarationDescr = pkg.getWindowDeclarations().iterator().next(); + assertThat(windowDeclarationDescr.getName()).isEqualTo("contains"); + } + + @Test + void nestedConstraint() { + final String text = + "rule R\n" + + "when\n" + + " Person( contains.matches.( city == \"london\", country == \"uk\"))\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("contains.matches.city == \"london\""); + }); + assertThat(patternDescr.getConstraint().getDescrs().get(1)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("contains.matches.country == \"uk\""); + }); + }); + } + + @Test + public void function() { + final String text = "function boolean contains(String s) { return true; }"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + FunctionDescr function = packageDescr.getFunctions().get(0); + assertThat(function.getName()).isEqualTo("contains"); + } + + @Test + public void patternFilter() { + final String text = "rule X when StockTick( symbol==\"ACME\") over window:contains(10) then end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + BehaviorDescr behavior = pattern.getBehaviors().get(0); + assertThat(behavior.getType()).isEqualTo("window"); + assertThat(behavior.getSubType()).isEqualTo("contains"); + assertThat(behavior.getParameters().get(0)).isEqualTo("10"); + } + + @Test + public void accumulateFunction() { + final String text = "rule R1\n" + + "when\n" + + " accumulate( Person( $age : age > 21 ), $ave : contains( $age ) );\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accumulate = (AccumulateDescr) out.getSource(); + assertThat(accumulate.getFunctions().get(0).getFunction()).isEqualToIgnoringWhitespace("contains"); + } + + @Test + public void fromWindow() { + final String text = + "rule X\n" + + "when\n" + + " StockTick() from window contains\n" + + "then\n" + + "end\n"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getSource()).isInstanceOfSatisfying(WindowReferenceDescr.class, windowReferenceDescr -> { + assertThat(windowReferenceDescr.getName()).isEqualTo("contains"); + }); + } + + @Test + public void type() { + final String text = "global contains.matches bbb"; + PackageDescr pkg = parseAndGetPackageDescr(text); + GlobalDescr global = pkg.getGlobals().get(0); + assertThat(global.getType()).isEqualTo("contains.matches"); + assertThat(global.getIdentifier()).isEqualTo("bbb"); + } + + @Test + public void unification() throws Exception { + final String text = "rule X\n" + + "when\n" + + " contains := Person()\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + assertThat(pattern.getIdentifier()).isEqualTo("contains"); + assertThat(pattern.isUnification()).isTrue(); + } + + @Test + public void annotation() { + final String text = "rule R\n" + + "@contains.matches(soundslike=\"abc\")\n" + + "when\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + AnnotationDescr annotation = rule.getAnnotation("contains.matches"); + assertThat(annotation.getValue("soundslike")).isEqualTo("\"abc\""); + } + + @Test + public void constraintBoundVariable() { + final String text = "rule X\n" + + "when\n" + + " Person( contains : age > 20)\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("contains : age > 20"); + } + + @Test + public void constraintBoundVariableUnify() { + final String text = "rule X\n" + + "when\n" + + " Person( contains := age > 20)\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("contains := age > 20"); + } + + @Test + void xpathChunk() { + final String text = + "rule R when\n" + + " $man: Man( /contains.matches#soundslike[memberOf > 10] )\n" + + "then\n" + + "end\n"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("/contains.matches#soundslike[memberOf > 10]"); + } + + @Test + void createdName() { + final String text = + "rule X\n" + + "when\n" + + " Person( age > new contains.matches(10))\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("age > new contains.matches(10)"); + } + + @Test + void explicitGenericInvocationSuffix() { + final String text = + "rule X\n" + + "when\n" + + " Person( name == contains())\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("name == contains()"); + } + + @Disabled("Old parser does not support this syntax") + @Test + void innerCreator() { + final String text = + "rule X\n" + + "when\n" + + " Person( outer.new contains() != null )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("outer.new contains() != null"); + } + + @Test + void superSuffix() { + final String text = + "rule X\n" + + "when\n" + + " Person( address.super.contains() == 10 )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("address.super.contains() == 10"); + } + + @Disabled("To be done by https://github.com/apache/incubator-kie-drools/issues/5874") + @Test + void operator_key() { + final String text = + "rule X\n" + + "when\n" + + " Person( age provides 10 )\n" + + "then\n" + + "end"; + // PROVIDES is not IDENTIFIER, but included in drlIdentifier + Operator.addOperatorToRegistry("provides", false); + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("age provides 10"); + } + + @Disabled("To be done by https://github.com/apache/incubator-kie-drools/issues/5874") + @Test + void neg_operator_key() { + final String text = + "rule X\n" + + "when\n" + + " Person( age not provides 10 )\n" + + "then\n" + + "end"; + // PROVIDES is not IDENTIFIER, but included in drlIdentifier + Operator.addOperatorToRegistry("provides", true); + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("age not provides 10"); + } + + @Test + void operator_key_temporal() { + // This test (and MiscDRLParserTest.parse_PluggableOperators) fails when adapting drlIdentifier to operator_key and neg_operator_key in DRL6Expressions.g4 + // See https://github.com/apache/incubator-kie-drools/issues/5874 + final String text = + "rule X\n" + + "when\n" + + " Person( this after[1,10] $a || this not after[15,20] $a )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("this after[1,10] $a || this not after[15,20] $a"); + } +} 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/DRLParserTest.java index f792effd235..1533aefdc0b 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/DRLParserTest.java @@ -1,3 +1,21 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.drools.drl.parser.antlr4; import java.util.List; 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 f44b6b5abd9..9f1d67035b3 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 @@ -1,3 +1,21 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.drools.drl.parser.antlr4; import java.io.BufferedReader; 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 f0d1f854d26..270b8f8c37c 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 @@ -32,4 +32,11 @@ private ParserTestUtils() { public static DrlParser getParser() { return new DrlParser(); } + + /** + * Enables the old parser. Just for quick testing purposes. + */ + public static void enableOldParser() { + DrlParser.ANTLR4_PARSER_ENABLED = false; + } } 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/DRL6Expressions.g4 index 190bceee75d..02c20088f4c 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/DRL6Expressions.g4 @@ -146,7 +146,7 @@ type typeMatch : primitiveType (LBRACK RBRACK)* - | IDENTIFIER (typeArguments)? (DOT IDENTIFIER (typeArguments)? )* (LBRACK RBRACK)* + | drlIdentifier (typeArguments)? (DOT drlIdentifier (typeArguments)? )* (LBRACK RBRACK)* ; typeArguments @@ -282,7 +282,7 @@ finally { ternOp--; } fullAnnotation [AnnotatedDescrBuilder inDescrBuilder] returns [AnnotationDescr result] @init{ String n = ""; AnnotationDescrBuilder annoBuilder = null; } - : AT name=IDENTIFIER { n = $name.text; } ( DOT x=IDENTIFIER { n += "." + $x.text; } )* + : AT name=drlIdentifier { n = $name.text; } ( DOT x=drlIdentifier { n += "." + $x.text; } )* { if( buildDescr ) { if ( inDescrBuilder == null ) { $result = new AnnotationDescr( n ); @@ -310,7 +310,7 @@ annotationElementValuePairs [AnnotationDescr descr, AnnotatedDescrBuilder inDesc ; annotationElementValuePair [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] - : key=IDENTIFIER ASSIGN val=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setKeyValue( $key.text, $val.result ); } } + : key=drlIdentifier ASSIGN val=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setKeyValue( $key.text, $val.result ); } } ; annotationValue[AnnotatedDescrBuilder inDescrBuilder] returns [Object result] @@ -615,10 +615,10 @@ unaryExpressionNotPlusMinus returns [BaseDescr result] | castExpression | backReferenceExpression | { isLeft = helper.getLeftMostExpr() == null;} - ( ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.COLON}? (var=IDENTIFIER COLON - { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($COLON, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, false); helper.setStart( bind, $var ); } } )) - | ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.DRL_UNIFY}? (var=IDENTIFIER DRL_UNIFY - { hasBindings = true; helper.emit($var, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($DRL_UNIFY, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, true); helper.setStart( bind, $var ); } } )) + ( ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.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 + { 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 ); } } )) )? ( left2=xpathPrimary { if( buildDescr ) { $result = $left2.result; } } @@ -677,7 +677,7 @@ xpathPrimary returns [BaseDescr result] ; xpathChunk returns [BaseDescr result] - : xpathSeparator IDENTIFIER (DOT IDENTIFIER)* (HASH IDENTIFIER)? (LBRACK xpathExpressionList RBRACK)? + : xpathSeparator drlIdentifier (DOT drlIdentifier)* (HASH drlIdentifier)? (LBRACK xpathExpressionList RBRACK)? ; xpathExpressionList returns [java.util.List exprs] @@ -761,13 +761,14 @@ creator ; createdName - : IDENTIFIER typeArguments? - ( DOT IDENTIFIER typeArguments?)* + : drlIdentifier typeArguments? + ( DOT drlIdentifier typeArguments?)* | primitiveType ; +// Old parser cannot parse innerCreator with selector expression (outer.new InnerClass() != null) TODO: Delete this after investigation innerCreator - : {!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? IDENTIFIER classCreatorRest + : {!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? drlIdentifier classCreatorRest ; arrayCreatorRest @@ -800,7 +801,7 @@ nonWildcardTypeArguments explicitGenericInvocationSuffix : super_key superSuffix - | IDENTIFIER arguments + | drlIdentifier arguments ; selector @@ -820,7 +821,7 @@ selector superSuffix : arguments - | DOT IDENTIFIER (arguments)? + | DOT drlIdentifier (arguments)? ; squareArguments returns [java.util.List args] 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/DRLParser.g4 index 03d6b20ced9..a58b38e0b44 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/DRLParser.g4 @@ -31,7 +31,7 @@ packagedef : PACKAGE name=drlQualifiedName SEMI? ; unitdef : DRL_UNIT name=drlQualifiedName SEMI? ; importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? #importStandardDef - | IMPORT (DRL_ACCUMULATE|DRL_ACC) drlQualifiedName IDENTIFIER #importAccumulateDef + | IMPORT (DRL_ACCUMULATE|DRL_ACC) drlQualifiedName drlIdentifier #importAccumulateDef ; globaldef : DRL_GLOBAL type drlIdentifier ; @@ -69,7 +69,7 @@ entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* DRL_END ; // windowDeclaration := WINDOW ID annotation* lhsPatternBind END -windowDeclaration : DRL_WINDOW name=IDENTIFIER drlAnnotation* lhsPatternBind DRL_END ; +windowDeclaration : DRL_WINDOW name=drlIdentifier drlAnnotation* lhsPatternBind DRL_END ; // (enum)typeDeclaration := [ENUM] qualifiedIdentifier annotation* enumerative+ field* END @@ -151,7 +151,7 @@ lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? positionalConstraints : constraint (COMMA constraint)* SEMI ; constraints : constraint (COMMA constraint)* ; constraint : ( nestedConstraint | conditionalOrExpression ) ; -nestedConstraint : ( IDENTIFIER ( DOT | NULL_SAFE_DOT | HASH ) )* IDENTIFIER (DOT | NULL_SAFE_DOT ) LPAREN constraints RPAREN ; +nestedConstraint : ( drlIdentifier ( DOT | NULL_SAFE_DOT | HASH ) )* drlIdentifier (DOT | NULL_SAFE_DOT ) LPAREN constraints RPAREN ; // named consequence @@ -309,7 +309,7 @@ mapEntry patternFilter := OVER filterDef filterDef := label ID LEFT_PAREN parameters RIGHT_PAREN */ -patternFilter : DRL_WINDOW COLON IDENTIFIER LPAREN expressionList RPAREN ; +patternFilter : DRL_WINDOW COLON drlIdentifier LPAREN expressionList RPAREN ; /* patternSource := FROM @@ -348,7 +348,7 @@ blockStatements : drlBlockStatement* ; /* accumulateFunction := label? ID parameters */ -accumulateFunction : label? IDENTIFIER conditionalExpressions ; +accumulateFunction : label? drlIdentifier conditionalExpressions ; // parameters := LEFT_PAREN (conditionalExpression (COMMA conditionalExpression)* )? RIGHT_PAREN conditionalExpressions : LPAREN (conditionalExpression (COMMA conditionalExpression)* )? RPAREN ; @@ -360,7 +360,7 @@ fromCollect : DRL_COLLECT LPAREN lhsPatternBind RPAREN ; fromEntryPoint : DRL_ENTRY_POINT stringId ; // fromWindow := WINDOW ID -fromWindow : DRL_WINDOW IDENTIFIER ; +fromWindow : DRL_WINDOW drlIdentifier ; /* lhsExists := EXISTS @@ -424,8 +424,7 @@ namedConsequence : RHS_NAMED_CONSEQUENCE_THEN consequenceBody ; stringId : ( drlIdentifier | DRL_STRING_LITERAL ) ; -type : (classOrInterfaceType | primitiveType) typeArguments? ( DOT IDENTIFIER typeArguments? )* (LBRACK RBRACK)* ; - +//type := ID typeArguments? ( DOT ID typeArguments? )* (LEFT_SQUARE RIGHT_SQUARE)* //typeArguments : LT typeArgument (COMMA typeArgument)* GT ; //typeArgument : QUESTION (( EXTENDS | SUPER ) type )? | type ; @@ -462,7 +461,7 @@ assignmentOperator : ASSIGN | LT LT ASSIGN ; label : drlIdentifier COLON ; -unif : IDENTIFIER DRL_UNIFY ; +unif : drlIdentifier DRL_UNIFY ; /* extending JavaParser variableInitializer */ drlVariableInitializer 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 5fef1724053..db5e0c2dd8c 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 @@ -190,7 +190,7 @@ public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulate .withParserRuleContext(ctx) .build(); accumulateImportDescr.setTarget(ctx.drlQualifiedName().getText()); - accumulateImportDescr.setFunctionName(ctx.IDENTIFIER().getText()); + accumulateImportDescr.setFunctionName(ctx.drlIdentifier().getText()); return accumulateImportDescr; } @@ -549,7 +549,7 @@ private PatternDescr getSinglePatternDescr(DRLParser.LhsPatternBindContext ctx) if (ctx.label() != null) { patternDescr.setIdentifier(ctx.label().drlIdentifier().getText()); } else if (ctx.unif() != null) { - patternDescr.setIdentifier(ctx.unif().IDENTIFIER().getText()); + patternDescr.setIdentifier(ctx.unif().drlIdentifier().getText()); patternDescr.setUnification(true); } DescrHelper.refreshPatternDescrProperties(patternDescr, ctx); @@ -733,7 +733,7 @@ public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { .withParserRuleContext(ctx) .build(); behaviorDescr.setType(ctx.DRL_WINDOW().getText()); - behaviorDescr.setSubType(ctx.IDENTIFIER().getText()); + behaviorDescr.setSubType(ctx.drlIdentifier().getText()); List expressionContexts = ctx.expressionList().expression(); List parameters = expressionContexts.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); behaviorDescr.setParameters(parameters); @@ -781,7 +781,7 @@ public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) @Override public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLParser.AccumulateFunctionContext ctx) { - String function = ctx.IDENTIFIER().getText(); + String function = ctx.drlIdentifier().getText(); String bind = ctx.label() == null ? null : ctx.label().drlIdentifier().getText(); String[] params = ctx.conditionalExpressions().conditionalExpression().stream() @@ -799,7 +799,7 @@ public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) @Override public WindowReferenceDescr visitFromWindow(DRLParser.FromWindowContext ctx) { - return BaseDescrFactory.builder(new WindowReferenceDescr(ctx.IDENTIFIER().getText())) + return BaseDescrFactory.builder(new WindowReferenceDescr(ctx.drlIdentifier().getText())) .withParserRuleContext(ctx) .build(); } From 06723142af200868ad5cec03844f59c15fefd59b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Tue, 7 May 2024 04:41:39 +0200 Subject: [PATCH 097/141] [new-parser] Allow OOPath as a LHS pattern (#5884) * Add OOPath support to lhsPattern * Set namespace and unit properties to PackageDescr children --- .../drl/parser/antlr4/MiscDRLParserTest.java | 61 +++++++++++++++++++ .../drl/parser/antlr4/package_children.drl | 53 ++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 5 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 21 +++++++ 4 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_children.drl 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 9f1d67035b3..4964f77457b 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 @@ -26,6 +26,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; @@ -4090,6 +4091,28 @@ void ooPathMixedWithStandardConstraint() { .isEqualToIgnoringWhitespace("/wife[$age : age] && age > $age"); } + @Test + void ooPathLhsPattern() { + final String text = "package org.drools\n" + + "rule PlainNot when\n" + + " not( /strings [ this == \"It Does Work\" ] )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { + assertThat(notDescr.getDescrs()).hasSize(1); + assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getConstraint().getDescrs()).hasSize(1); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("/strings [ this == \"It Does Work\" ]"); + assertThat(exprConstraintDescr.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); + assertThat(exprConstraintDescr.getPosition()).isEqualTo(0); + }); + }); + }); + } + @Test void inlineCast() { final String text = "package org.drools\n" + @@ -4605,4 +4628,42 @@ public void enumDeclaration() { TypeFieldDescr romanStr = enumDeclarationDescr.getFields().get("romanStr"); assertThat(romanStr.getPattern().getObjectType()).isEqualTo("String"); } + + @Test + void packageChildrenNamespaceAndUnitProperties() { + String namespace = "org.drools.compiler.test"; + String source = readResource("package_children.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + // Package and Rule Unit's namespace. + assertThat(pkg.getName()).isEqualTo(namespace); + assertThat(pkg.getUnit().getNamespace()).isEqualTo(namespace); + + // Children that are expected to have the package name as their namespace. + assertNamespace(pkg.getImports(), namespace); + assertNamespace(pkg.getFunctionImports(), namespace); + assertNamespace(pkg.getAccumulateImports(), namespace); + assertNamespace(pkg.getGlobals(), namespace); + assertNamespace(pkg.getFunctions(), namespace); + assertNamespace(pkg.getRules(), namespace); + assertNamespace(pkg.getAttributes(), namespace); + + // Children that are expected to have no namespace. + assertNamespace(pkg.getTypeDeclarations(), ""); + assertNamespace(pkg.getEnumDeclarations(), ""); + assertNamespace(pkg.getEntryPointDeclarations(), ""); + assertNamespace(pkg.getWindowDeclarations(), ""); + + assertThat(pkg.getRules()) + .allSatisfy(ruleDescr -> assertThat(ruleDescr.getUnit()).isNotNull()) + .allSatisfy(ruleDescr -> assertThat(ruleDescr.getUnit().getTarget()).isEqualTo("TestUnit")); + + assertThat(pkg.getRules().get(0).getUnitQualifiedName()).isEqualTo("TestUnit.MyQuery"); + assertThat(pkg.getRules().get(1).getUnitQualifiedName()).isEqualTo("TestUnit.My Rule"); + } + + static void assertNamespace(Collection children, String namespace) { + assertThat(children).isNotEmpty(); // Make sure that every child type is represented. + assertThat(children).allSatisfy(baseDescr -> assertThat(baseDescr.getNamespace()).isEqualTo(namespace)); + } } diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_children.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_children.drl new file mode 100644 index 00000000000..f419879de3e --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_children.drl @@ -0,0 +1,53 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test + +unit TestUnit + +import org.drools.compiler.Cheese + +import function abc.def.x + +import accumulate foo.Bar2 baz2 + +global List result + +declare Person end + +declare enum Color WHITE; end + +declare entry-point EntryPoint end + +declare window Window + Double() over window:length( 10 ) +end + +query MyQuery + Cheese() +end + +function String doSomething() {} + +enabled true; + +dialect "java" + +rule "My Rule" +when +then +end 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/DRLParser.g4 index a58b38e0b44..f0eba169bfe 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/DRLParser.g4 @@ -147,7 +147,10 @@ lhsPattern : xpathPrimary (OVER patternFilter)? | ( QUESTION? qualifiedIdentifier LPAREN positionalConstraints? constraints? RPAREN (OVER patternFilter)? (FROM patternSource)? ) ; */ -lhsPattern : QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN drlAnnotation* (DRL_OVER patternFilter)? (DRL_FROM patternSource)? ; +lhsPattern + : xpathPrimary (DRL_OVER patternFilter)? + | QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN drlAnnotation* (DRL_OVER patternFilter)? (DRL_FROM patternSource)? + ; positionalConstraints : constraint (COMMA constraint)* SEMI ; constraints : constraint (COMMA constraint)* ; constraint : ( nestedConstraint | conditionalOrExpression ) ; 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 db5e0c2dd8c..143e0a2da80 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 @@ -111,14 +111,19 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc // This bunch of if-blocks will be refactored by DROOLS-7564 descrList.forEach(descr -> { if (descr instanceof UnitDescr) { + descr.setNamespace(packageDescr.getNamespace()); packageDescr.setUnit((UnitDescr) descr); } else if (descr instanceof GlobalDescr) { + descr.setNamespace(packageDescr.getNamespace()); packageDescr.addGlobal((GlobalDescr) descr); } else if (descr instanceof FunctionImportDescr) { + descr.setNamespace(packageDescr.getNamespace()); packageDescr.addFunctionImport((FunctionImportDescr) descr); } else if (descr instanceof AccumulateImportDescr) { + descr.setNamespace(packageDescr.getNamespace()); packageDescr.addAccumulateImport((AccumulateImportDescr) descr); } else if (descr instanceof ImportDescr) { + descr.setNamespace(packageDescr.getNamespace()); packageDescr.addImport((ImportDescr) descr); } else if (descr instanceof FunctionDescr) { FunctionDescr functionDescr = (FunctionDescr) descr; @@ -137,12 +142,14 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc } else if (descr instanceof EnumDeclarationDescr) { packageDescr.addEnumDeclaration((EnumDeclarationDescr) descr); } else if (descr instanceof AttributeDescr) { + descr.setNamespace(packageDescr.getNamespace()); packageDescr.addAttribute((AttributeDescr) descr); } else if (descr instanceof RuleDescr) { // QueryDescr extends RuleDescr RuleDescr ruleDescr = (RuleDescr) descr; packageDescr.addRule(ruleDescr); packageDescr.afterRuleAdded(ruleDescr); ruleDescr.setNamespace(packageDescr.getNamespace()); + ruleDescr.setUnit(packageDescr.getUnit()); } }); } @@ -579,6 +586,20 @@ private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindConte */ @Override public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { + if (ctx.xpathPrimary() != null) { + String constraint = visitConstraintChildren(ctx); + ExprConstraintDescr constraintDescr = BaseDescrFactory.builder(new ExprConstraintDescr(constraint)) + .withParserRuleContext(ctx) + .build(); + constraintDescr.setType(ExprConstraintDescr.Type.NAMED); + constraintDescr.setPosition(0); + PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr()) + .withParserRuleContext(ctx) + .build(); + patternDescr.addConstraint(constraintDescr); + return patternDescr; + } + PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr(ctx.objectType.getText())) .withParserRuleContext(ctx) .build(); From 08e21ec5b108e6c9fe5810a0ba34eb7b84e21c4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Tue, 7 May 2024 04:42:01 +0200 Subject: [PATCH 098/141] Preserve whitespace in accumulate/result (#5889) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 22 +++++++++---------- .../drl/parser/antlr4/DRLVisitorImpl.java | 2 +- 2 files changed, 12 insertions(+), 12 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 4964f77457b..ffc1eeac067 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 @@ -2165,10 +2165,10 @@ public void parse_Accumulate() throws Exception { final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;"); - assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;"); + assertThat(accum.getInitCode()).isEqualTo( "int x = 0;"); + assertThat(accum.getActionCode()).isEqualTo( "x++;"); assertThat(accum.getReverseCode()).isNull(); - assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)"); + assertThat(accum.getResultCode()).isEqualTo( "new Integer(x)"); assertThat(accum.isExternalFunction()).isFalse(); @@ -2187,10 +2187,10 @@ public void parse_AccumulateWithBindings() throws Exception { final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace( "$counter"); - assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;"); - assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;"); - assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)"); + assertThat(outPattern.getIdentifier()).isEqualTo( "$counter"); + assertThat(accum.getInitCode()).isEqualTo( "int x = 0;"); + assertThat(accum.getActionCode()).isEqualTo( "x++;"); + assertThat(accum.getResultCode()).isEqualTo( "new Integer(x)"); final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); assertThat(pattern.getObjectType()).isEqualTo("Person"); @@ -2218,10 +2218,10 @@ public void accumulateWithoutOptionalDelimiters() throws Exception { final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace( "$counter"); - assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0"); - assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++"); - assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)"); + assertThat(outPattern.getIdentifier()).isEqualTo( "$counter"); + assertThat(accum.getInitCode()).isEqualTo( "int x = 0"); + assertThat(accum.getActionCode()).isEqualTo( "x++"); + assertThat(accum.getResultCode()).isEqualTo( "new Integer(x)"); final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); assertThat(pattern.getObjectType()).isEqualTo("Person"); 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 143e0a2da80..52b93f0af7b 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 @@ -792,7 +792,7 @@ public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) if (ctx.DRL_REVERSE() != null) { accumulateDescr.setReverseCode(getTextPreservingWhitespace(ctx.reverseBlockStatements)); } - accumulateDescr.setResultCode(ctx.expression().getText()); + accumulateDescr.setResultCode(getTextPreservingWhitespace(ctx.expression())); } else { // accumulate function accumulateDescr.addFunction(visitAccumulateFunction(ctx.accumulateFunction())); From c5e4f0c1d1fda8a90be6d368b4bb24d53857b6a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Tue, 7 May 2024 04:42:24 +0200 Subject: [PATCH 099/141] Allow empty queries (#5892) --- .../src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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/DRLParser.g4 index f0eba169bfe..6c37402f10f 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/DRLParser.g4 @@ -101,7 +101,7 @@ parameter : type? drlIdentifier ; // type is optional. Removed (LEFT_SQUARE RIGH lhs : DRL_WHEN lhsExpression* ; -queryLhs : lhsExpression+ ; +queryLhs : lhsExpression* ; lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed | lhsUnary #lhsUnarySingle From e5ce02eb4a56208253aa7ba2e387dc7fb17e8f53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Tue, 7 May 2024 04:42:47 +0200 Subject: [PATCH 100/141] Improve Verifier's consequence processing resiliency (#5887) --- .../java/org/drools/verifier/visitor/RuleDescrVisitor.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/RuleDescrVisitor.java b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/RuleDescrVisitor.java index 9a614cda74c..ca6f99b68c2 100644 --- a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/RuleDescrVisitor.java +++ b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/RuleDescrVisitor.java @@ -200,6 +200,10 @@ private Consequence visitConsequence(VerifierComponent parent, * Strip all comments out of the code. */ StringBuilder buffer = new StringBuilder(text); + + // Make sure there is a '\n' at the end of a comment even if it's the last line of the consequence. + buffer.append('\n'); + int commentIndex = buffer.indexOf("//"); while (commentIndex != -1) { From 1d0c2e316116c76c21ebbcb3f12ea887cfe3210b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 8 May 2024 08:42:41 +0200 Subject: [PATCH 101/141] Avoid NPE when the input DRL is empty (#5894) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 7 +++++++ .../drools/drl/parser/antlr4/DescrHelper.java | 20 +++++++++++-------- 2 files changed, 19 insertions(+), 8 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 ffc1eeac067..724662f4291 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 @@ -153,6 +153,13 @@ private QueryDescr parseAndGetFirstQueryDescrFromFile(String filename) { return parseAndGetFirstQueryDescr(readResource(filename)); } + @Test + void emptySource() { + final String source = ""; + final PackageDescr pkg = parseAndGetPackageDescr(source); + assertThat(pkg.getName()).isEmpty(); + } + @Test void parse_validPackage() { final String source = "package foo.bar.baz"; 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 b091b8f588f..a822b5ddf76 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 @@ -21,6 +21,7 @@ import java.util.List; import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.AndDescr; import org.drools.drl.ast.descr.AttributeDescr; @@ -38,23 +39,26 @@ private DescrHelper() { } public static T populateCommonProperties(T descr, ParserRuleContext ctx) { + Token startToken = ctx.getStart(); // Start token is never null. + // If the stop token is null, use the start token as both the start end the end. + Token stopToken = ctx.getStop() != null ? ctx.getStop() : startToken; if (descr instanceof ExprConstraintDescr) { // Backward Compatibility Notes: // Old DRL6Parser.constraint() has slightly different behavior for ExprConstraintDescr. Keep it for backward compatibility // When we will update LanguageLevel, we can align this with other Descr. - descr.setStartCharacter(ctx.getStart().getStartIndex()); - descr.setEndCharacter(ctx.getStop().getStopIndex()); - descr.setLocation(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); - descr.setEndLocation(ctx.getStop().getLine(), ctx.getStop().getCharPositionInLine()); + descr.setStartCharacter(startToken.getStartIndex()); + descr.setEndCharacter(stopToken.getStopIndex()); + descr.setLocation(startToken.getLine(), startToken.getCharPositionInLine()); + descr.setEndLocation(stopToken.getLine(), stopToken.getCharPositionInLine()); } else { - descr.setStartCharacter(ctx.getStart().getStartIndex()); + descr.setStartCharacter(startToken.getStartIndex()); // Backward Compatibility Notes: // Old DRL6Parser adds +1 for EndCharacter (except ExprConstraintDescr). This new parser follows the same to keep the backward compatibility. // However, it doesn't look reasonable. When we will update LanguageLevel, we can remove this +1. - descr.setEndCharacter(ctx.getStop().getStopIndex() + 1); - descr.setLocation(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); - descr.setEndLocation(ctx.getStop().getLine(), ctx.getStop().getCharPositionInLine() + ctx.getStop().getText().length() - 1); // last column of the end token + descr.setEndCharacter(stopToken.getStopIndex() + 1); + descr.setLocation(startToken.getLine(), startToken.getCharPositionInLine()); + descr.setEndLocation(stopToken.getLine(), stopToken.getCharPositionInLine() + stopToken.getText().length() - 1); // last column of the end token } return descr; } From fd7d3b77bbe58fd56f4a1d361faa7b4e0e77ce70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 8 May 2024 08:43:48 +0200 Subject: [PATCH 102/141] Avoid error when there is no space between rule keyword and rule name (#5898) --- .../drools/drl/parser/antlr4/MiscDRLParserTest.java | 11 +++++++++++ .../org/drools/drl/parser/antlr4/LexerHelper.java | 11 ++++++----- .../org/drools/drl/parser/util/ParserStringUtils.java | 5 ++++- .../testcoverage/functional/parser/DrlParserTest.java | 2 +- 4 files changed, 22 insertions(+), 7 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 724662f4291..8aa6b0fa866 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 @@ -4673,4 +4673,15 @@ static void assertNamespace(Collection children, String nam assertThat(children).isNotEmpty(); // Make sure that every child type is represented. assertThat(children).allSatisfy(baseDescr -> assertThat(baseDescr.getNamespace()).isEqualTo(namespace)); } + + @Test + public void noWhitespaceBetweenRuleKeywordAndName() { + final String text = "rule X when then end rule\"Y\" when then end rule'Z'when then end"; + + PackageDescr pkg = parseAndGetPackageDescr(text); + + assertThat(pkg.getRules()) + .map(RuleDescr::getName) + .containsExactly("X", "Y", "Z"); + } } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java index 479eebce85e..4960baaf315 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java @@ -18,7 +18,7 @@ */ package org.drools.drl.parser.antlr4; -import java.util.List; +import java.util.Set; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.IntStream; @@ -29,9 +29,10 @@ */ public class LexerHelper { - private static final List semiAndWS = List.of(';', ' ', '\t', '\n', '\r'); - private static final List statementKeywordsList = List.of(ParserHelper.statementKeywords); - private static final List attributeKeywordsList = List.of(DroolsSoftKeywords.SALIENCE, + private static final Set semiAndWS = Set.of(';', ' ', '\t', '\n', '\r'); + private static final Set delimiters = Set.of(';', ' ', '\t', '\n', '\r', '"', '\''); + private static final Set statementKeywordsList = Set.of(ParserHelper.statementKeywords); + private static final Set attributeKeywordsList = Set.of(DroolsSoftKeywords.SALIENCE, DroolsSoftKeywords.ENABLED, DroolsSoftKeywords.NO + "-" + DroolsSoftKeywords.LOOP, DroolsSoftKeywords.AUTO + "-" + DroolsSoftKeywords.FOCUS, @@ -82,7 +83,7 @@ private String captureNextToken() { StringBuilder sb = new StringBuilder(); while (true) { int la = input.LA(lookAheadCounter); - if (semiAndWS.contains((char) la) || la == IntStream.EOF) { + if (delimiters.contains((char) la) || la == IntStream.EOF) { break; } sb.append((char) la); diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java index b67e64dd17a..6226cc070e0 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java @@ -33,7 +33,10 @@ private ParserStringUtils() { public static String safeStripStringDelimiters(String value) { if (value != null) { value = value.trim(); - if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { + if (value.length() >= 2 && ( + value.startsWith("\"") && value.endsWith("\"") + || value.startsWith("'") && value.endsWith("'") + )) { value = value.substring(1, value.length() - 1); } } diff --git a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/parser/DrlParserTest.java b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/parser/DrlParserTest.java index dadbe10e7b1..9aa85201e2a 100644 --- a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/parser/DrlParserTest.java +++ b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/parser/DrlParserTest.java @@ -34,7 +34,7 @@ public DrlParserTest(final File file, final KieBaseTestConfiguration kieBaseTest super(file, kieBaseTestConfiguration); } - @Parameters + @Parameters(name = "{index}: {0}, {1}") public static Collection getParameters() { return getTestParamsFromFiles(getFiles("drl")); } From 4c684a885fdb2bb6268ed5006c539fbcdc584b24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 8 May 2024 08:46:05 +0200 Subject: [PATCH 103/141] Strip double quotes from declared entry-point ID (#5905) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 19 +++++++++++++++---- .../drl/parser/antlr4/DRLVisitorImpl.java | 2 +- 2 files changed, 16 insertions(+), 5 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 8aa6b0fa866..376af150e59 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 @@ -32,6 +32,7 @@ import java.util.Map; import java.util.Optional; import java.util.regex.Pattern; +import java.util.stream.Stream; import org.drools.drl.ast.descr.AccumulateDescr; import org.drools.drl.ast.descr.AccumulateImportDescr; @@ -74,6 +75,8 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import static org.assertj.core.api.Assertions.assertThat; @@ -3465,10 +3468,18 @@ public void parse_InfinityLiteral() throws Exception { } - @Test - public void parse_EntryPointDeclaration() throws Exception { + public static Stream entryPointIds() { + return Stream.of( + Arguments.of("eventStream", "eventStream"), + Arguments.of("\"My entry-point 'ID'\"", "My entry-point 'ID'") + ); + } + + @ParameterizedTest + @MethodSource("entryPointIds") + public void parse_EntryPointDeclaration(String sourceId, String expectedId) throws Exception { final String text = "package org.drools\n" + - "declare entry-point eventStream\n" + + "declare entry-point " + sourceId + "\n" + " @source(\"jndi://queues/events\")\n" + " @foo( true )\n" + "end"; @@ -3480,7 +3491,7 @@ public void parse_EntryPointDeclaration() throws Exception { EntryPointDeclarationDescr epd = pkg.getEntryPointDeclarations().iterator().next(); - assertThat(epd.getEntryPointId()).isEqualTo("eventStream"); + assertThat(epd.getEntryPointId()).isEqualTo(expectedId); assertThat(epd.getAnnotations().size()).isEqualTo(2); assertThat(epd.getAnnotation("source").getValue()).isEqualTo("\"jndi://queues/events\""); assertThat(epd.getAnnotation("foo").getValue()).isEqualTo("true"); 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 52b93f0af7b..1faa36574e8 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 @@ -292,7 +292,7 @@ public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPoin EntryPointDeclarationDescr entryPointDeclarationDescr = BaseDescrFactory.builder(new EntryPointDeclarationDescr()) .withParserRuleContext(ctx) .build(); - entryPointDeclarationDescr.setEntryPointId(ctx.name.getText()); + entryPointDeclarationDescr.setEntryPointId(safeStripStringDelimiters(ctx.name.getText())); ctx.drlAnnotation().stream() .map(this::visitDrlAnnotation) .forEach(entryPointDeclarationDescr::addAnnotation); From 5c75fb07930dd0191ee5b4cb40c6d9a072f9c54e Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 8 May 2024 16:20:38 +0900 Subject: [PATCH 104/141] =?UTF-8?q?[incubator-kie-drools-5879]=20[new-pars?= =?UTF-8?q?er]=20build=20failure=20on=20kie-dmn-val=E2=80=A6=20(#5899)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5879] [new-parser] build failure on kie-dmn-validation - WIP - test case only * - nongreedy subrule * - Add tests - also fix andRestriction --- .../drl/parser/antlr4/DRLExprParserTest.java | 108 +++++++++++++++++- .../drl/parser/antlr4/MiscDRLParserTest.java | 56 +++++++++ .../drl/parser/antlr4/DRL6Expressions.g4 | 4 +- .../model/codegen/execmodel/CompilerTest.java | 58 ++++++++++ 4 files changed, 221 insertions(+), 5 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 7a866ec2846..2a6d4e96a6a 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 @@ -18,9 +18,6 @@ */ package org.drools.drl.parser.antlr4; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - import java.util.Arrays; import java.util.List; @@ -43,6 +40,9 @@ 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; + /** * DRLExprTreeTest */ @@ -462,4 +462,106 @@ public void testNoViableAlt() { assertThat(parser.hasErrors()).isFalse(); } } + + @Test + void orWithMethodCall() { + String source = "value == 10 || someMethod() == 4"; + ConstraintConnectiveDescr result = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); // root is AND + assertThat(result.getDescrs().size()).isEqualTo(1); + ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get(0); + assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); + assertThat(or.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get(0); + assertThat(expr.getOperator()).isEqualTo("=="); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("value"); + assertThat(right.getExpression()).isEqualTo("10"); + + expr = (RelationalExprDescr) or.getDescrs().get(1); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod()"); + assertThat(right.getExpression()).isEqualTo("4"); + } + + @Test + void orWithMethodCallWithArg() { + String source = "value == 10 || someMethod(value) == 4"; + ConstraintConnectiveDescr result = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); // root is AND + assertThat(result.getDescrs().size()).isEqualTo(1); + ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get(0); + assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); + assertThat(or.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get(0); + assertThat(expr.getOperator()).isEqualTo("=="); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("value"); + assertThat(right.getExpression()).isEqualTo("10"); + + expr = (RelationalExprDescr) or.getDescrs().get(1); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod(value)"); + assertThat(right.getExpression()).isEqualTo("4"); + } + + @Test + void andWithMethodCall() { + String source = "value == 10 && someMethod() == 4"; + ConstraintConnectiveDescr result = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get(0); + assertThat(expr.getOperator()).isEqualTo("=="); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("value"); + assertThat(right.getExpression()).isEqualTo("10"); + + expr = (RelationalExprDescr) result.getDescrs().get(1); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod()"); + assertThat(right.getExpression()).isEqualTo("4"); + } + + @Test + void andWithMethodCallWithArg() { + String source = "value == 10 && someMethod(value) == 4"; + ConstraintConnectiveDescr result = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs().size()).isEqualTo(2); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get(0); + assertThat(expr.getOperator()).isEqualTo("=="); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("value"); + assertThat(right.getExpression()).isEqualTo("10"); + + expr = (RelationalExprDescr) result.getDescrs().get(1); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod(value)"); + assertThat(right.getExpression()).isEqualTo("4"); + } } 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 376af150e59..94802923bba 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 @@ -136,6 +136,14 @@ private RuleDescr parseAndGetFirstRuleDescr(String drl) { return pkg.getRules().get(0); } + private ExprConstraintDescr parseAndGetFirstConstraintDescr(String drl) { + RuleDescr rule = parseAndGetFirstRuleDescr(drl); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOf(PatternDescr.class); + PatternDescr patternDescr = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOf(ExprConstraintDescr.class); + return (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + } + private PackageDescr parseAndGetPackageDescrFromFile(String filename) { return parseAndGetPackageDescr(readResource(filename)); } @@ -4695,4 +4703,52 @@ public void noWhitespaceBetweenRuleKeywordAndName() { .map(RuleDescr::getName) .containsExactly("X", "Y", "Z"); } + + @Test + void orWithMethodCall() { + final String text = + "rule R1\n" + + "when\n" + + " MyFact( value == 10 || someMethod() == 4 )\n" + + "then\n" + + "end"; + ExprConstraintDescr exprConstraintDescr = parseAndGetFirstConstraintDescr(text); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("value == 10 || someMethod() == 4"); + } + + @Test + void orWithMethodCallWithArg() { + final String text = + "rule R1\n" + + "when\n" + + " MyFact( value == 10 || someMethod(value) == 4 )\n" + + "then\n" + + "end"; + ExprConstraintDescr exprConstraintDescr = parseAndGetFirstConstraintDescr(text); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("value == 10 || someMethod(value) == 4"); + } + + @Test + void andWithMethodCall() { + final String text = + "rule R1\n" + + "when\n" + + " MyFact( value == 10 && someMethod() == 4 )\n" + + "then\n" + + "end"; + ExprConstraintDescr exprConstraintDescr = parseAndGetFirstConstraintDescr(text); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("value == 10 && someMethod() == 4"); + } + + @Test + void andWithMethodCallWithArg() { + final String text = + "rule R1\n" + + "when\n" + + " MyFact( value == 10 && someMethod(value) == 4 )\n" + + "then\n" + + "end"; + ExprConstraintDescr exprConstraintDescr = parseAndGetFirstConstraintDescr(text); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("value == 10 && someMethod(value) == 4"); + } } 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/DRL6Expressions.g4 index 02c20088f4c..27734251f1e 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/DRL6Expressions.g4 @@ -519,7 +519,7 @@ orRestriction returns [BaseDescr result] $result = descr; } } - )* EOF? + )*? EOF? ; andRestriction returns [BaseDescr result] @@ -535,7 +535,7 @@ andRestriction returns [BaseDescr result] $result = descr; } } - )* + )*? ; singleRestriction returns [BaseDescr 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 8badee9adeb..702020fb7e5 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 @@ -3161,4 +3161,62 @@ public void testSharedConstraintWithExtraParenthesis() { assertThat(list.size()).isEqualTo(1); assertThat(list.get(0)).isEqualTo("r1"); } + + @Test + public void orWithMethodCall() { + final String str = + "package org.example\n" + + "import " + MyFact.class.getCanonicalName() + ";" + + "rule r1 when\n" + + " MyFact( value == 10 || someMethod() == 4 )\n" + + "then\n" + + "end\n"; + + KieSession ksession = getKieSession( str ); + + ksession.insert(new MyFact(5)); + int fired = ksession.fireAllRules(); + assertThat(fired).isEqualTo(1); + } + + @Test + public void orWithMethodCallWithArg() { + final String str = + "package org.example\n" + + "import " + MyFact.class.getCanonicalName() + ";" + + "rule r1 when\n" + + " MyFact( value == 10 || someMethod(2) == 4 )\n" + + "then\n" + + "end\n"; + + KieSession ksession = getKieSession( str ); + + ksession.insert(new MyFact(5)); + int fired = ksession.fireAllRules(); + assertThat(fired).isEqualTo(1); + } + + public static class MyFact { + private int value; + + public MyFact(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public int someMethod(int input) { + return input * 2; + } + + public int someMethod() { + return 4; + } + } } From fe52b11c12eb0182fae9ca3258aed4a293694316 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 9 May 2024 10:15:35 +0900 Subject: [PATCH 105/141] [incubator-kie-drools-5906] [new-parser] unification in accumulate (#5907) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 27 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 11 ++++++-- 3 files changed, 37 insertions(+), 3 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 94802923bba..899d7902d3a 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 @@ -4751,4 +4751,31 @@ void andWithMethodCallWithArg() { ExprConstraintDescr exprConstraintDescr = parseAndGetFirstConstraintDescr(text); assertThat(exprConstraintDescr.getExpression()).isEqualTo("value == 10 && someMethod(value) == 4"); } + + @Test + void unificationInAccumulateRule() { + final String text = + "rule R\n" + + "when\n" + + " MyFact($i : currentValue)\n" + + " accumulate( $p : Person( name == \"John\" ),\n" + + " $i := min( $p.getAge() ) )\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + AccumulateDescr accumulateDescr = (AccumulateDescr) outPattern.getSource(); + assertThat(accumulateDescr.getInputPattern()).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getIdentifier()).isEqualTo("$p"); + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + }); + + AccumulateDescr.AccumulateFunctionCallDescr accumulateFunction = accumulateDescr.getFunctions().get(0); + assertThat(accumulateFunction.getBind()).isEqualTo("$i"); + assertThat(accumulateFunction.isUnification()).isTrue(); + assertThat(accumulateFunction.getFunction()).isEqualTo("min"); + assertThat(accumulateFunction.getParams()).containsExactly("$p.getAge()"); + } } 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/DRLParser.g4 index 6c37402f10f..2416b09cfbf 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/DRLParser.g4 @@ -351,7 +351,7 @@ blockStatements : drlBlockStatement* ; /* accumulateFunction := label? ID parameters */ -accumulateFunction : label? drlIdentifier conditionalExpressions ; +accumulateFunction : (label|unif)? drlIdentifier conditionalExpressions ; // parameters := LEFT_PAREN (conditionalExpression (COMMA conditionalExpression)* )? RIGHT_PAREN conditionalExpressions : LPAREN (conditionalExpression (COMMA conditionalExpression)* )? RPAREN ; 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 1faa36574e8..8212a7f64c4 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 @@ -803,12 +803,19 @@ public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) @Override public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLParser.AccumulateFunctionContext ctx) { String function = ctx.drlIdentifier().getText(); - String bind = ctx.label() == null ? null : ctx.label().drlIdentifier().getText(); + String bind = null; + boolean unify = false; + if (ctx.label() != null) { + bind = ctx.label().drlIdentifier().getText(); + } else if (ctx.unif() != null) { + bind = ctx.unif().drlIdentifier().getText(); + unify = true; + } String[] params = ctx.conditionalExpressions().conditionalExpression().stream() .map(RuleContext::getText) .toArray(String[]::new); - return new AccumulateDescr.AccumulateFunctionCallDescr(function, bind, false, params); + return new AccumulateDescr.AccumulateFunctionCallDescr(function, bind, unify, params); } @Override From 06cc98392af4a7ee2428cd3297f1d6ed0e813e41 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 10 May 2024 10:34:40 +0900 Subject: [PATCH 106/141] [incubator-kie-drools-5912] [new-parser] Corner-case combinations of not, or, and exists (#5914) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 44 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 8 ++-- 2 files changed, 48 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 899d7902d3a..e2a039f709d 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 @@ -4778,4 +4778,48 @@ void unificationInAccumulateRule() { assertThat(accumulateFunction.getFunction()).isEqualTo("min"); assertThat(accumulateFunction.getParams()).containsExactly("$p.getAge()"); } + + @Test + void existsOrNot() { + final String text = + "rule R\n" + + "when\n" + + " exists(not(Integer()) or not(Double()))\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(ExistsDescr.class, existsDescr -> { + assertThat(existsDescr.getDescrs().get(0)).isInstanceOfSatisfying(OrDescr.class, orDescr -> { + assertThat(orDescr.getDescrs()).hasSize(2); + assertThat(orDescr.getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { + assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Integer"); + }); + }); + assertThat(orDescr.getDescrs().get(1)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { + assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Double"); + }); + }); + }); + }); + } + + @Test + void nestedNot() { + final String text = + "rule R\n" + + "when\n" + + " not ( not ( Cheese() ) )\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { + assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, nestedNotDescr -> { + assertThat(nestedNotDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Cheese"); + }); + }); + }); + } } 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/DRLParser.g4 index 2416b09cfbf..bf0d2f41ade 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/DRLParser.g4 @@ -105,9 +105,9 @@ queryLhs : lhsExpression* ; lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed | lhsUnary #lhsUnarySingle - | LPAREN DRL_AND lhsExpression+ RPAREN #lhsAnd + | DRL_AND lhsExpression+ #lhsAnd | lhsExpression (DRL_AND lhsExpression)+ #lhsAnd - | LPAREN DRL_OR lhsExpression+ RPAREN #lhsOr + | DRL_OR lhsExpression+ #lhsOr | lhsExpression (DRL_OR lhsExpression)+ #lhsOr ; @@ -373,7 +373,7 @@ fromWindow : DRL_WINDOW drlIdentifier ; ) */ // Use lhsExpression instead of lhsOr because lhsExpression has good enough structure -lhsExists : DRL_EXISTS ( lhsPatternBind | lhsExpression ) ; +lhsExists : DRL_EXISTS ( LPAREN lhsExpression RPAREN | lhsPatternBind ) ; /* lhsNot := NOT @@ -383,7 +383,7 @@ lhsExists : DRL_EXISTS ( lhsPatternBind | lhsExpression ) ; ) */ // Use lhsExpression instead of lhsOr because lhsExpression has good enough structure -lhsNot : DRL_NOT ( lhsPatternBind | lhsExpression ) ; +lhsNot : DRL_NOT ( LPAREN lhsExpression RPAREN | lhsPatternBind ) ; /** * lhsEval := EVAL LEFT_PAREN conditionalExpression RIGHT_PAREN From acac1c7a89c7cab98739302e539aa09d47d1a12d Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 10 May 2024 22:53:38 +0900 Subject: [PATCH 107/141] =?UTF-8?q?[incubator-kie-drools-5918]=20[new-pars?= =?UTF-8?q?er]=20Annotations=20can=20appear=20in=20lh=E2=80=A6=20(#5921)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5918] [new-parser] Annotations can appear in lhsOr and lhsAnd * - infix or, and --- .../drl/parser/antlr4/MiscDRLParserTest.java | 83 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 8 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 26 ++++-- 3 files changed, 107 insertions(+), 10 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 e2a039f709d..f4cd6e4c32f 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 @@ -3990,6 +3990,89 @@ void lhsPatternAnnotation() { assertThat(annotationDescr.getSingleValueAsString()).isEqualTo("!*, age"); } + @Test + void prefixAndDescrAnnotation() { + final String text = + "rule R\n" + + " when\n" + + " ( and @Annot \n" + + " String() \n" + + " Integer() ) \n" + + " then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + AndDescr andDescr = ruleDescr.getLhs(); + AnnotationDescr annotationDescr = andDescr.getAnnotations().iterator().next(); + assertThat(annotationDescr.getName()).isEqualTo("Annot"); + assertThat(annotationDescr.hasValue()).isFalse(); + + assertThat(andDescr.getDescrs()).hasSize(2); + } + + @Test + void prefixOrDescrAnnotation() { + final String text = + "rule R\n" + + " when\n" + + " ( or @Annot \n" + + " String() \n" + + " Integer() ) \n" + + " then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + OrDescr orDescr = (OrDescr) ruleDescr.getLhs().getDescrs().get(0); + AnnotationDescr annotationDescr = orDescr.getAnnotations().iterator().next(); + + assertThat(annotationDescr.getName()).isEqualTo("Annot"); + assertThat(annotationDescr.hasValue()).isFalse(); + + assertThat(orDescr.getDescrs()).hasSize(2); + } + + @Test + void infixAndDescrAnnotation() { + final String text = + "rule R\n" + + " when\n" + + " ( Double() \n" + + " and @Annot1 String() \n" + + " and @Annot2 Integer() ) " + + " then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + AndDescr andDescr = ruleDescr.getLhs(); + Collection annotationDescrs = andDescr.getAnnotations(); + assertThat(annotationDescrs).extracting(AnnotationDescr::getName).containsExactlyInAnyOrder("Annot1", "Annot2"); + + assertThat(andDescr.getDescrs()).hasSize(3); + } + + @Test + void infixOrDescrAnnotation() { + final String text = + "rule R\n" + + " when\n" + + " ( Double() \n" + + " or @Annot1 String() \n" + + " or @Annot2 Integer() ) " + + " then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + OrDescr orDescr = (OrDescr) ruleDescr.getLhs().getDescrs().get(0); + Collection annotationDescrs = orDescr.getAnnotations(); + assertThat(annotationDescrs).extracting(AnnotationDescr::getName).containsExactlyInAnyOrder("Annot1", "Annot2"); + + assertThat(orDescr.getDescrs()).hasSize(3); + } + @Test void annotationWithEmptyParentheses() { final String text = "package org.drools;\n" + 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/DRLParser.g4 index bf0d2f41ade..018375dd5d7 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/DRLParser.g4 @@ -105,10 +105,10 @@ queryLhs : lhsExpression* ; lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed | lhsUnary #lhsUnarySingle - | DRL_AND lhsExpression+ #lhsAnd - | lhsExpression (DRL_AND lhsExpression)+ #lhsAnd - | DRL_OR lhsExpression+ #lhsOr - | lhsExpression (DRL_OR lhsExpression)+ #lhsOr + | DRL_AND drlAnnotation* lhsExpression+ #lhsAnd + | lhsExpression (DRL_AND drlAnnotation* lhsExpression)+ #lhsAnd + | DRL_OR drlAnnotation* lhsExpression+ #lhsOr + | lhsExpression (DRL_OR drlAnnotation* lhsExpression)+ #lhsOr ; // lhsAnd is used as a label in lhsExpression rule. But some other rules explicitly use the def, so lhsAndDef is declared. 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 8212a7f64c4..80ce8d6986a 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 @@ -988,7 +988,13 @@ public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { // B() C() // So, we need to flatten it so that OrDescr has A(), B() and C() as children. List flattenedDescrs = flattenOrDescr(descrList); - flattenedDescrs.forEach(orDescr::addDescr); + flattenedDescrs.forEach(descr -> { + if (descr instanceof AnnotationDescr annotationDescr) { + orDescr.addAnnotation(annotationDescr); + } else { + orDescr.addDescr(descr); + } + }); return orDescr; } } @@ -998,9 +1004,10 @@ 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 && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { + if (descr instanceof OrDescr orDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { // sibling OrDescr should be flattened unless it's explicitly enclosed by parenthesis - flattenedDescrs.addAll(((OrDescr) descr).getDescrs()); + flattenedDescrs.addAll(orDescr.getDescrs()); + flattenedDescrs.addAll(orDescr.getAnnotations()); } else { flattenedDescrs.add(descr); } @@ -1032,7 +1039,13 @@ private BaseDescr createAndDescr(ParserRuleContext ctx) { // B() C() // So, we need to flatten it so that AndDescr has A(), B() and C() as children. List flattenedDescrs = flattenAndDescr(descrList); - flattenedDescrs.forEach(andDescr::addDescr); + flattenedDescrs.forEach(descr -> { + if (descr instanceof AnnotationDescr annotationDescr) { + andDescr.addAnnotation(annotationDescr); + } else { + andDescr.addDescr(descr); + } + }); return andDescr; } } @@ -1042,9 +1055,10 @@ 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 && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { + if (descr instanceof AndDescr andDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { // sibling AndDescr should be flattened unless it's explicitly enclosed by parenthesis - flattenedDescrs.addAll(((AndDescr) descr).getDescrs()); + flattenedDescrs.addAll(andDescr.getDescrs()); + flattenedDescrs.addAll(andDescr.getAnnotations()); } else { flattenedDescrs.add(descr); } From c9df2fb390271bb876a6792720ba47edf5cbc686 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 10 May 2024 22:54:15 +0900 Subject: [PATCH 108/141] [incubator-kie-drools-5915] [new-parser] ctx.lhsPattern().size() == 0 (#5922) - Avoid unnecessary IllegalStateException - Avoid empty error message --- .../drl/parser/antlr4/MiscDRLParserTest.java | 15 +++++++++++++++ .../drools/drl/parser/antlr4/DRLParserError.java | 1 + .../drools/drl/parser/antlr4/DRLVisitorImpl.java | 2 +- 3 files changed, 17 insertions(+), 1 deletion(-) 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 f4cd6e4c32f..183d2843345 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 @@ -69,6 +69,7 @@ import org.drools.drl.ast.descr.TypeFieldDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; import org.drools.drl.parser.DrlParser; +import org.drools.drl.parser.DroolsError; import org.drools.drl.parser.DroolsParserException; import org.drools.drl.parser.impl.Operator; import org.junit.jupiter.api.BeforeEach; @@ -4905,4 +4906,18 @@ void nestedNot() { }); }); } + + @Test + void errorMessage_shouldNotContainEmptyString() { + final String text = + "rule R\n" + + "when\n" + + " foo\n" + // parse error + "then\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescrWithoutErrorCheck(text); + assertThat(pkg).isNull(); + assertThat(parser.hasErrors()).isTrue(); + assertThat(parser.getErrors()).extracting(DroolsError::getMessage).doesNotContain(""); + } } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserError.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserError.java index 7c8f2c68900..e07eef4a491 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserError.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserError.java @@ -36,6 +36,7 @@ public DRLParserError(int lineNumber, int column, String message) { } public DRLParserError(Exception exception) { + this.message = exception.getMessage(); this.exception = exception; } 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 80ce8d6986a..4b0036e669b 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 @@ -542,7 +542,7 @@ public BaseDescr visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { } else if (ctx.lhsPattern().size() > 1) { return getOrDescrWithMultiplePatternDescr(ctx); } else { - throw new IllegalStateException("ctx.lhsPattern().size() == 0 : " + ctx.getText()); + return null; // only caused by a parser error } } From 10979027f3cb46459a8fb8eb43344bc935b1d2a4 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 13 May 2024 14:23:27 +0900 Subject: [PATCH 109/141] [incubator-kie-drools-5908] ReteOOWaltzTest 'end' detection issue (#5913) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5908] ReteOOWaltzTest 'end' detection issue * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker --------- Co-authored-by: Jiří Locker --- .../drl/parser/antlr4/MiscDRLParserTest.java | 77 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLLexer.g4 | 5 +- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- 3 files changed, 82 insertions(+), 2 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 183d2843345..8b220177dfd 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 @@ -3728,6 +3728,83 @@ void endAndMultiLineCommentAndRule() { assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); } + @Test + void endAndNonPairingDoubleQuoteInSingleLineCommentInRHS() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " //System.out.println(\");\n" + // non-pairing double quote in comment + " retract($p)\n" + + "end\n" + + "rule \"R2\" when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndNonPairingDoubleQuoteInMultiLineCommentInRHS() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " /*System.out.println\n" + + " (\");*/\n" + // non-pairing double quote in comment + " retract($p)\n" + + "end\n" + + "rule \"R2\" when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndDoubleQuotationsInRHS() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " System.out.println(\"Draw \"+$p1+\" \"+$p2);\n" + + " retract($p)\n" + + "end\n" + + "rule \"R2\" when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndSingleQuotationsInRHS() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " System.out.println('Draw '+$p1+' '+$p2);\n" + + " retract($p)\n" + + "end\n" + + "rule \"R2\" when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + @Test void singleQuoteInRhsWithSpace() { String consequence = getResultConsequence(" System.out.println( 'singleQuoteInRhs' );\n"); 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/DRLLexer.g4 index 58719554dec..5809147d651 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/DRLLexer.g4 @@ -169,6 +169,9 @@ DrlUnicodeEscape mode RHS; RHS_WS : [ \t\r\n\u000C]+ -> channel(HIDDEN); +RHS_COMMENT: '/*' .*? '*/' ; +RHS_LINE_COMMENT: '//' ~[\r\n]* ; + //DRL_RHS_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) { setText("end"); } -> popMode; DRL_RHS_END : {isRhsDrlEnd()}? DRL_END -> popMode; @@ -181,7 +184,7 @@ RHS_STRING_LITERAL RHS_NAMED_CONSEQUENCE_THEN : DRL_THEN LBRACK IDENTIFIER RBRACK ; RHS_CHUNK - : ~[ ()[\]{},;\t\r\n\u000C]+ // ;}) could be a delimitter proceding 'end'. ()[]{},; are delimiters to match RHS_STRING_LITERAL + : ~[ "'()[\]{},;\t\r\n\u000C]+ // ;}) could be a delimitter proceding 'end'. ()[]{},; are delimiters to match RHS_STRING_LITERAL | LPAREN | RPAREN | LBRACK 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/DRLParser.g4 index 018375dd5d7..e277eb98265 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/DRLParser.g4 @@ -420,7 +420,7 @@ groupByKeyBinding : label? conditionalExpression ; rhs : DRL_THEN consequenceBody namedConsequence* ; -consequenceBody : ( RHS_STRING_LITERAL | RHS_CHUNK )* ; +consequenceBody : ( RHS_COMMENT | RHS_LINE_COMMENT | RHS_STRING_LITERAL | RHS_CHUNK )* ; // THEN LEFT_SQUARE ID RIGHT_SQUARE chunk namedConsequence : RHS_NAMED_CONSEQUENCE_THEN consequenceBody ; From dcf848f38998e07939047c03097f2556ccdcaacd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Mon, 13 May 2024 10:06:34 +0200 Subject: [PATCH 110/141] Match EOF at the end of the compilation unit (#5930) --- .../antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- .../java/org/drools/drl/parser/antlr4/DescrHelper.java | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) 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/DRLParser.g4 index e277eb98265..da397785c1d 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/DRLParser.g4 @@ -14,7 +14,7 @@ import DRL6Expressions, JavaParser; * | query * ; */ -compilationUnit : packagedef? unitdef? drlStatementdef* ; +compilationUnit : packagedef? unitdef? drlStatementdef* EOF ; drlStatementdef : importdef SEMI? 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 a822b5ddf76..02a4f38d276 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 @@ -22,9 +22,6 @@ import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; -import org.antlr.v4.runtime.tree.TerminalNode; -import org.drools.drl.ast.descr.AndDescr; -import org.drools.drl.ast.descr.AttributeDescr; import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.ExprConstraintDescr; import org.drools.drl.ast.descr.PatternDescr; @@ -58,11 +55,15 @@ public static T populateCommonProperties(T descr, ParserRu // However, it doesn't look reasonable. When we will update LanguageLevel, we can remove this +1. descr.setEndCharacter(stopToken.getStopIndex() + 1); descr.setLocation(startToken.getLine(), startToken.getCharPositionInLine()); - descr.setEndLocation(stopToken.getLine(), stopToken.getCharPositionInLine() + stopToken.getText().length() - 1); // last column of the end token + descr.setEndLocation(stopToken.getLine(), stopToken.getCharPositionInLine() + stopTokenLength(stopToken) - 1); // last column of the end token } return descr; } + private static int stopTokenLength(Token token) { + return token.getType() == Token.EOF ? 0 : token.getText().length(); + } + public static T populateCommonProperties(T descr, List ctxList) { if (ctxList.isEmpty()) { return descr; From c08fca1975dcaeceaf4b687956fb3e877fd0c38b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Tue, 14 May 2024 08:41:16 +0200 Subject: [PATCH 111/141] Use InternalResource's encoding (#5940) --- .../src/main/java/org/drools/drl/parser/DrlParser.java | 2 +- .../java/org/drools/drl/parser/antlr4/DRLParserHelper.java | 7 +++++-- .../org/drools/drl/parser/antlr4/DRLParserWrapper.java | 4 ++-- 3 files changed, 8 insertions(+), 5 deletions(-) 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 5e6fb78c6f2..26ee6dffb7b 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 @@ -188,7 +188,7 @@ public PackageDescr parse(final boolean isEditor, System.out.println("### parse : ANTLR4_PARSER_ENABLED = " + ANTLR4_PARSER_ENABLED); if (ANTLR4_PARSER_ENABLED) { // new parser based on antlr4 - return compileWithAntlr4Parser(parser -> parser.parse(is)); + return compileWithAntlr4Parser(parser -> parser.parse(is, encoding)); } else { // old parsers based on antlr3 lexer = DRLFactory.buildLexer(is, encoding, languageLevel); 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/DRLParserHelper.java index 9c8fef57d0d..7d945f6bb8b 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/DRLParserHelper.java @@ -22,6 +22,7 @@ import java.io.InputStream; import java.io.Reader; import java.io.UncheckedIOException; +import java.nio.charset.Charset; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; @@ -56,9 +57,11 @@ public static DRLParser createDrlParser(String drl) { return createDrlParser(charStream); } - public static DRLParser createDrlParser(InputStream is) { + public static DRLParser createDrlParser(InputStream is, String encoding) { try { - CharStream charStream = CharStreams.fromStream(is); + CharStream charStream = encoding != null + ? CharStreams.fromStream(is, Charset.forName(encoding)) + : CharStreams.fromStream(is); return createDrlParser(charStream); } catch (IOException e) { throw new UncheckedIOException(e); 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/DRLParserWrapper.java index c28e57b9974..e2f8ee99604 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/DRLParserWrapper.java @@ -50,8 +50,8 @@ public PackageDescr parse(String drl) { /** * Main entry point for parsing DRL */ - public PackageDescr parse(InputStream is) { - DRLParser drlParser = DRLParserHelper.createDrlParser(is); + public PackageDescr parse(InputStream is, String encoding) { + DRLParser drlParser = DRLParserHelper.createDrlParser(is, encoding); return parse(drlParser); } From 9ac7944cb6b3607d8c4a665c57c0d61cd0a42ccc Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 14 May 2024 23:19:14 +0900 Subject: [PATCH 112/141] [incubator-kie-drools-5924] [new-parser] Remove DRLIncompleteCodeTest (#5941) * [incubator-kie-drools-5924] [new-parser] Disable DRLIncompleteCodeTest * Remove editor mode tests --- .../compiler/lang/DRLIncompleteCodeTest.java | 250 ------------------ .../mvel/compiler/lang/RuleParserTest.java | 20 -- 2 files changed, 270 deletions(-) delete mode 100644 drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLIncompleteCodeTest.java diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLIncompleteCodeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLIncompleteCodeTest.java deleted file mode 100644 index 04ba8d26389..00000000000 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLIncompleteCodeTest.java +++ /dev/null @@ -1,250 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.mvel.compiler.lang; - -import java.util.LinkedList; - -import org.antlr.runtime.RecognitionException; -import org.drools.compiler.builder.impl.EvaluatorRegistry; -import org.drools.drl.ast.descr.PackageDescr; -import org.drools.drl.parser.DrlParser; -import org.drools.drl.parser.DroolsParserException; -import org.drools.drl.parser.lang.Location; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.kie.internal.builder.conf.LanguageLevelOption; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DRLIncompleteCodeTest { - - @Before - public void setup() { - // just initialising the static operator definitions - new EvaluatorRegistry(); - } - - @Test - @Ignore - public void testIncompleteCode1() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.* rule MyRule when Class ( property memberOf collexction "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - System.out.println(parser.getErrors()); - - assertThat(descr).isNotNull(); - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - - assertThat(getLastIntegerValue(parser.getEditorSentences().get(2) - .getContent())).isEqualTo(Location.LOCATION_LHS_INSIDE_CONDITION_END); - } - - @Test - public void testIncompleteCode2() throws DroolsParserException, - RecognitionException { - String input = "rule MyRule when Class ( property memberOf collection "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr).isNotNull(); - assertThat(getLastIntegerValue(parser.getEditorSentences().get(0) - .getContent())).isEqualTo(Location.LOCATION_LHS_INSIDE_CONDITION_END); - } - - @Test - public void testIncompleteCode3() throws DroolsParserException, - RecognitionException { - String input = "rule MyRule when Class ( property > somevalue ) then end query MyQuery Class ( property == collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr).isNotNull(); - assertThat(descr.getRules().get(0).getName()).isEqualTo("MyRule"); - - assertThat(descr).isNotNull(); - assertThat(descr.getRules().get(1).getName()).isEqualTo("MyQuery"); - - assertThat(getLastIntegerValue(parser - .getEditorSentences().get(0).getContent())).isEqualTo(Location.LOCATION_RHS); - } - - @Test - public void testIncompleteCode4() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.*" - + " rule MyRule when Class ( property == collection ) then end " - + " query MyQuery Class ( property == collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - - assertThat(descr).isNotNull(); - assertThat(descr.getRules().get(0).getName()).isEqualTo("MyRule"); - - assertThat(descr).isNotNull(); - assertThat(descr.getRules().get(1).getName()).isEqualTo("MyQuery"); - } - - @Test - public void testIncompleteCode5() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.*" - + " rule MyRule when Class ( property memberOf collection ) then end " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr).isNotNull(); - } - - @Test - public void testIncompleteCode6() throws DroolsParserException, - RecognitionException { - String input = "packe 1111.111 import a.b.c.*" - + " rule MyRule when Class ( property memberOf collection ) then end " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr).isNotNull(); - } - - @Test - public void testIncompleteCode7() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c imrt a.b.c.*" - + " rule MyRule when Class ( property memberOf collection ) then end " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr).isNotNull(); - } - - @Test - public void testIncompleteCode8() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.1111.c.*" - + " rule MyRule when Class ( property memberOf collection ) then end " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - System.out.println(parser.getErrors()); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - // FIXME: assertEquals(2, descr.getRules().size()); - assertThat(parser.hasErrors()).isEqualTo(true); - } - - @Test @Ignore - public void testIncompleteCode9() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.*" - + " rule MyRule xxxxx Class ( property memberOf collection ) then end " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - - assertThat(descr.getRules().size()).isEqualTo(1); - assertThat(descr.getRules().get(0).getName()).isEqualTo("MyQuery"); - } - - @Test @Ignore - public void testIncompleteCode10() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.*" - + " rule MyRule xxxxx Class ( property memberOf " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - - assertThat(descr.getRules().size()).isEqualTo(0); - } - - @Test - public void testIncompleteCode11() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.*" - + " rule MyRule when Class ( property memberOf collection ) then end " - + " qzzzzuery MyQuery Class ( property "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - - assertThat(descr).isNotNull(); - assertThat(descr.getRules().get(0).getName()).isEqualTo("MyRule"); - } - - @Test - public void testIncompleteCode12() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c " + "import a.b.c.* " + "rule MyRule" - + " when " + " m: Message( ) " + " " + " then" - + "end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - assertThat(descr).isNotNull(); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - } - - @Test - public void testIncompleteCode13() throws DroolsParserException, - RecognitionException { - String input = "package com.sample " - + "import com.sample.DroolsTest.Message; " - + "rule \"Hello World\"" + " when " + " then" + " \\\" " - + "end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - assertThat(descr).isNotNull(); - } - - @SuppressWarnings("unchecked") - private int getLastIntegerValue(LinkedList list) { - // System.out.println(list.toString()); - int lastIntergerValue = -1; - for (Object object : list) { - if (object instanceof Integer) { - lastIntergerValue = (Integer) object; - } - } - return lastIntergerValue; - } -} diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java index 3ad7c622d01..1566604d241 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java @@ -110,26 +110,6 @@ public void testPackage() throws Exception { assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); } - @Test - public void testPackageWithError() throws Exception { - final String source = "package 12 foo.bar.baz"; - final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); - final PackageDescr pkg = parser.parse( true, - new StringReader( source ) ); - assertThat(parser.hasErrors()).isTrue(); - assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); - } - - @Test - public void testPackageWithError2() throws Exception { - final String source = "package 12 12312 231"; - final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); - final PackageDescr pkg = parser.parse( true, - new StringReader( source ) ); - assertThat(parser.hasErrors()).isTrue(); - assertThat(pkg.getName()).isEqualTo(""); - } - @Test public void testCompilationUnit() throws Exception { final String source = "package foo; import com.foo.Bar; import com.foo.Baz;"; From 5dc109eb0e4fd14beb7afbde6fae0371afc89889 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 15 May 2024 08:11:38 +0200 Subject: [PATCH 113/141] Set namespace of qualified declared types (#5947) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 14 ++++++++++ .../antlr4/qualified_type_declaration.drl | 27 +++++++++++++++++++ .../drl/parser/antlr4/DRLVisitorImpl.java | 10 +++++-- 3 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_type_declaration.drl 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 8b220177dfd..8075c89aed6 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 @@ -3071,6 +3071,20 @@ public void parse_TypeDeclarationWithFields() throws Exception { } + @Test + public void parse_QualifiedTypeDeclaration() throws Exception { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "qualified_type_declaration.drl" ); + + TypeDeclarationDescr someFact = pkg.getTypeDeclarations().get( 0 ); + assertThat(someFact.getTypeName()).isEqualTo("SomeFact"); + assertThat(someFact.getNamespace()).isEqualTo("com.sample1"); + + EnumDeclarationDescr color = pkg.getEnumDeclarations().get( 0 ); + assertThat(color.getTypeName()).isEqualTo("Color"); + assertThat(color.getNamespace()).isEqualTo("com.sample2"); + } + @Test public void parenthesesOneLevelNestWithThreeSiblings() throws Exception { final PackageDescr pkg = parseAndGetPackageDescrFromFile( "Rule_with_nested_LHS.drl" ); diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_type_declaration.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_type_declaration.drl new file mode 100644 index 00000000000..0eaa7067117 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_type_declaration.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +declare com.sample1.SomeFact + name : String + age: Integer +end + +declare enum com.sample2.Color + WHITE; +end 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 4b0036e669b..49a527612ab 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 @@ -235,9 +235,12 @@ public BaseDescr visitDeclaredef(DRLParser.DeclaredefContext ctx) { @Override public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContext ctx) { - TypeDeclarationDescr typeDeclarationDescr = BaseDescrFactory.builder(new TypeDeclarationDescr(ctx.name.getText())) + TypeDeclarationDescr typeDeclarationDescr = BaseDescrFactory.builder(new TypeDeclarationDescr()) .withParserRuleContext(ctx) .build(); + + typeDeclarationDescr.setTypeName(ctx.name.getText()); + if (ctx.DRL_TRAIT() != null) { typeDeclarationDescr.setTrait(true); } @@ -257,9 +260,12 @@ public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContex @Override public EnumDeclarationDescr visitEnumDeclaration(DRLParser.EnumDeclarationContext ctx) { - EnumDeclarationDescr enumDeclarationDescr = BaseDescrFactory.builder(new EnumDeclarationDescr(ctx.name.getText())) + EnumDeclarationDescr enumDeclarationDescr = BaseDescrFactory.builder(new EnumDeclarationDescr()) .withParserRuleContext(ctx) .build(); + + enumDeclarationDescr.setTypeName(ctx.name.getText()); + ctx.drlAnnotation().stream() .map(this::visitDrlAnnotation) .forEach(enumDeclarationDescr::addAnnotation); From da58c7dd919622d6de240f490fbdf91d1555eea8 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 15 May 2024 18:07:58 +0900 Subject: [PATCH 114/141] [incubator-kie-drools-5945] [new-parser] Broken named consequences inside OR (#5950) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Tests for incubator-kie-drools-5945 * [incubator-kie-drools-5945] [new-parser] Broken named consequences inside OR --------- Co-authored-by: Jiří Locker --- .../drl/parser/antlr4/MiscDRLParserTest.java | 92 +++++++++++++++++++ .../drl/parser/antlr4/DRLVisitorImpl.java | 15 ++- 2 files changed, 105 insertions(+), 2 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 8075c89aed6..bf553765e26 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 @@ -4657,6 +4657,98 @@ void namedConsequenceOrWithBindVariables() { assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMarkOrMario"); } + @Test + void testNamedConsequencesInsideOR1() { + final String text = + "import org.drools.mvel.compiler.Cheese;\n " + + "global java.util.List results;\n" + + "\n" + + "rule R1 when\n" + + " ( $a: Cheese ( type == \"stilton\" ) do[t1]\n" + + " or\n" + + " $b: Cheese ( type == \"gorgonzola\" ) )\n" + + " $c: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $c.getType() );\n" + + "then[t1]\n" + + " results.add( $a.getType() );\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + assertThat(ruleDescr.getLhs().getDescrs()).hasSize(2); + assertThat(ruleDescr.getLhs().getDescrs()).first().isInstanceOfSatisfying(OrDescr.class, stiltonOrGorgonzola -> { + assertThat(stiltonOrGorgonzola.getDescrs()).hasSize(2); + assertThat(stiltonOrGorgonzola.getDescrs()).first().isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs()).hasSize(2); + assertThat(andDescr.getDescrs()).first().isInstanceOfSatisfying(PatternDescr.class, stilton -> { + assertThat(stilton.getIdentifier()).isEqualTo("$a"); + assertThat(stilton.getObjectType()).isEqualTo("Cheese"); + assertThat(stilton.getConstraint().toString()).contains("stilton"); + }); + assertThat(andDescr.getDescrs()).last().isInstanceOfSatisfying(NamedConsequenceDescr.class, namedConsequenceDescr -> { + assertThat(namedConsequenceDescr.getName()).isEqualTo("t1"); + }); + }); + assertThat(stiltonOrGorgonzola.getDescrs()).last().isInstanceOfSatisfying(PatternDescr.class, gorgonzola -> { + assertThat(gorgonzola.getIdentifier()).isEqualTo("$b"); + assertThat(gorgonzola.getObjectType()).isEqualTo("Cheese"); + assertThat(gorgonzola.getConstraint().toString()).contains("gorgonzola"); + }); + }); + assertThat(ruleDescr.getLhs().getDescrs()).last().isInstanceOfSatisfying(PatternDescr.class, cheddar -> { + assertThat(cheddar.getIdentifier()).isEqualTo("$c"); + assertThat(cheddar.getObjectType()).isEqualTo("Cheese"); + assertThat(cheddar.getConstraint().toString()).contains("cheddar"); + }); + } + + @Test + void testNamedConsequencesInsideOR2() { + final String text = + "import org.drools.mvel.compiler.Cheese;\n " + + "global java.util.List results;\n" + + "\n" + + "rule R1 when\n" + + " ( $a: Cheese ( type == \"stilton\" )\n" + + " or\n" + + " $b: Cheese ( type == \"gorgonzola\" ) do[t1] )\n" + + " $c: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $c.getType() );\n" + + "then[t1]\n" + + " results.add( $b.getType() );\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + assertThat(ruleDescr.getLhs().getDescrs()).hasSize(2); + assertThat(ruleDescr.getLhs().getDescrs()).first().isInstanceOfSatisfying(OrDescr.class, stiltonOrGorgonzola -> { + assertThat(stiltonOrGorgonzola.getDescrs()).hasSize(2); + assertThat(stiltonOrGorgonzola.getDescrs()).first().isInstanceOfSatisfying(PatternDescr.class, stilton -> { + assertThat(stilton.getIdentifier()).isEqualTo("$a"); + assertThat(stilton.getObjectType()).isEqualTo("Cheese"); + assertThat(stilton.getConstraint().toString()).contains("stilton"); + }); + assertThat(stiltonOrGorgonzola.getDescrs()).last().isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs()).hasSize(2); + assertThat(andDescr.getDescrs()).first().isInstanceOfSatisfying(PatternDescr.class, gorgonzola -> { + assertThat(gorgonzola.getIdentifier()).isEqualTo("$b"); + assertThat(gorgonzola.getObjectType()).isEqualTo("Cheese"); + assertThat(gorgonzola.getConstraint().toString()).contains("gorgonzola"); + }); + assertThat(andDescr.getDescrs()).last().isInstanceOfSatisfying(NamedConsequenceDescr.class, namedConsequenceDescr -> { + assertThat(namedConsequenceDescr.getName()).isEqualTo("t1"); + }); + }); + }); + assertThat(ruleDescr.getLhs().getDescrs()).last().isInstanceOfSatisfying(PatternDescr.class, cheddar -> { + assertThat(cheddar.getIdentifier()).isEqualTo("$c"); + assertThat(cheddar.getObjectType()).isEqualTo("Cheese"); + assertThat(cheddar.getConstraint().toString()).contains("cheddar"); + }); + } + @Test public void queryComplexLhs() { final String text = "query isContainedIn(String x, String y)\n" + 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 49a527612ab..7001beed648 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 @@ -1078,8 +1078,19 @@ public BaseDescr visitLhsAndDef(DRLParser.LhsAndDefContext ctx) { } @Override - public List visitLhsUnary(DRLParser.LhsUnaryContext ctx) { - return visitDescrChildren(ctx); // lhsUnary may have consequenceInvocation, so not always a single child + public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { + List children = visitDescrChildren(ctx); + if (children.size() > 1) { + // lhsUnary may have multiple children e.g. consequenceInvocation, connect with AND + AndDescr andDescr = BaseDescrFactory.builder(new AndDescr()) + .withParserRuleContext(ctx) + .build(); + children.forEach(andDescr::addDescr); + return andDescr; + } else { + // size == 1. children never be empty + return children.get(0); + } } /** From a314a396e4c0f01e8d36decdb370e9f17dcce4c0 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 21 May 2024 15:51:56 +0900 Subject: [PATCH 115/141] =?UTF-8?q?[incubator-kie-drools-5818]=20[new-pars?= =?UTF-8?q?er]=20Parsing=20fails=20if=20a=20Java=20keyw=E2=80=A6=20(#5958)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5818] [new-parser] Parsing fails if a Java keyword appears in a qualified name * - Exclude 'new' from 'drlIdentifier' because of 'primary' ambiguity - Add tests --- .../drl/parser/antlr4/DRLExprParserTest.java | 22 +++++-- .../drl/parser/antlr4/MiscDRLParserTest.java | 19 ++++++ .../drl/parser/antlr4/ParserTestUtils.java | 19 ++++++ .../drl/parser/antlr4/DRL6Expressions.g4 | 59 ++++++++++++++++++- 4 files changed, 112 insertions(+), 7 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 2a6d4e96a6a..6489f3fdf80 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 @@ -442,12 +442,13 @@ public void testExtraneousInput() { @Test public void testNoViableAlt() { - String source = "x.int"; + String source = "a~a"; parser.parse(source); // Backward Compatibility Notes: - // Old expr parser (DRL6Expressions) allows this expression because it's too tolerant (fail at runtime anyway). - // Backward compatibility doesn't seem to be required in this case. (But we may align with the old tolerant behavior.) + // Old expr parser (DRL6Expressions) allows this expression and only takes "a" ignoring the invalid part "~a" without emitting an error. + // This is rather a bug in the old parser, and the new parser (ANTLR4) correctly emits an error for this case. + // Backward compatibility doesn't seem to be required in this case. if (DrlParser.ANTLR4_PARSER_ENABLED) { assertThat(parser.hasErrors()).isTrue(); assertThat(parser.getErrors()).hasSize(1); @@ -457,7 +458,7 @@ public void testNoViableAlt() { assertThat(exception.getColumn()).isEqualTo(2); assertThat(exception.getOffset()).isEqualTo(2); assertThat(exception.getMessage()) - .isEqualToIgnoringCase("[ERR 101] Line 1:2 no viable alternative at input '.int'"); + .isEqualToIgnoringCase("[ERR 101] Line 1:2 no viable alternative at input 'a'"); } else { assertThat(parser.hasErrors()).isFalse(); } @@ -564,4 +565,17 @@ void andWithMethodCallWithArg() { assertThat(left.getExpression()).isEqualTo("someMethod(value)"); assertThat(right.getExpression()).isEqualTo("4"); } + + @Test + void newBigDecimal() { + String source = "$bd : new BigDecimal(30)"; + ConstraintConnectiveDescr result = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getDescrs().size()).isEqualTo(1); + + BindingDescr bind = (BindingDescr) result.getDescrs().get(0); + assertThat(bind.getVariable()).isEqualTo("$bd"); + assertThat(bind.getExpression()).isEqualTo("new BigDecimal(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 bf553765e26..85c8423ba89 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 @@ -5103,4 +5103,23 @@ void errorMessage_shouldNotContainEmptyString() { assertThat(parser.hasErrors()).isTrue(); assertThat(parser.getErrors()).extracting(DroolsError::getMessage).doesNotContain(""); } + + @ParameterizedTest + @MethodSource("org.drools.drl.parser.antlr4.ParserTestUtils#javaKeywords") + void javaKeywordsInPackage(String keyword) { + String pkgName = "org.drools." + keyword; + String text = "package " + pkgName + "\n" + + "rule R\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + "end\n"; + + PackageDescr pkg = parseAndGetPackageDescr(text); + + assertThat(pkg.getName()).isEqualTo(pkgName); + assertThat(pkg.getRules()).hasSize(1); + + assertThat(pkg.getRules().get(0).getName()).isEqualTo("R"); + } } 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 270b8f8c37c..3419eab65e5 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 @@ -18,10 +18,25 @@ */ package org.drools.drl.parser.antlr4; +import java.util.Arrays; +import java.util.List; + import org.drools.drl.parser.DrlParser; public class ParserTestUtils { + // 'new' is not included because it cannot be included in drlIdentifier. + // See https://github.com/apache/incubator-kie-drools/pull/5958 + public static List javaKeywords = + Arrays.asList( + "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", + "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", + "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", + "package", "private", "protected", "public", "return", "short", "static", "strictfp", + "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", + "while" + ); + private ParserTestUtils() { // It is a utility class, so it should not be instantiated. } @@ -39,4 +54,8 @@ public static DrlParser getParser() { 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/DRL6Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 index 27734251f1e..f2a5a79f195 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/DRL6Expressions.g4 @@ -162,6 +162,58 @@ typeArgument drlIdentifier returns [Token token] : drlKeywords | IDENTIFIER + // java keywords + | ABSTRACT + | ASSERT + | BOOLEAN + | BREAK + | BYTE + | CASE + | CATCH + | CHAR + | CLASS + | CONST + | CONTINUE + | DEFAULT + | DO + | DOUBLE + | ELSE + | ENUM + | EXTENDS + | FINAL + | FINALLY + | FLOAT + | FOR + | IF + | GOTO + | IMPLEMENTS + | IMPORT + | INSTANCEOF + | INT + | INTERFACE + | LONG + | NATIVE +// | NEW // avoid ambiguity with 'new_key creator' and 'drlIdentifier' in 'primary' + | PACKAGE + | PRIVATE + | PROTECTED + | PUBLIC + | RETURN + | SHORT + | STATIC + | STRICTFP + | SUPER + | SWITCH + | SYNCHRONIZED + | THIS + | THROW + | THROWS + | TRANSIENT + | TRY + | VOID + | VOLATILE + | WHILE + // Module related keywords | MODULE | OPEN | REQUIRES @@ -172,12 +224,13 @@ drlIdentifier returns [Token token] | PROVIDES | WITH | TRANSITIVE + // other java keywords + | VAR | YIELD + | RECORD | SEALED | PERMITS - | RECORD - | VAR - | THIS + | NON_SEALED ; // matches any drl keywords From 4769de16986975fe285c4912609c05ba266c6da7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Locker?= Date: Wed, 22 May 2024 09:22:00 +0200 Subject: [PATCH 116/141] Avoid IndexOutOfBoundsException in lhsUnary (#5956) --- .../java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 7001beed648..485928d6e7a 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 @@ -1087,9 +1087,10 @@ public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { .build(); children.forEach(andDescr::addDescr); return andDescr; - } else { - // size == 1. children never be empty + } else if (children.size() == 1) { return children.get(0); + } else { + return null; // only caused by a parser error } } From 12edf718e0d433ad7aacaecc961fb5208c31cc9a Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 22 May 2024 16:24:28 +0900 Subject: [PATCH 117/141] =?UTF-8?q?[incubator-kie-drools-5909]=20[new-pars?= =?UTF-8?q?er]=20Accumulate=20parsed=20incorrectl=E2=80=A6=20(#5965)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5909] [new-parser] Accumulate parsed incorrectly if init and action statements are empty * Update drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java Co-authored-by: Jiří Locker --------- Co-authored-by: Jiří Locker --- .../drl/parser/antlr4/MiscDRLParserTest.java | 20 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- .../antlr4/Antlr4ParserStringUtils.java | 3 +++ .../drl/parser/antlr4/DRLVisitorImpl.java | 2 +- 4 files changed, 25 insertions(+), 2 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 85c8423ba89..ca565a83209 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 @@ -5122,4 +5122,24 @@ void javaKeywordsInPackage(String keyword) { assertThat(pkg.getRules().get(0).getName()).isEqualTo("R"); } + + @Test + void accumulateEmptyChunks() { + String text = "rule R\n" + + "when\n" + + " $totalAmount : Number() from accumulate( Cheese( $price : price ),\n" + + " init( ),\n" + + " action( ),\n" + + " result( null ) );\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accumulateDescr = (AccumulateDescr) outPattern.getSource(); + assertThat(accumulateDescr.getInitCode()).isEmpty(); + assertThat(accumulateDescr.getActionCode()).isEmpty(); + assertThat(accumulateDescr.getReverseCode()).isNull(); + assertThat(accumulateDescr.getResultCode()).isEqualTo( "null"); + } } 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/DRLParser.g4 index da397785c1d..e96aa729aec 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/DRLParser.g4 @@ -340,7 +340,7 @@ fromAccumulate := ACCUMULATE LEFT_PAREN lhsAnd (COMMA|SEMICOLON) ) RIGHT_PAREN */ fromAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) - ( DRL_INIT LPAREN initBlockStatements=chunk RPAREN COMMA? DRL_ACTION LPAREN actionBlockStatements=chunk RPAREN COMMA? ( DRL_REVERSE LPAREN reverseBlockStatements=chunk RPAREN COMMA?)? DRL_RESULT LPAREN expression RPAREN + ( DRL_INIT LPAREN initBlockStatements=chunk? RPAREN COMMA? DRL_ACTION LPAREN actionBlockStatements=chunk? RPAREN COMMA? ( DRL_REVERSE LPAREN reverseBlockStatements=chunk? RPAREN COMMA?)? DRL_RESULT LPAREN resultBlockStatements=chunk RPAREN | accumulateFunction ) RPAREN (SEMI)? diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java index a33eb143dd8..a0f09fb4717 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java @@ -38,6 +38,9 @@ private Antlr4ParserStringUtils() { * Get text from ParserRuleContext's CharStream without trimming whitespace */ public static String getTextPreservingWhitespace(ParserRuleContext ctx) { + if (ctx == null) { + return ""; + } // Using raw CharStream int startIndex = ctx.start.getStartIndex(); int stopIndex = ctx.stop.getStopIndex(); 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 485928d6e7a..ddb3d370fad 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 @@ -798,7 +798,7 @@ public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) if (ctx.DRL_REVERSE() != null) { accumulateDescr.setReverseCode(getTextPreservingWhitespace(ctx.reverseBlockStatements)); } - accumulateDescr.setResultCode(getTextPreservingWhitespace(ctx.expression())); + accumulateDescr.setResultCode(getTextPreservingWhitespace(ctx.resultBlockStatements)); } else { // accumulate function accumulateDescr.addFunction(visitAccumulateFunction(ctx.accumulateFunction())); From 0873f8df73e6c591c5079c474cfd167b73574b22 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 23 May 2024 11:27:42 +0900 Subject: [PATCH 118/141] [incubator-kie-drools-5936] [new-parser] || and && should be allowed as alternatives to infix or and and (#5966) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 78 ++++++++++++++++++- .../org/drools/drl/parser/antlr4/DRLParser.g4 | 10 +-- .../antlr4/Antlr4ParserStringUtils.java | 6 ++ .../drl/parser/antlr4/DRLVisitorImpl.java | 2 +- 4 files changed, 88 insertions(+), 8 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 ca565a83209..e81bfb21f0c 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 @@ -5135,11 +5135,85 @@ void accumulateEmptyChunks() { "end"; RuleDescr rule = parseAndGetFirstRuleDescr(text); - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final AccumulateDescr accumulateDescr = (AccumulateDescr) outPattern.getSource(); assertThat(accumulateDescr.getInitCode()).isEmpty(); assertThat(accumulateDescr.getActionCode()).isEmpty(); assertThat(accumulateDescr.getReverseCode()).isNull(); - assertThat(accumulateDescr.getResultCode()).isEqualTo( "null"); + assertThat(accumulateDescr.getResultCode()).isEqualTo("null"); + } + + @Test + void doublePipeInfixOr() { + final String text = + "rule R\n" + + "when\n" + + " Person()\n" + + " ||\n" + + " Address()\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(OrDescr.class, orDescr -> { + assertThat(orDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + }); + assertThat(orDescr.getDescrs().get(1)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Address"); + }); + }); + } + + @Test + void doubleAmpersandInfixAnd() { + final String text = + "rule R\n" + + "when\n" + + " Person()\n" + + " &&\n" + + " Address()\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + }); + assertThat(rule.getLhs().getDescrs().get(1)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Address"); + }); + } + + @Test + void doubleAmpersandInfixAndInAccumulate() { + final String text = + "rule R\n" + + "when\n" + + " accumulate( FactA($a : value) && FactB($b : value);\n" + + " $avg : average($a + $b))\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + AccumulateDescr accumulateDescr = (AccumulateDescr) outPattern.getSource(); + assertThat(accumulateDescr.getInput()).isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs()).hasSize(2); + assertThat(andDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("FactA"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("$a : value"); + }); + }); + assertThat(andDescr.getDescrs().get(1)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("FactB"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("$b : value"); + }); + }); + }); + + AccumulateDescr.AccumulateFunctionCallDescr accumulateFunction = accumulateDescr.getFunctions().get(0); + assertThat(accumulateFunction.getBind()).isEqualTo("$avg"); + assertThat(accumulateFunction.getFunction()).isEqualTo("average"); + assertThat(accumulateFunction.getParams()).containsExactly("$a + $b"); } } 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/DRLParser.g4 index e96aa729aec..251f73f2508 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/DRLParser.g4 @@ -104,16 +104,16 @@ lhs : DRL_WHEN lhsExpression* ; queryLhs : lhsExpression* ; lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed - | lhsUnary #lhsUnarySingle - | DRL_AND drlAnnotation* lhsExpression+ #lhsAnd - | lhsExpression (DRL_AND drlAnnotation* lhsExpression)+ #lhsAnd | DRL_OR drlAnnotation* lhsExpression+ #lhsOr - | lhsExpression (DRL_OR drlAnnotation* lhsExpression)+ #lhsOr + | lhsExpression ((DRL_OR|OR) drlAnnotation* lhsExpression)+ #lhsOr + | DRL_AND drlAnnotation* lhsExpression+ #lhsAnd + | lhsExpression ((DRL_AND|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 lhsUnary)* + | lhsUnary ((DRL_AND|AND) lhsUnary)* | LPAREN DRL_AND lhsUnary+ RPAREN ; diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java index a0f09fb4717..74fb54c2c4c 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java @@ -56,6 +56,9 @@ public static String getTextPreservingWhitespace(ParserRuleContext ctx) { * Get text from List of ParserRuleContext's CharStream without trimming whitespace */ public static String getTextPreservingWhitespace(List ctx) { + if (ctx == null) { + return ""; + } return ctx.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.joining()); } @@ -65,6 +68,9 @@ public static String getTextPreservingWhitespace(List Date: Mon, 27 May 2024 10:29:29 +0900 Subject: [PATCH 119/141] =?UTF-8?q?[incubator-kie-drools-5938]=20[new-pars?= =?UTF-8?q?er]=20Tests=20using=20wrong=20duration=20a=E2=80=A6=20(#5969)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [incubator-kie-drools-5938] [new-parser] Tests using wrong duration attribute format * - Use explicit test value --- .../drl/parser/antlr4/MiscDRLParserTest.java | 16 ++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- .../drools/drl/parser/antlr4/DRLVisitorImpl.java | 15 --------------- 3 files changed, 17 insertions(+), 16 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 e81bfb21f0c..ab2f7070606 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 @@ -5216,4 +5216,20 @@ void doubleAmpersandInfixAndInAccumulate() { assertThat(accumulateFunction.getFunction()).isEqualTo("average"); assertThat(accumulateFunction.getParams()).containsExactly("$a + $b"); } + + @Test + void durationChunk() { + final String text = + "rule R\n" + + " duration (wrong input) \n" + + "when\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getAttributes()).containsKey("duration"); + assertThat(rule.getAttributes().get("duration").getType()).isEqualTo(AttributeDescr.Type.EXPRESSION); + + // At the moment, the parser accepts any input and let the compile phase validate it. + assertThat(rule.getAttributes().get("duration").getValue()).isEqualTo("wrong input"); + } } 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/DRLParser.g4 index 251f73f2508..cf1afb97862 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/DRLParser.g4 @@ -445,7 +445,7 @@ attribute : name=( 'salience' | 'enabled' ) conditionalAttributeValue #expressio | name=( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) DRL_STRING_LITERAL #stringAttribute | name='calendars' DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* #stringListAttribute | name='timer' ( DECIMAL_LITERAL | LPAREN chunk RPAREN ) #intOrChunkAttribute - | name='duration' ( DECIMAL_LITERAL | TIME_INTERVAL | LPAREN TIME_INTERVAL RPAREN ) #durationAttribute + | name='duration' ( DECIMAL_LITERAL | LPAREN chunk RPAREN ) #intOrChunkAttribute ; conditionalAttributeValue : ( LPAREN conditionalExpression RPAREN | conditionalExpression ) ; 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 4e6192ecad6..39aa5e930e8 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 @@ -514,21 +514,6 @@ public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeCont return attributeDescr; } - @Override - public AttributeDescr visitDurationAttribute(DRLParser.DurationAttributeContext ctx) { - AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) - .withParserRuleContext(ctx) - .build(); - if (ctx.DECIMAL_LITERAL() != null) { - attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); - attributeDescr.setType(AttributeDescr.Type.NUMBER); - } else { - attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.TIME_INTERVAL().getText()))); - attributeDescr.setType(AttributeDescr.Type.EXPRESSION); - } - return attributeDescr; - } - /** * entry point for LHS */ From 840ab031b1939511b3f3a5f639bbfadbcd2c05e1 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 3 Jun 2024 16:20:54 +0900 Subject: [PATCH 120/141] [incubator-kie-drools-5948] [new-parser] Broken testIncompatibleListOnAccumulateFunction (#5975) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 82 +++++++++++++++++-- .../{accumulate.drl => from_accumulate.drl} | 0 .../org/drools/drl/parser/antlr4/DRLParser.g4 | 3 +- .../drl/parser/antlr4/DRLVisitorImpl.java | 18 +++- 4 files changed, 95 insertions(+), 8 deletions(-) rename drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/{accumulate.drl => from_accumulate.drl} (100%) 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 ab2f7070606..875315157d1 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 @@ -2174,12 +2174,44 @@ public void parse_QualifiedClassname() throws Exception { } @Test - public void parse_Accumulate() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulate.drl" ); + void accumulate() { + final String drl = "rule R\n" + + "when\n" + + " accumulate( Person( $age : age );\n" + + " $avg : average( $age ) );\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(drl); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions.size()).isEqualTo(1); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$avg"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$age"); + + final PatternDescr pattern = accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + + // accum.getInput() is always AndDescr + assertThat(accum.getInput()).isInstanceOfSatisfying(AndDescr.class, and -> { + assertThat(and.getDescrs()).hasSize(1); + assertThat(and.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + }); + }); + } + + @Test + void fromAccumulate() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile("from_accumulate.drl" ); assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + final RuleDescr rule = pkg.getRules().get( 0 ); assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); @@ -2191,8 +2223,16 @@ public void parse_Accumulate() throws Exception { assertThat(accum.isExternalFunction()).isFalse(); - final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + final PatternDescr pattern = accum.getInputPattern(); assertThat(pattern.getObjectType()).isEqualTo("Person"); + + // accum.getInput() is always AndDescr + assertThat(accum.getInput()).isInstanceOfSatisfying(AndDescr.class, and -> { + assertThat(and.getDescrs()).hasSize(1); + assertThat(and.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + }); + }); } @Test @@ -5232,4 +5272,36 @@ void durationChunk() { // At the moment, the parser accepts any input and let the compile phase validate it. assertThat(rule.getAttributes().get("duration").getValue()).isEqualTo("wrong input"); } + + @Test + void accumulateWithEmptyActionAndReverse() { + final String drl = "rule R when\n" + + " Number() from accumulate( Number(),\n" + + " init( double total = 0; ),\n" + + " action( ),\n" + + " reverse( ),\n" + + " result( new Double( total ) )\n" + + " )\n" + + "then end"; + RuleDescr rule = parseAndGetFirstRuleDescr(drl); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(accum.getInitCode()).isEqualTo( "double total = 0;"); + assertThat(accum.getActionCode()).isEmpty(); + assertThat(accum.getReverseCode()).isEmpty(); + assertThat(accum.getResultCode()).isEqualTo( "new Double( total )"); + + assertThat(accum.isExternalFunction()).isFalse(); + + final PatternDescr pattern = accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Number"); + + assertThat(accum.getInput()).isInstanceOfSatisfying(AndDescr.class, and -> { + assertThat(and.getDescrs()).hasSize(1); + assertThat(and.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Number"); + }); + }); + } } diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/from_accumulate.drl similarity index 100% rename from drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate.drl rename to drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/from_accumulate.drl 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/DRLParser.g4 index cf1afb97862..cabdaaa1f34 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/DRLParser.g4 @@ -340,7 +340,8 @@ fromAccumulate := ACCUMULATE LEFT_PAREN lhsAnd (COMMA|SEMICOLON) ) RIGHT_PAREN */ fromAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) - ( DRL_INIT LPAREN initBlockStatements=chunk? RPAREN COMMA? DRL_ACTION LPAREN actionBlockStatements=chunk? RPAREN COMMA? ( DRL_REVERSE LPAREN reverseBlockStatements=chunk? RPAREN COMMA?)? DRL_RESULT LPAREN resultBlockStatements=chunk RPAREN + ( DRL_INIT LPAREN initBlockStatements=chunk? RPAREN COMMA? DRL_ACTION LPAREN actionBlockStatements=chunk? RPAREN COMMA? DRL_REVERSE LPAREN reverseBlockStatements=chunk? RPAREN COMMA? DRL_RESULT LPAREN resultBlockStatements=chunk RPAREN + | DRL_INIT LPAREN initBlockStatements=chunk? RPAREN COMMA? DRL_ACTION LPAREN actionBlockStatements=chunk? RPAREN COMMA? DRL_RESULT LPAREN resultBlockStatements=chunk RPAREN | accumulateFunction ) RPAREN (SEMI)? 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 39aa5e930e8..d67450e9193 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 @@ -699,7 +699,8 @@ public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { AccumulateDescr accumulateDescr = BaseDescrFactory.builder(new AccumulateDescr()) .withParserRuleContext(ctx) .build(); - accumulateDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); + // accumulateDescr.input is always AndDescr + accumulateDescr.setInput(wrapWithAndDescr(visitLhsAndDef(ctx.lhsAndDef()), ctx.lhsAndDef())); // accumulate function for (DRLParser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { @@ -714,6 +715,18 @@ public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { return patternDescr; } + private AndDescr wrapWithAndDescr(BaseDescr baseDescr, ParserRuleContext ctx) { + if (baseDescr instanceof AndDescr andDescr) { + return andDescr; + } else { + AndDescr andDescr = BaseDescrFactory.builder(new AndDescr()) + .withParserRuleContext(ctx) + .build(); + andDescr.addDescr(baseDescr); + return andDescr; + } + } + @Override public Object visitLhsGroupBy(DRLParser.LhsGroupByContext ctx) { GroupByDescr groupByDescr = BaseDescrFactory.builder(new GroupByDescr()) @@ -775,7 +788,8 @@ public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) AccumulateDescr accumulateDescr = BaseDescrFactory.builder(new AccumulateDescr()) .withParserRuleContext(ctx) .build(); - accumulateDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); + // accumulateDescr.input is always AndDescr + accumulateDescr.setInput(wrapWithAndDescr(visitLhsAndDef(ctx.lhsAndDef()), ctx.lhsAndDef())); if (ctx.DRL_INIT() != null) { // inline custom accumulate accumulateDescr.setInitCode(getTextPreservingWhitespace(ctx.initBlockStatements)); From f65e262877ca766185b34a4d30c21e7ed7bcf27e Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 4 Jun 2024 15:41:48 +0900 Subject: [PATCH 121/141] [incubator-kie-drools-5932] [new-parser] Anonymous classes not supported (#5979) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 23 +++++++++++++++++++ .../drl/parser/antlr4/DRL6Expressions.g4 | 6 ++--- .../drl/parser/antlr4/DRLVisitorImpl.java | 2 +- 3 files changed, 27 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 875315157d1..d3a919d0c48 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 @@ -5304,4 +5304,27 @@ void accumulateWithEmptyActionAndReverse() { }); }); } + + @Test + void functionWithAnonymousClass() { + final String text = "function Function f() {\n" + + " return new Function() {\n" + + " public Integer apply(String s) {\n" + + " return s.length();\n" + + " }\n" + + " };\n" + + "}"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + FunctionDescr function = packageDescr.getFunctions().get(0); + + assertThat(function.getName()).isEqualTo("f"); + assertThat(function.getReturnType()).isEqualToIgnoringWhitespace("Function"); + assertThat(function.getParameterTypes()).isEmpty(); + assertThat(function.getParameterNames()).isEmpty(); + assertThat(function.getBody()).isEqualToIgnoringWhitespace("return new Function() {\n" + + " public Integer apply(String s) {\n" + + " return s.length();\n" + + " }\n" + + " };"); + } } 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/DRL6Expressions.g4 index f2a5a79f195..026beef4cea 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/DRL6Expressions.g4 @@ -810,7 +810,7 @@ identifierSuffix creator : nonWildcardTypeArguments? createdName - (arrayCreatorRest | classCreatorRest) + (arrayCreatorRest | classCreatorRestExpr) ; createdName @@ -821,7 +821,7 @@ createdName // Old parser cannot parse innerCreator with selector expression (outer.new InnerClass() != null) TODO: Delete this after investigation innerCreator - : {!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? drlIdentifier classCreatorRest + : {!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? drlIdentifier classCreatorRestExpr ; arrayCreatorRest @@ -840,7 +840,7 @@ arrayInitializer : LBRACE (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RBRACE ; -classCreatorRest +classCreatorRestExpr // do not overwrite JavaParser.g4 classCreatorRest : arguments //classBody? //sotty: restored classBody to allow for inline, anonymous classes ; 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 d67450e9193..cefce9921c1 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 @@ -207,7 +207,7 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { .withParserRuleContext(ctx) .build(); if (ctx.typeTypeOrVoid() != null) { - functionDescr.setReturnType(ctx.typeTypeOrVoid().getText()); + functionDescr.setReturnType(getTextPreservingWhitespace(ctx.typeTypeOrVoid())); } else { functionDescr.setReturnType("void"); } From aec972dde50e58b60fe16ad445411133d8fc1082 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 4 Jun 2024 16:14:33 +0900 Subject: [PATCH 122/141] [incubator-kie-drools-5920] [new-parser] Strict annotation parsing (#5976) - Skip the test for new parser --- .../mvel/integrationtests/StrictAnnotationTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/StrictAnnotationTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/StrictAnnotationTest.java index cc3a605be16..602b8ead083 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/StrictAnnotationTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/StrictAnnotationTest.java @@ -32,10 +32,13 @@ import org.drools.core.common.DefaultEventHandle; import org.drools.core.impl.RuleBaseFactory; +import org.drools.drl.parser.DrlParser; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; import org.drools.testcoverage.common.util.TestParametersUtil; +import org.junit.Assume; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -70,6 +73,12 @@ public static Collection getParameters() { return TestParametersUtil.getKieBaseCloudConfigurations(false); } + @BeforeClass + public static void checkSkip() { + // if new antlr4 parser is enabled, skip this test, because DRL6_STRICT is not supported + Assume.assumeFalse(DrlParser.ANTLR4_PARSER_ENABLED); + } + @Test public void testUnknownAnnotation() { String str = From ca734657ffad53d8da958680289934918f0ed0aa Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 4 Jun 2024 17:29:23 +0900 Subject: [PATCH 123/141] [incubator-kie-drools-5911] [new-parser] Support optional type keyword for backward compatibility (#5977) --- .../drools/drl/parser/antlr4/MiscDRLParserTest.java | 13 +++++++++++++ .../org/drools/drl/parser/antlr4/DRL6Expressions.g4 | 1 + .../antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 | 1 + .../org/drools/drl/parser/antlr4/DRLParser.g4 | 2 +- 4 files changed, 16 insertions(+), 1 deletion(-) 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 d3a919d0c48..7057579d8d8 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 @@ -5327,4 +5327,17 @@ void functionWithAnonymousClass() { " }\n" + " };"); } + + @Test + void typeDeclarationWithTypeToken() { + final String drl = "declare type Foo\n" + // "type" is just optional + " id : int\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(drl); + + TypeDeclarationDescr typeDeclarationDescr = pkg.getTypeDeclarations().get(0); + assertThat(typeDeclarationDescr.getTypeName()).isEqualTo("Foo"); + TypeFieldDescr typeFieldDescr = typeDeclarationDescr.getFields().get("id"); + assertThat(typeFieldDescr.getPattern().getObjectType()).isEqualTo("int"); + } } 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/DRL6Expressions.g4 index 026beef4cea..9819713fbb5 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/DRL6Expressions.g4 @@ -241,6 +241,7 @@ drlKeywords returns [Token token] | DRL_GLOBAL | DRL_DECLARE | DRL_TRAIT + | DRL_TYPE | DRL_RULE | DRL_QUERY | DRL_WHEN 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/DRLLexer.g4 index 5809147d651..198dfccfc2a 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/DRLLexer.g4 @@ -36,6 +36,7 @@ DRL_FUNCTION : 'function'; DRL_GLOBAL : 'global'; DRL_DECLARE : 'declare'; DRL_TRAIT : 'trait'; +DRL_TYPE : 'type'; DRL_RULE : 'rule'; DRL_QUERY : 'query'; DRL_WHEN : 'when'; 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/DRLParser.g4 index cabdaaa1f34..40b3bc66596 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/DRLParser.g4 @@ -61,7 +61,7 @@ declaredef : DRL_DECLARE ( * END */ -typeDeclaration : DRL_TRAIT? name=drlQualifiedName (EXTENDS superTypes+=drlQualifiedName (COMMA superTypes+=drlQualifiedName)* )? drlAnnotation* field* DRL_END ; +typeDeclaration : DRL_TRAIT? DRL_TYPE? name=drlQualifiedName (EXTENDS superTypes+=drlQualifiedName (COMMA superTypes+=drlQualifiedName)* )? drlAnnotation* field* DRL_END ; // entryPointDeclaration := ENTRY-POINT stringId annotation* END From 6ca467111f2c81890de3671072ae287280fcdf0b Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 7 Jun 2024 15:23:28 +0900 Subject: [PATCH 124/141] [incubator-kie-drools-5980-DSL] [new-parser] Enable DSL tests (#5981) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 126 +++++++++--------- 1 file changed, 60 insertions(+), 66 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 7057579d8d8..92df973dda8 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 @@ -20,6 +20,7 @@ import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; @@ -131,6 +132,17 @@ private PackageDescr parseAndGetPackageDescrWithoutErrorCheck(String drl) { } } + private PackageDescr parseAndGetPackageDescrWithDsl(String dslrFileName, String dslFileName) { + try (InputStreamReader dslr = new InputStreamReader(getClass().getResourceAsStream(dslrFileName)); + InputStreamReader dsl = new InputStreamReader(getClass().getResourceAsStream(dslFileName))) { + PackageDescr pkg = parser.parse(dslr, dsl); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + return pkg; + } catch (DroolsParserException | IOException e) { + throw new RuntimeException(e); + } + } + private RuleDescr parseAndGetFirstRuleDescr(String drl) { PackageDescr pkg = parseAndGetPackageDescr(drl); assertThat(pkg.getRules()).isNotEmpty(); @@ -1161,73 +1173,55 @@ public void parse_MultipleRules() throws Exception { assertThat(first.getObjectType()).isEqualTo("Cheese"); } - @Disabled("Priority : low | Not yet support DSL") - @Test - public void parse_ExpanderLineSpread() throws Exception { -// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); -// final PackageDescr pkg = parser.parse( this.getReader( "expander_spread_lines.dslr" ), -// this.getReader( "complex.dsl" ) ); -// -// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); -// -// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); -// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); -// -// final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); -// assertThat(or.getDescrs().size()).isEqualTo(2); -// assertThat( (String) rule.getConsequence() ).isNotNull(); - - } - - @Disabled("Priority : low | Not yet support DSL") - @Test - public void parse_ExpanderMultipleConstraints() throws Exception { -// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); -// final PackageDescr pkg = parser.parse( this.getReader( "expander_multiple_constraints.dslr" ), -// this.getReader( "multiple_constraints.dsl" ) ); -// -// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); -// -// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); -// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); -// -// PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); -// assertThat(pattern.getObjectType()).isEqualTo("Person"); -// -// assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); -// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); -// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); -// -// pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); -// assertThat(pattern.getObjectType()).isEqualTo("Bar"); -// -// assertThat( (String) rule.getConsequence() ).isNotNull(); - - } - - @Disabled("Priority : low | Not yet support DSL") - @Test - public void parse_ExpanderMultipleConstraintsFlush() throws Exception { -// final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); -// // this is similar to the other test, but it requires a flush to add the -// // constraints -// final PackageDescr pkg = parser.parse( this.getReader( "expander_multiple_constraints_flush.dslr" ), -// this.getReader( "multiple_constraints.dsl" ) ); -// -// assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); -// -// final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); -// assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); -// -// final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); -// assertThat(pattern.getObjectType()).isEqualTo("Person"); -// -// assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); -// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); -// assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); -// -// assertThat( (String) rule.getConsequence() ).isNotNull(); + @Test + public void parse_ExpanderLineSpread() { + final PackageDescr pkg = parseAndGetPackageDescrWithDsl("expander_spread_lines.dslr", "complex.dsl"); + + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertThat(or.getDescrs().size()).isEqualTo(2); + assertThat((String) rule.getConsequence()).isNotNull(); + } + + @Test + public void parse_ExpanderMultipleConstraints() { + final PackageDescr pkg = parseAndGetPackageDescrWithDsl("expander_multiple_constraints.dslr", "multiple_constraints.dsl"); + + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); + assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); + assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); + + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(pattern.getObjectType()).isEqualTo("Bar"); + + assertThat((String) rule.getConsequence()).isNotNull(); + } + + @Test + public void parse_ExpanderMultipleConstraintsFlush() { + // this is similar to the other test, but it requires a flush to add the + // constraints + final PackageDescr pkg = parseAndGetPackageDescrWithDsl("expander_multiple_constraints_flush.dslr", "multiple_constraints.dsl"); + + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + + assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); + assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); + assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); + assertThat((String) rule.getConsequence()).isNotNull(); } @Test From 3940d11f8bd5421ae28523e689a4f074ac48d0ae Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 7 Jun 2024 15:23:37 +0900 Subject: [PATCH 125/141] [incubator-kie-drools-5982] [new-parser] Enable alternative attributes test (#5983) --- .../drl/parser/antlr4/MiscDRLParserTest.java | 15 +++++++-------- .../drools/drl/parser/antlr4/DRL6Expressions.g4 | 1 + .../org/drools/drl/parser/antlr4/DRLLexer.g4 | 1 + .../org/drools/drl/parser/antlr4/DRLParser.g4 | 15 ++++++++------- 4 files changed, 17 insertions(+), 15 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 92df973dda8..4769ce9f3ba 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 @@ -1964,9 +1964,8 @@ public void parse_Timer() throws Exception { assertThat(at.getValue()).isEqualTo("true"); } - @Disabled("Priority : Low | Not written in docs nor other unit tests. Drop the support?") @Test - public void parse_Attributes_alternateSyntax() throws Exception { + public void parse_Attributes_alternateSyntax() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( "rule_attributes_alt.drl" ); assertThat(rule.getName()).isEqualTo("simple_rule"); @@ -1975,27 +1974,27 @@ public void parse_Attributes_alternateSyntax() throws Exception { final Map attrs = rule.getAttributes(); assertThat(attrs.size()).isEqualTo(6); - AttributeDescr at = (AttributeDescr) attrs.get( "salience" ); + AttributeDescr at = attrs.get( "salience" ); assertThat(at.getName()).isEqualTo("salience"); assertThat(at.getValue()).isEqualTo("42"); - at = (AttributeDescr) attrs.get( "agenda-group" ); + at = attrs.get( "agenda-group" ); assertThat(at.getName()).isEqualTo("agenda-group"); assertThat(at.getValue()).isEqualTo("my_group"); - at = (AttributeDescr) attrs.get( "no-loop" ); + at = attrs.get( "no-loop" ); assertThat(at.getName()).isEqualTo("no-loop"); assertThat(at.getValue()).isEqualTo("true"); - at = (AttributeDescr) attrs.get( "lock-on-active" ); + at = attrs.get( "lock-on-active" ); assertThat(at.getName()).isEqualTo("lock-on-active"); assertThat(at.getValue()).isEqualTo("true"); - at = (AttributeDescr) attrs.get( "duration" ); + at = attrs.get( "duration" ); assertThat(at.getName()).isEqualTo("duration"); assertThat(at.getValue()).isEqualTo("42"); - at = (AttributeDescr) attrs.get( "activation-group" ); + at = attrs.get( "activation-group" ); assertThat(at.getName()).isEqualTo("activation-group"); assertThat(at.getValue()).isEqualTo("my_activation_group"); } 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/DRL6Expressions.g4 index 9819713fbb5..2efe8b1ec8e 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/DRL6Expressions.g4 @@ -264,6 +264,7 @@ drlKeywords returns [Token token] | DRL_EVAL | DRL_FORALL | DRL_OVER + | DRL_ATTRIBUTES | DRL_SALIENCE | DRL_ENABLED | DRL_NO_LOOP 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/DRLLexer.g4 index 198dfccfc2a..2a433de8b06 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/DRLLexer.g4 @@ -89,6 +89,7 @@ DRL_STARTED_BY : 'startedby'; DRL_WINDOW : 'window'; // attributes +DRL_ATTRIBUTES : 'attributes'; DRL_SALIENCE : 'salience'; DRL_ENABLED : 'enabled'; DRL_NO_LOOP : 'no-loop'; 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/DRLParser.g4 index 40b3bc66596..c1e399fd01c 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/DRLParser.g4 @@ -440,13 +440,14 @@ drlAnnotation : {boolean buildState = buildDescr; buildDescr = true;} anno=fullAnnotation[null] {buildDescr = buildState;} // either standard Java annotation | AT name=drlQualifiedName (LPAREN chunk RPAREN)? ; // or support @watch(!*, age) etc. -attributes : attribute ( COMMA? attribute )* ; -attribute : name=( 'salience' | 'enabled' ) conditionalAttributeValue #expressionAttribute - | name=( 'no-loop' | 'auto-focus' | 'lock-on-active' | 'refract' | 'direct' ) BOOL_LITERAL? #booleanAttribute - | name=( 'agenda-group' | 'activation-group' | 'ruleflow-group' | 'date-effective' | 'date-expires' | 'dialect' ) DRL_STRING_LITERAL #stringAttribute - | name='calendars' DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* #stringListAttribute - | name='timer' ( DECIMAL_LITERAL | LPAREN chunk RPAREN ) #intOrChunkAttribute - | name='duration' ( DECIMAL_LITERAL | LPAREN chunk RPAREN ) #intOrChunkAttribute +// attributes := (ATTRIBUTES COLON?)? [ attribute ( COMMA? attribute )* ] +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_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 ; conditionalAttributeValue : ( LPAREN conditionalExpression RPAREN | conditionalExpression ) ; From f5055e5716268595030ee67d0220ded97e960ff0 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 7 Jun 2024 15:23:45 +0900 Subject: [PATCH 126/141] [incubator-kie-drools-5933] [new-parser] PackageDescr.resource not set (#5984) --- .../antlr4/DescrCommonPropertyTest.java | 17 +++- .../java/org/drools/drl/parser/DrlParser.java | 2 +- .../drl/parser/antlr4/BaseDescrFactory.java | 6 ++ .../drl/parser/antlr4/DRLParserHelper.java | 7 +- .../drl/parser/antlr4/DRLParserWrapper.java | 9 ++- .../drl/parser/antlr4/DRLVisitorImpl.java | 77 ++++++++++++++++--- 6 files changed, 100 insertions(+), 18 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 25c51ca9b7f..0582c9faf5e 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 @@ -18,6 +18,11 @@ */ package org.drools.drl.parser.antlr4; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + import org.drools.drl.ast.descr.AccumulateDescr; import org.drools.drl.ast.descr.AccumulateImportDescr; import org.drools.drl.ast.descr.AndDescr; @@ -49,8 +54,10 @@ import org.drools.drl.ast.descr.WindowReferenceDescr; import org.drools.drl.parser.DrlParser; import org.drools.drl.parser.DroolsParserException; +import org.drools.io.InputStreamResource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.kie.api.io.Resource; import static org.assertj.core.api.Assertions.assertThat; @@ -61,17 +68,20 @@ class DescrCommonPropertyTest { private DrlParser parser; + private Resource resource; + @BeforeEach public void setUp() { parser = ParserTestUtils.getParser(); } private PackageDescr parseAndGetPackageDescr(String drl) { - try { - PackageDescr pkg = parser.parse(null, drl); + try (InputStream inputStream = new ByteArrayInputStream(drl.getBytes(StandardCharsets.UTF_8))) { + resource = new InputStreamResource(inputStream); + PackageDescr pkg = parser.parse(resource); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); return pkg; - } catch (DroolsParserException e) { + } catch (DroolsParserException | IOException e) { throw new RuntimeException(e); } } @@ -83,6 +93,7 @@ private void assertProperties(BaseDescr descr, int startCharacter, int endCharac assertThat(descr.getColumn()).isEqualTo(column); // first column of the start token. column is 0-based assertThat(descr.getEndLine()).isEqualTo(endLine); // line of the end token. line is 1-based assertThat(descr.getEndColumn()).isEqualTo(endColumn); // last column of the end token. column is 0-based + assertThat(descr.getResource()).isEqualTo(resource); } @Test 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 26ee6dffb7b..398e5f49923 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 @@ -200,7 +200,7 @@ public PackageDescr parse(final boolean isEditor, private PackageDescr compileWithAntlr4Parser(Function packageDescrFunction) throws DroolsParserException { try { // we don't use languageLevel here, assuming DRL6 compatible - DRLParserWrapper parser = new DRLParserWrapper(); + DRLParserWrapper parser = new DRLParserWrapper(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/BaseDescrFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/BaseDescrFactory.java index 31fe45747e3..f48db5926b8 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/BaseDescrFactory.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/BaseDescrFactory.java @@ -20,6 +20,7 @@ import org.antlr.v4.runtime.ParserRuleContext; import org.drools.drl.ast.descr.BaseDescr; +import org.kie.api.io.Resource; import static org.drools.drl.parser.antlr4.DescrHelper.populateCommonProperties; @@ -53,6 +54,11 @@ public Builder withParserRuleContext(ParserRuleContext ctx) { return this; } + public Builder withResource(Resource resource) { + toReturn.setResource(resource); + return this; + } + public T build() { return toReturn; } 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/DRLParserHelper.java index 7d945f6bb8b..131145b2d75 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/DRLParserHelper.java @@ -33,6 +33,7 @@ import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.drools.drl.ast.descr.PackageDescr; +import org.kie.api.io.Resource; import org.kie.internal.builder.conf.LanguageLevelOption; /** @@ -49,7 +50,7 @@ private DRLParserHelper() { */ public static PackageDescr parse(String drl) { DRLParser drlParser = createDrlParser(drl); - return compilationUnitContext2PackageDescr(drlParser.compilationUnit(), drlParser.getTokenStream()); + return compilationUnitContext2PackageDescr(drlParser.compilationUnit(), drlParser.getTokenStream(), null); } public static DRLParser createDrlParser(String drl) { @@ -89,8 +90,8 @@ private static DRLParser createDrlParser(CharStream charStream) { /** * DRLVisitorImpl visits a parse tree and creates a PackageDescr */ - public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.CompilationUnitContext ctx, TokenStream tokenStream) { - DRLVisitorImpl visitor = new DRLVisitorImpl(tokenStream); + public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.CompilationUnitContext ctx, TokenStream tokenStream, Resource resource) { + DRLVisitorImpl visitor = new DRLVisitorImpl(tokenStream, resource); Object descr = visitor.visit(ctx); if (descr instanceof PackageDescr) { return (PackageDescr) descr; 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/DRLParserWrapper.java index e2f8ee99604..e89ad669197 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/DRLParserWrapper.java @@ -25,6 +25,7 @@ import java.util.stream.Collectors; import org.drools.drl.ast.descr.PackageDescr; +import org.kie.api.io.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,6 +40,12 @@ public class DRLParserWrapper { private final List errors = new ArrayList<>(); + private final Resource resource; + + public DRLParserWrapper(Resource resource) { + this.resource = resource; + } + /** * Main entry point for parsing DRL */ @@ -72,7 +79,7 @@ private PackageDescr parse(DRLParser drlParser) { errors.addAll(errorListener.getErrors()); try { - return compilationUnitContext2PackageDescr(cxt, drlParser.getTokenStream()); + return compilationUnitContext2PackageDescr(cxt, drlParser.getTokenStream(), resource); } catch (Exception e) { LOGGER.error("Exception while creating PackageDescr", e); errors.add(new DRLParserError(e)); 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 cefce9921c1..47d1b40bf9b 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 @@ -65,6 +65,7 @@ import org.drools.drl.ast.descr.UnitDescr; import org.drools.drl.ast.descr.WindowDeclarationDescr; import org.drools.drl.ast.descr.WindowReferenceDescr; +import org.kie.api.io.Resource; import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.extractNamedConsequenceName; import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.getTextPreservingWhitespace; @@ -83,9 +84,11 @@ public class DRLVisitorImpl extends DRLParserBaseVisitor { private final TokenStream tokenStream; + private final Resource resource; - public DRLVisitorImpl(TokenStream tokenStream) { + public DRLVisitorImpl(TokenStream tokenStream, Resource resource) { this.tokenStream = tokenStream; + this.resource = resource; } /** @@ -95,6 +98,7 @@ public DRLVisitorImpl(TokenStream tokenStream) { public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { PackageDescr packageDescr = BaseDescrFactory.builder(new PackageDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); if (ctx.packagedef() != null) { packageDescr.setName(getTextWithoutErrorNode(ctx.packagedef().name)); @@ -158,6 +162,7 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc public UnitDescr visitUnitdef(DRLParser.UnitdefContext ctx) { return BaseDescrFactory.builder(new UnitDescr(ctx.name.getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); } @@ -170,6 +175,7 @@ public BaseDescr visitDrlStatementdef(DRLParser.DrlStatementdefContext ctx) { public GlobalDescr visitGlobaldef(DRLParser.GlobaldefContext ctx) { return BaseDescrFactory.builder(new GlobalDescr(ctx.drlIdentifier().getText(), ctx.type().getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); } @@ -179,12 +185,14 @@ public ImportDescr visitImportStandardDef(DRLParser.ImportStandardDefContext ctx if (ctx.DRL_FUNCTION() != null || ctx.STATIC() != null) { FunctionImportDescr functionImportDescr = BaseDescrFactory.builder(new FunctionImportDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); functionImportDescr.setTarget(target); return functionImportDescr; } else { ImportDescr importDescr = BaseDescrFactory.builder(new ImportDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); importDescr.setTarget(target); return importDescr; @@ -195,6 +203,7 @@ public ImportDescr visitImportStandardDef(DRLParser.ImportStandardDefContext ctx public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulateDefContext ctx) { AccumulateImportDescr accumulateImportDescr = BaseDescrFactory.builder(new AccumulateImportDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); accumulateImportDescr.setTarget(ctx.drlQualifiedName().getText()); accumulateImportDescr.setFunctionName(ctx.drlIdentifier().getText()); @@ -205,6 +214,7 @@ public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulate public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { FunctionDescr functionDescr = BaseDescrFactory.builder(new FunctionDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); if (ctx.typeTypeOrVoid() != null) { functionDescr.setReturnType(getTextPreservingWhitespace(ctx.typeTypeOrVoid())); @@ -237,6 +247,7 @@ public BaseDescr visitDeclaredef(DRLParser.DeclaredefContext ctx) { public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContext ctx) { TypeDeclarationDescr typeDeclarationDescr = BaseDescrFactory.builder(new TypeDeclarationDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); typeDeclarationDescr.setTypeName(ctx.name.getText()); @@ -262,6 +273,7 @@ public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContex public EnumDeclarationDescr visitEnumDeclaration(DRLParser.EnumDeclarationContext ctx) { EnumDeclarationDescr enumDeclarationDescr = BaseDescrFactory.builder(new EnumDeclarationDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); enumDeclarationDescr.setTypeName(ctx.name.getText()); @@ -286,6 +298,7 @@ public EnumDeclarationDescr visitEnumDeclaration(DRLParser.EnumDeclarationContex public EnumLiteralDescr visitEnumerative(DRLParser.EnumerativeContext ctx) { EnumLiteralDescr enumLiteralDescr = BaseDescrFactory.builder(new EnumLiteralDescr(ctx.drlIdentifier().getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); ctx.expression().stream() .map(Antlr4ParserStringUtils::getTextPreservingWhitespace) @@ -297,6 +310,7 @@ public EnumLiteralDescr visitEnumerative(DRLParser.EnumerativeContext ctx) { public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPointDeclarationContext ctx) { EntryPointDeclarationDescr entryPointDeclarationDescr = BaseDescrFactory.builder(new EntryPointDeclarationDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); entryPointDeclarationDescr.setEntryPointId(safeStripStringDelimiters(ctx.name.getText())); ctx.drlAnnotation().stream() @@ -309,6 +323,7 @@ public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPoin public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclarationContext ctx) { WindowDeclarationDescr windowDeclarationDescr = BaseDescrFactory.builder(new WindowDeclarationDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); windowDeclarationDescr.setName(ctx.name.getText()); ctx.drlAnnotation().stream() @@ -325,6 +340,7 @@ public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclaration public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { RuleDescr ruleDescr = BaseDescrFactory.builder(new RuleDescr(safeStripStringDelimiters(ctx.name.getText()))) .withParserRuleContext(ctx) + .withResource(resource) .build(); if (ctx.EXTENDS() != null) { @@ -359,7 +375,9 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { lhsDescrList.forEach(rootDescr::addOrMerge); DescrHelper.populateCommonProperties(rootDescr, ctx.lhs().lhsExpression()); } else { - ruleDescr.setLhs(new AndDescr()); + ruleDescr.setLhs(BaseDescrFactory.builder(new AndDescr()) + .withResource(resource) + .build()); } if (ctx.rhs() != null) { @@ -383,6 +401,7 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { QueryDescr queryDescr = BaseDescrFactory.builder(new QueryDescr(safeStripStringDelimiters(ctx.name.getText()))) .withParserRuleContext(ctx) + .withResource(resource) .build(); DRLParser.ParametersContext parametersContext = ctx.parameters(); @@ -414,12 +433,14 @@ public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { } return BaseDescrFactory.builder(ctx.anno.result) .withParserRuleContext(ctx) + .withResource(resource) .build(); } // A chunk that is neither a single value nor a list of key-value pairs. For example `!*, age` in `@watch(!*, age)`. AnnotationDescr annotationDescr = BaseDescrFactory.builder(new AnnotationDescr(ctx.name.getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); if (ctx.chunk() != null) { annotationDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); @@ -431,6 +452,7 @@ public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { TypeFieldDescr typeFieldDescr = BaseDescrFactory.builder(new TypeFieldDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); typeFieldDescr.setFieldName(ctx.label().drlIdentifier().getText()); typeFieldDescr.setPattern(new PatternDescr(ctx.type().getText())); @@ -447,6 +469,7 @@ public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); attributeDescr.setValue(getTextPreservingWhitespace(ctx.conditionalAttributeValue())); attributeDescr.setType(AttributeDescr.Type.EXPRESSION); @@ -457,6 +480,7 @@ public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeCont public AttributeDescr visitBooleanAttribute(DRLParser.BooleanAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); attributeDescr.setValue(ctx.BOOL_LITERAL() != null ? ctx.BOOL_LITERAL().getText() : "true"); attributeDescr.setType(AttributeDescr.Type.BOOLEAN); @@ -467,6 +491,7 @@ public AttributeDescr visitBooleanAttribute(DRLParser.BooleanAttributeContext ct public AttributeDescr visitStringAttribute(DRLParser.StringAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.DRL_STRING_LITERAL().getText()))); attributeDescr.setType(AttributeDescr.Type.STRING); @@ -477,6 +502,7 @@ public AttributeDescr visitStringAttribute(DRLParser.StringAttributeContext ctx) public AttributeDescr visitStringListAttribute(DRLParser.StringListAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); List valueList = ctx.DRL_STRING_LITERAL().stream() .map(ParseTree::getText) @@ -503,6 +529,7 @@ private static String createStringList(List valueList) { public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); if (ctx.DECIMAL_LITERAL() != null) { attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); @@ -557,6 +584,7 @@ private PatternDescr getSinglePatternDescr(DRLParser.LhsPatternBindContext ctx) private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindContext ctx) { OrDescr orDescr = BaseDescrFactory.builder(new OrDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); List descrList = visitDescrChildren(ctx); descrList.stream() @@ -581,11 +609,13 @@ public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { String constraint = visitConstraintChildren(ctx); ExprConstraintDescr constraintDescr = BaseDescrFactory.builder(new ExprConstraintDescr(constraint)) .withParserRuleContext(ctx) + .withResource(resource) .build(); constraintDescr.setType(ExprConstraintDescr.Type.NAMED); constraintDescr.setPosition(0); PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); patternDescr.addConstraint(constraintDescr); return patternDescr; @@ -593,6 +623,7 @@ public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr(ctx.objectType.getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); if (ctx.QUESTION() != null) { patternDescr.setQuery(true); @@ -621,6 +652,7 @@ private void addToPatternDescr(PatternDescr patternDescr, ExprConstraintDescr ex public NamedConsequenceDescr visitNamedConsequenceInvocation(DRLParser.NamedConsequenceInvocationContext ctx) { NamedConsequenceDescr namedConsequenceDescr = BaseDescrFactory.builder(new NamedConsequenceDescr(ctx.drlIdentifier().getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); return namedConsequenceDescr; } @@ -629,6 +661,7 @@ public NamedConsequenceDescr visitNamedConsequenceInvocation(DRLParser.NamedCons public NamedConsequenceDescr visitBreakingNamedConsequenceInvocation(DRLParser.BreakingNamedConsequenceInvocationContext ctx) { NamedConsequenceDescr namedConsequenceDescr = BaseDescrFactory.builder(new NamedConsequenceDescr(ctx.drlIdentifier().getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); namedConsequenceDescr.setBreaking(true); return namedConsequenceDescr; @@ -645,9 +678,11 @@ public NamedConsequenceDescr visitBreakingNamedConsequenceInvocation(DRLParser.B public ConditionalBranchDescr visitConditionalBranch(DRLParser.ConditionalBranchContext ctx) { ConditionalBranchDescr conditionalBranchDescr = BaseDescrFactory.builder(new ConditionalBranchDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); EvalDescr evalDescr = BaseDescrFactory.builder(new EvalDescr()) .withParserRuleContext(ctx.conditionalOrExpression()) + .withResource(resource) .build(); evalDescr.setContent(getTextPreservingWhitespace(ctx.conditionalOrExpression())); conditionalBranchDescr.setCondition(evalDescr); @@ -665,6 +700,7 @@ public ConditionalBranchDescr visitConditionalBranch(DRLParser.ConditionalBranch if (ctx.do2 != null) { ConditionalBranchDescr elseBranchDescr = BaseDescrFactory.builder(new ConditionalBranchDescr()) .withParserRuleContext(ctx.do2) + .withResource(resource) .build(); conditionalBranchDescr.setElseBranch(elseBranchDescr); NamedConsequenceDescr namedConsequenceDescr = visitNamedConsequenceInvocation(ctx.do2); @@ -672,6 +708,7 @@ public ConditionalBranchDescr visitConditionalBranch(DRLParser.ConditionalBranch } else if (ctx.break2 != null) { ConditionalBranchDescr elseBranchDescr = BaseDescrFactory.builder(new ConditionalBranchDescr()) .withParserRuleContext(ctx.break2) + .withResource(resource) .build(); conditionalBranchDescr.setElseBranch(elseBranchDescr); NamedConsequenceDescr namedConsequenceDescr = visitBreakingNamedConsequenceInvocation(ctx.break2); @@ -689,6 +726,7 @@ public ConditionalBranchDescr visitConditionalBranch(DRLParser.ConditionalBranch public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { ForallDescr forallDescr = BaseDescrFactory.builder(new ForallDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); visitDescrChildren(ctx).forEach(forallDescr::addDescr); return forallDescr; @@ -698,6 +736,7 @@ public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { AccumulateDescr accumulateDescr = BaseDescrFactory.builder(new AccumulateDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); // accumulateDescr.input is always AndDescr accumulateDescr.setInput(wrapWithAndDescr(visitLhsAndDef(ctx.lhsAndDef()), ctx.lhsAndDef())); @@ -707,7 +746,9 @@ public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { accumulateDescr.addFunction(visitAccumulateFunction(accumulateFunctionContext)); } - PatternDescr patternDescr = new PatternDescr("Object"); + PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr("Object")) + .withResource(resource) + .build(); patternDescr.setSource(accumulateDescr); List constraintDescrList = visitConstraints(ctx.constraints()); constraintDescrList.forEach(patternDescr::addConstraint); @@ -731,6 +772,7 @@ private AndDescr wrapWithAndDescr(BaseDescr baseDescr, ParserRuleContext ctx) { public Object visitLhsGroupBy(DRLParser.LhsGroupByContext ctx) { GroupByDescr groupByDescr = BaseDescrFactory.builder(new GroupByDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); groupByDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); @@ -744,7 +786,9 @@ public Object visitLhsGroupBy(DRLParser.LhsGroupByContext ctx) { groupByDescr.addFunction(visitAccumulateFunction(accumulateFunctionContext)); } - PatternDescr patternDescr = new PatternDescr("Object"); + PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr("Object")) + .withResource(resource) + .build(); patternDescr.setSource(groupByDescr); List constraintDescrList = visitConstraints(ctx.constraints()); constraintDescrList.forEach(patternDescr::addConstraint); @@ -756,6 +800,7 @@ public Object visitLhsGroupBy(DRLParser.LhsGroupByContext ctx) { public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { BehaviorDescr behaviorDescr = BaseDescrFactory.builder(new BehaviorDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); behaviorDescr.setType(ctx.DRL_WINDOW().getText()); behaviorDescr.setSubType(ctx.drlIdentifier().getText()); @@ -769,6 +814,7 @@ public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { FromDescr fromDescr = BaseDescrFactory.builder(new FromDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); fromDescr.setDataSource(new MVELExprDescr(getTextPreservingWhitespace(ctx))); return fromDescr; @@ -778,6 +824,7 @@ public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { public CollectDescr visitFromCollect(DRLParser.FromCollectContext ctx) { CollectDescr collectDescr = BaseDescrFactory.builder(new CollectDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); collectDescr.setInputPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); return collectDescr; @@ -787,6 +834,7 @@ public CollectDescr visitFromCollect(DRLParser.FromCollectContext ctx) { public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) { AccumulateDescr accumulateDescr = BaseDescrFactory.builder(new AccumulateDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); // accumulateDescr.input is always AndDescr accumulateDescr.setInput(wrapWithAndDescr(visitLhsAndDef(ctx.lhsAndDef()), ctx.lhsAndDef())); @@ -827,6 +875,7 @@ public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLPa public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) { return BaseDescrFactory.builder(new EntryPointDescr(safeStripStringDelimiters(ctx.stringId().getText()))) .withParserRuleContext(ctx) + .withResource(resource) .build(); } @@ -834,6 +883,7 @@ public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) public WindowReferenceDescr visitFromWindow(DRLParser.FromWindowContext ctx) { return BaseDescrFactory.builder(new WindowReferenceDescr(ctx.drlIdentifier().getText())) .withParserRuleContext(ctx) + .withResource(resource) .build(); } @@ -887,8 +937,9 @@ public List visitConstraint(DRLParser.ConstraintContext ctx String constraint = visitConstraintChildren(ctx); if (!constraint.isEmpty()) { ExprConstraintDescr constraintDescr = BaseDescrFactory.builder(new ExprConstraintDescr(constraint)) - .withParserRuleContext(ctx) - .build(); + .withParserRuleContext(ctx) + .withResource(resource) + .build(); constraintDescr.setType(ExprConstraintDescr.Type.NAMED); descrList.add(constraintDescr); return descrList; @@ -922,6 +973,7 @@ public String visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { ExistsDescr existsDescr = BaseDescrFactory.builder(new ExistsDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); if (ctx.lhsExpression() != null) { // exists( A() or B() ) @@ -943,6 +995,7 @@ public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { NotDescr notDescr = BaseDescrFactory.builder(new NotDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); if (ctx.lhsExpression() != null) { // not ( A() or B() ) @@ -964,6 +1017,7 @@ public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { public EvalDescr visitLhsEval(DRLParser.LhsEvalContext ctx) { return BaseDescrFactory.builder(new EvalDescr(getTextPreservingWhitespace(ctx.conditionalOrExpression()))) .withParserRuleContext(ctx) + .withResource(resource) .build(); } @@ -982,8 +1036,9 @@ public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { return descrList.get(0).getDescr(); } else { OrDescr orDescr = BaseDescrFactory.builder(new OrDescr()) - .withParserRuleContext(ctx) - .build(); + .withParserRuleContext(ctx) + .withResource(resource) + .build(); // For example, in case of A() or B() or C(), // Parser creates AST like this: // lhsOr @@ -1033,8 +1088,9 @@ private BaseDescr createAndDescr(ParserRuleContext ctx) { return descrList.get(0).getDescr(); } else { AndDescr andDescr = BaseDescrFactory.builder(new AndDescr()) - .withParserRuleContext(ctx) - .build(); + .withParserRuleContext(ctx) + .withResource(resource) + .build(); // For example, in case of A() and B() and C(), // Parser creates AST like this: // lhsAnd @@ -1083,6 +1139,7 @@ public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { // lhsUnary may have multiple children e.g. consequenceInvocation, connect with AND AndDescr andDescr = BaseDescrFactory.builder(new AndDescr()) .withParserRuleContext(ctx) + .withResource(resource) .build(); children.forEach(andDescr::addDescr); return andDescr; From 3ba4c323f911fd84d9e97b59e78d69fc3cb2de33 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Mon, 10 Jun 2024 16:06:04 +0900 Subject: [PATCH 127/141] Incubator kie drools 5792 cleanup tests (#5986) * [incubator-kie-drools-5792] cleanup drools-drl-parser-tests - Apply open-rewrite JUnit5BestPractices * - Apply open-rewrite SimplifyChainedAssertJAssertions * - remove 'parse_' prefix - remove unused 'throw Exception' * - code format --- .../drl/parser/antlr4/DRLExprParserTest.java | 82 +- .../antlr4/DRLParserIdentifierTest.java | 20 +- .../drl/parser/antlr4/DRLParserTest.java | 12 +- .../antlr4/DescrCommonPropertyTest.java | 11 +- .../drl/parser/antlr4/DescrDumperTest.java | 188 +- .../drl/parser/antlr4/MiscDRLParserTest.java | 1902 ++++++++--------- 6 files changed, 1077 insertions(+), 1138 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 6489f3fdf80..0baeac61ff1 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 @@ -46,28 +46,28 @@ /** * DRLExprTreeTest */ -public class DRLExprParserTest { +class DRLExprParserTest { DrlExprParser parser; @BeforeEach - public void setUp() { + void setUp() { this.parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); } @AfterEach - public void tearDown() { + void tearDown() { this.parser = null; } @Test - public void testSimpleExpression() { + void simpleExpression() { String source = "a > b"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); assertThat(expr.getOperator()).isEqualTo(">"); @@ -80,13 +80,13 @@ public void testSimpleExpression() { } @Test - public void testAndConnective() throws Exception { + void andConnective() { String source = "a > b && 10 != 20"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); + assertThat(result.getDescrs()).hasSize(2); RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); assertThat(expr.getOperator()).isEqualTo(">"); @@ -104,17 +104,17 @@ public void testAndConnective() throws Exception { } @Test - public void testConnective2() throws Exception { + void connective2() { String source = "(a > b || 10 != 20) && someMethod(10) == 20"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); + assertThat(result.getDescrs()).hasSize(2); ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get( 0 ); assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); - assertThat(or.getDescrs().size()).isEqualTo(2); + assertThat(or.getDescrs()).hasSize(2); RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get( 0 ); assertThat(expr.getOperator()).isEqualTo(">"); @@ -140,13 +140,13 @@ public void testConnective2() throws Exception { } @Test - public void testBinding() throws Exception { + void binding() { String source = "$x : property"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); assertThat(bind.getVariable()).isEqualTo("$x"); @@ -154,13 +154,13 @@ public void testBinding() throws Exception { } @Test - public void testBindingConstraint() throws Exception { + void bindingConstraint() { String source = "$x : property > value"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); RelationalExprDescr rel = (RelationalExprDescr) result.getDescrs().get( 0 ); assertThat(rel.getOperator()).isEqualTo(">"); @@ -174,13 +174,13 @@ public void testBindingConstraint() throws Exception { } @Test - public void testBindingWithRestrictions() throws Exception { + void bindingWithRestrictions() { String source = "$x : property > value && < 20"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); + assertThat(result.getDescrs()).hasSize(2); RelationalExprDescr rel = (RelationalExprDescr) result.getDescrs().get( 0 ); assertThat(rel.getOperator()).isEqualTo(">"); @@ -203,13 +203,13 @@ public void testBindingWithRestrictions() throws Exception { } @Test - public void testDoubleBinding() throws Exception { + void doubleBinding() { String source = "$x : x.m( 1, a ) && $y : y[z].foo"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); + assertThat(result.getDescrs()).hasSize(2); BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); assertThat(bind.getVariable()).isEqualTo("$x"); @@ -231,7 +231,7 @@ public void testDoubleBinding() throws Exception { @ParameterizedTest @EnumSource(Operator.BuiltInOperator.class) - public void testDrlKeywordMethodCall(Operator.BuiltInOperator operator) throws Exception { + void drlKeywordMethodCall(Operator.BuiltInOperator operator) { // Skip operators that cannot be used as method names (==, !=, <, etc.). assumeFalse(nonKeywordBuiltInOperators.contains(operator)); @@ -240,7 +240,7 @@ public void testDrlKeywordMethodCall(Operator.BuiltInOperator operator) throws E assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); AtomicExprDescr descr = (AtomicExprDescr) result.getDescrs().get( 0 ); assertThat(descr.getExpression()).isEqualTo(source); @@ -248,7 +248,7 @@ public void testDrlKeywordMethodCall(Operator.BuiltInOperator operator) throws E @ParameterizedTest @EnumSource(Operator.BuiltInOperator.class) - public void testDrlKeywordInChainedMethodCallWithBinding(Operator.BuiltInOperator operator) throws Exception { + void drlKeywordInChainedMethodCallWithBinding(Operator.BuiltInOperator operator) { // Skip operators that cannot be used as method names (==, !=, <, etc.). assumeFalse(nonKeywordBuiltInOperators.contains(operator)); @@ -259,7 +259,7 @@ public void testDrlKeywordInChainedMethodCallWithBinding(Operator.BuiltInOperato assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); assertThat(bind.getVariable()).isEqualTo(bindingVariableSource); @@ -267,17 +267,17 @@ public void testDrlKeywordInChainedMethodCallWithBinding(Operator.BuiltInOperato } @Test - public void testDeepBinding() throws Exception { + void deepBinding() { String source = "($a : a > $b : b[10].prop || 10 != 20) && $x : someMethod(10) == 20"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); + assertThat(result.getDescrs()).hasSize(2); ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get( 0 ); assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); - assertThat(or.getDescrs().size()).isEqualTo(2); + assertThat(or.getDescrs()).hasSize(2); RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get( 0 ); assertThat(expr.getOperator()).isEqualTo(">"); @@ -307,14 +307,14 @@ public void testDeepBinding() throws Exception { @Test @Timeout(10000L) - public void testNestedExpression() throws Exception { + void nestedExpression() { // DROOLS-982 String source = "(((((((((((((((((((((((((((((((((((((((((((((((((( a > b ))))))))))))))))))))))))))))))))))))))))))))))))))"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); assertThat(expr.getOperator()).isEqualTo(">"); @@ -349,12 +349,12 @@ public void testNestedExpression() throws Exception { "Object[][].class.getName()", "newArrayList()" }) - void testKeywords(String source) { + void keywords(String source) { ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); AtomicExprDescr expr = (AtomicExprDescr) result.getDescrs().get( 0 ); @@ -362,13 +362,13 @@ void testKeywords(String source) { } @Test - public void testKeyword_instanceof() { + void keywordInstanceof() { String source = "a instanceof A"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); // Unlike the other keywords, instanceof can only be used in a relational expression, // so it needs to be tested differently. @@ -383,7 +383,7 @@ public void testKeyword_instanceof() { } @Test - public void testMismatchedInput() { + void mismatchedInput() { String source = "+"; parser.parse(source); assertThat(parser.hasErrors()).isTrue(); @@ -412,7 +412,7 @@ public void testMismatchedInput() { } @Test - public void testExtraneousInput() { + void extraneousInput() { String source = "a +; b"; parser.parse(source); assertThat(parser.hasErrors()).isTrue(); @@ -441,7 +441,7 @@ public void testExtraneousInput() { } @Test - public void testNoViableAlt() { + void noViableAlt() { String source = "a~a"; parser.parse(source); @@ -471,10 +471,10 @@ void orWithMethodCall() { assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); // root is AND - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get(0); assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); - assertThat(or.getDescrs().size()).isEqualTo(2); + assertThat(or.getDescrs()).hasSize(2); RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get(0); assertThat(expr.getOperator()).isEqualTo("=="); @@ -498,10 +498,10 @@ void orWithMethodCallWithArg() { assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); // root is AND - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get(0); assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); - assertThat(or.getDescrs().size()).isEqualTo(2); + assertThat(or.getDescrs()).hasSize(2); RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get(0); assertThat(expr.getOperator()).isEqualTo("=="); @@ -525,7 +525,7 @@ void andWithMethodCall() { assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); + assertThat(result.getDescrs()).hasSize(2); RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get(0); assertThat(expr.getOperator()).isEqualTo("=="); @@ -549,7 +549,7 @@ void andWithMethodCallWithArg() { assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); - assertThat(result.getDescrs().size()).isEqualTo(2); + assertThat(result.getDescrs()).hasSize(2); RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get(0); assertThat(expr.getOperator()).isEqualTo("=="); @@ -572,7 +572,7 @@ void newBigDecimal() { ConstraintConnectiveDescr result = parser.parse(source); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); - assertThat(result.getDescrs().size()).isEqualTo(1); + assertThat(result.getDescrs()).hasSize(1); BindingDescr bind = (BindingDescr) result.getDescrs().get(0); assertThat(bind.getVariable()).isEqualTo("$bd"); diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java index 5e0b60545b2..cd982fc001e 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java @@ -47,7 +47,7 @@ class DRLParserIdentifierTest { private DrlParser parser; @BeforeEach - public void setUp() { + void setUp() { parser = ParserTestUtils.getParser(); } @@ -108,7 +108,7 @@ void nestedConstraint() { } @Test - public void function() { + void function() { final String text = "function boolean contains(String s) { return true; }"; PackageDescr packageDescr = parseAndGetPackageDescr(text); FunctionDescr function = packageDescr.getFunctions().get(0); @@ -116,7 +116,7 @@ public void function() { } @Test - public void patternFilter() { + void patternFilter() { final String text = "rule X when StockTick( symbol==\"ACME\") over window:contains(10) then end"; RuleDescr rule = parseAndGetFirstRuleDescr(text); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); @@ -127,7 +127,7 @@ public void patternFilter() { } @Test - public void accumulateFunction() { + void accumulateFunction() { final String text = "rule R1\n" + "when\n" + " accumulate( Person( $age : age > 21 ), $ave : contains( $age ) );\n" + @@ -140,7 +140,7 @@ public void accumulateFunction() { } @Test - public void fromWindow() { + void fromWindow() { final String text = "rule X\n" + "when\n" + @@ -155,7 +155,7 @@ public void fromWindow() { } @Test - public void type() { + void type() { final String text = "global contains.matches bbb"; PackageDescr pkg = parseAndGetPackageDescr(text); GlobalDescr global = pkg.getGlobals().get(0); @@ -164,7 +164,7 @@ public void type() { } @Test - public void unification() throws Exception { + void unification() { final String text = "rule X\n" + "when\n" + " contains := Person()\n" + @@ -176,7 +176,7 @@ public void unification() throws Exception { } @Test - public void annotation() { + void annotation() { final String text = "rule R\n" + "@contains.matches(soundslike=\"abc\")\n" + "when\n" + @@ -188,7 +188,7 @@ public void annotation() { } @Test - public void constraintBoundVariable() { + void constraintBoundVariable() { final String text = "rule X\n" + "when\n" + " Person( contains : age > 20)\n" + @@ -200,7 +200,7 @@ public void constraintBoundVariable() { } @Test - public void constraintBoundVariableUnify() { + void constraintBoundVariableUnify() { final String text = "rule X\n" + "when\n" + " Person( contains := age > 20)\n" + 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/DRLParserTest.java index 1533aefdc0b..b760f5f75b4 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/DRLParserTest.java @@ -56,22 +56,22 @@ void parse_basicRule() { PackageDescr packageDescr = parse(drl); assertThat(packageDescr.getName()).isEqualTo("org.test"); - assertThat(packageDescr.getImports().size()).isEqualTo(1); + assertThat(packageDescr.getImports()).hasSize(1); assertThat(packageDescr.getImports().get(0).getTarget()).isEqualTo("org.test.model.Person"); - assertThat(packageDescr.getGlobals().size()).isEqualTo(1); + assertThat(packageDescr.getGlobals()).hasSize(1); GlobalDescr globalDescr = packageDescr.getGlobals().get(0); assertThat(globalDescr.getType()).isEqualTo("String"); assertThat(globalDescr.getIdentifier()).isEqualTo("result"); - assertThat(packageDescr.getRules().size()).isEqualTo(1); + assertThat(packageDescr.getRules()).hasSize(1); RuleDescr ruleDescr = packageDescr.getRules().get(0); AnnotationDescr annotationDescr = ruleDescr.getAnnotation("Test"); assertThat(annotationDescr).isNotNull(); assertThat(annotationDescr.getValue()).isEqualTo("true"); - assertThat(ruleDescr.getAttributes().size()).isEqualTo(2); + assertThat(ruleDescr.getAttributes()).hasSize(2); assertThat(ruleDescr.getAttributes().get("no-loop")).isNotNull(); AttributeDescr salience = ruleDescr.getAttributes().get("salience"); assertThat(salience).isNotNull(); @@ -79,13 +79,13 @@ void parse_basicRule() { assertThat(ruleDescr.getName()).isEqualTo("TestRule"); - assertThat(ruleDescr.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(ruleDescr.getLhs().getDescrs()).hasSize(1); PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); assertThat(patternDescr.getIdentifier()).isEqualTo("$p"); assertThat(patternDescr.getObjectType()).isEqualTo("Person"); List constraints = patternDescr.getConstraint().getDescrs(); - assertThat(constraints.size()).isEqualTo(1); + assertThat(constraints).hasSize(1); ExprConstraintDescr expr = (ExprConstraintDescr) constraints.get(0); assertThat(expr.getExpression()).isEqualTo("age >= 18"); 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 0582c9faf5e..2e1a0e8564e 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 @@ -71,7 +71,7 @@ class DescrCommonPropertyTest { private Resource resource; @BeforeEach - public void setUp() { + void setUp() { parser = ParserTestUtils.getParser(); } @@ -332,7 +332,7 @@ void accumulateDescr() { @Test void behaviorDescr() { - final String source = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end";; + final String source = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end"; final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); @@ -349,11 +349,12 @@ void fromDescr() { " Adult( $children : children)\n" + " Child() from $children\n" + " then\n" + - "end";; + "end"; + ; final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); - FromDescr from = (FromDescr) pattern.getSource(); + FromDescr from = (FromDescr) pattern.getSource(); // Backward Compatibility Notes: // The old DRL6Parser doesn't populate common properties of FromDescr (seem to be wrong). @@ -376,7 +377,7 @@ void collectDescr() { final PackageDescr pkg = parseAndGetPackageDescr(source); final RuleDescr rule = pkg.getRules().get(0); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); - CollectDescr collect = (CollectDescr) pattern.getSource(); + CollectDescr collect = (CollectDescr) pattern.getSource(); assertProperties(collect, 35, 64, 3, 21, 3, 49); } 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 1d038907c89..76f750ff215 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 @@ -18,8 +18,6 @@ */ package org.drools.drl.parser.antlr4; -import static org.assertj.core.api.Assertions.assertThat; - import org.drools.compiler.lang.DescrDumper; import org.drools.compiler.lang.DumperContext; import org.drools.drl.ast.descr.AtomicExprDescr; @@ -34,12 +32,14 @@ import org.junit.jupiter.api.Test; import org.kie.internal.builder.conf.LanguageLevelOption; +import static org.assertj.core.api.Assertions.assertThat; + public class DescrDumperTest { private DescrDumper dumper; @BeforeEach - public void setUp() throws Exception { + void setUp() { // configure operators new SetEvaluatorsDefinition(); new MatchesEvaluatorsDefinition(); @@ -48,238 +48,239 @@ public void setUp() throws Exception { } @Test - public void testDump() throws Exception { + void dump() { String input = "price > 10 && < 20 || == $val || == 30"; String expected = "( price > 10 && price < 20 || price == $val || price == 30 )"; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpMatches() throws Exception { + void dumpMatches() { String input = "type.toString matches \"something\\swith\\tsingle escapes\""; String expected = "type.toString ~= \"something\\swith\\tsingle escapes\""; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpMatches2() throws Exception { + void dumpMatches2() { String input = "type.toString matches 'something\\swith\\tsingle escapes'"; String expected = "type.toString ~= \"something\\swith\\tsingle escapes\""; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpMatches3() throws Exception { + void dumpMatches3() { String input = "this[\"content\"] matches \"hello ;=\""; String expected = "this[\"content\"] ~= \"hello ;=\""; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpContains() throws Exception { + void dumpContains() { String input = "list contains \"b\""; String expected = "list contains \"b\""; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpContains2() throws Exception { + void dumpContains2() { String input = "list not contains \"b\""; String expected = "!( list contains \"b\" )"; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpExcludes() throws Exception { + void dumpExcludes() { String input = "list excludes \"b\""; String expected = "!( list contains \"b\" )"; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpExcludes2() throws Exception { + void dumpExcludes2() { String input = "list not excludes \"b\""; String expected = "list contains \"b\""; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } - @Test @Disabled - public void testDumpWithDateAttr() throws Exception { + @Test + @Disabled + void dumpWithDateAttr() { String input = "son.birthDate == \"01-jan-2000\""; String expected = "son.birthDate == org.drools.util.DateUtils.parseDate( \"01-jan-2000\" )"; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpComplex() throws Exception { + void dumpComplex() { String input = "a ( > 60 && < 70 ) || ( > 50 && < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\""; String expected = "( ( a > 60 && a < 70 || a > 50 && a < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\" )"; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpBindings() throws Exception { + void dumpBindings() { String input = "$x : property > value"; String expected = "property > value"; - ConstraintConnectiveDescr descr = parse( input ); + ConstraintConnectiveDescr descr = parse(input); DumperContext ctx = new DumperContext(); - String result = dumper.dump( descr, - ctx ); + String result = dumper.dump(descr, + ctx); assertThat(result).isEqualTo(expected); - assertThat(ctx.getBindings().size()).isEqualTo(1); - BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(ctx.getBindings()).hasSize(1); + BindingDescr bind = ctx.getBindings().get(0); assertThat(bind.getVariable()).isEqualTo("$x"); assertThat(bind.getExpression()).isEqualTo("property"); } @Test - public void testDumpBindings2() throws Exception { + void dumpBindings2() { String input = "( $a : a > $b : b[10].prop || 10 != 20 ) && $x : someMethod(10) == 20"; String expected = "( a > b[10].prop || 10 != 20 ) && someMethod(10) == 20"; - ConstraintConnectiveDescr descr = parse( input ); + ConstraintConnectiveDescr descr = parse(input); DumperContext ctx = new DumperContext(); - String result = dumper.dump( descr, - ctx ); + String result = dumper.dump(descr, + ctx); assertThat(result).isEqualTo(expected); - assertThat(ctx.getBindings().size()).isEqualTo(3); - BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(ctx.getBindings()).hasSize(3); + BindingDescr bind = ctx.getBindings().get(0); assertThat(bind.getVariable()).isEqualTo("$a"); assertThat(bind.getExpression()).isEqualTo("a"); - bind = ctx.getBindings().get( 1 ); + bind = ctx.getBindings().get(1); assertThat(bind.getVariable()).isEqualTo("$b"); assertThat(bind.getExpression()).isEqualTo("b[10].prop"); - bind = ctx.getBindings().get( 2 ); + bind = ctx.getBindings().get(2); assertThat(bind.getVariable()).isEqualTo("$x"); assertThat(bind.getExpression()).isEqualTo("someMethod(10)"); } @Test - public void testDumpBindings3() throws Exception { + void dumpBindings3() { String input = "( $a : a > $b : b[10].prop || 10 != 20 ) && $x : someMethod(10)"; String expected = "( a > b[10].prop || 10 != 20 )"; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpBindings4() throws Exception { + void dumpBindings4() { String input = "( $a : a > $b : b[10].prop || $x : someMethod(10) ) && 10 != 20"; String expected = "( a > b[10].prop ) && 10 != 20"; - ConstraintConnectiveDescr descr = parse( input ); - String result = dumper.dump( descr ); + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); assertThat(result).isEqualTo(expected); } @Test - public void testDumpBindingsWithRestriction() throws Exception { + void dumpBindingsWithRestriction() { String input = "$x : age > 10 && < 20 || > 30"; String expected = "( age > 10 && age < 20 || age > 30 )"; - ConstraintConnectiveDescr descr = parse( input ); + ConstraintConnectiveDescr descr = parse(input); DumperContext ctx = new DumperContext(); - String result = dumper.dump( descr, - ctx ); + String result = dumper.dump(descr, + ctx); assertThat(result).isEqualTo(expected); - assertThat(ctx.getBindings().size()).isEqualTo(1); - BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(ctx.getBindings()).hasSize(1); + BindingDescr bind = ctx.getBindings().get(0); assertThat(bind.getVariable()).isEqualTo("$x"); assertThat(bind.getExpression()).isEqualTo("age"); } @Test - public void testDumpBindingsComplexOp() throws Exception { + void dumpBindingsComplexOp() { String input = "$x : age in (10, 20, $someVal)"; String expected = "( age == 10 || age == 20 || age == $someVal )"; - ConstraintConnectiveDescr descr = parse( input ); + ConstraintConnectiveDescr descr = parse(input); DumperContext ctx = new DumperContext(); - String result = dumper.dump( descr, - ctx ); + String result = dumper.dump(descr, + ctx); assertThat(result).isEqualTo(expected); - assertThat(ctx.getBindings().size()).isEqualTo(1); - BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(ctx.getBindings()).hasSize(1); + BindingDescr bind = ctx.getBindings().get(0); assertThat(bind.getVariable()).isEqualTo("$x"); assertThat(bind.getExpression()).isEqualTo("age"); } @Test - public void testDumpBindingsComplexOp2() throws Exception { + void dumpBindingsComplexOp2() { String input = "$x : age not in (10, 20, $someVal)"; String expected = "age != 10 && age != 20 && age != $someVal"; - ConstraintConnectiveDescr descr = parse( input ); + ConstraintConnectiveDescr descr = parse(input); DumperContext ctx = new DumperContext(); - String result = dumper.dump( descr, - ctx ); + String result = dumper.dump(descr, + ctx); assertThat(result).isEqualTo(expected); - assertThat(ctx.getBindings().size()).isEqualTo(1); - BindingDescr bind = ctx.getBindings().get( 0 ); + assertThat(ctx.getBindings()).hasSize(1); + BindingDescr bind = ctx.getBindings().get(0); assertThat(bind.getVariable()).isEqualTo("$x"); assertThat(bind.getExpression()).isEqualTo("age"); } @Test - public void testProcessInlineCast() throws Exception { + void processInlineCast() { String expr = "field1#Class.field2"; String expectedInstanceof = "field1 instanceof Class"; String expectedcasted = "((Class)field1).field2"; AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); - ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); - ccd.addDescr( atomicExpr ); - String[] instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null); - assertThat(ccd.getDescrs().size()).isEqualTo(2); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr(); + ccd.addDescr(atomicExpr); + String[] instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); + assertThat(ccd.getDescrs()).hasSize(2); assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedInstanceof); assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedcasted); @@ -288,8 +289,8 @@ public void testProcessInlineCast() throws Exception { String expectedInstanceof2 = "((Class1)field1).field2 instanceof Class2"; expectedcasted = "((Class2)((Class1)field1).field2).field3"; atomicExpr = new AtomicExprDescr(expr); - ccd = new ConstraintConnectiveDescr( ); - instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null); + ccd = new ConstraintConnectiveDescr(); + instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedInstanceof1); assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedInstanceof2); assertThat(instanceofAndCastedExpr[1]).isEqualTo(expectedcasted); @@ -297,13 +298,13 @@ public void testProcessInlineCast() throws Exception { } @Test - public void testProcessNullSafeDereferencing() throws Exception { + void processNullSafeDereferencing() { String expr = "field1!.field2"; String expectedNullCheck = "field1 != null"; String expectedExpr = "field1.field2"; AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); - ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); - String[] nullCheckAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr(); + String[] nullCheckAndExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedNullCheck); assertThat(nullCheckAndExpr[1]).isEqualTo(expectedExpr); assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); @@ -313,8 +314,8 @@ public void testProcessNullSafeDereferencing() throws Exception { String expectedNullCheck2 = "field1.field2 != null"; expectedExpr = "field1.field2.field3"; atomicExpr = new AtomicExprDescr(expr); - ccd = new ConstraintConnectiveDescr( ); - nullCheckAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + ccd = new ConstraintConnectiveDescr(); + nullCheckAndExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedNullCheck1); assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedNullCheck2); assertThat(nullCheckAndExpr[1]).isEqualTo(expectedExpr); @@ -322,13 +323,13 @@ public void testProcessNullSafeDereferencing() throws Exception { } @Test - public void testProcessImplicitConstraints() throws Exception { + void processImplicitConstraints() { String expr = "field1#Class!.field2"; String expectedConstraints = "field1 instanceof Class"; String expectedExpr = "((Class)field1).field2"; AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); - ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr( ); - String[] constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr(); + String[] constraintsAndExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints); assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); @@ -338,8 +339,8 @@ public void testProcessImplicitConstraints() throws Exception { String expectedConstraints2 = "field1.field2 instanceof Class"; expectedExpr = "((Class)field1.field2).field3"; atomicExpr = new AtomicExprDescr(expr); - ccd = new ConstraintConnectiveDescr( ); - constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + ccd = new ConstraintConnectiveDescr(); + constraintsAndExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints1); assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedConstraints2); assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); @@ -350,20 +351,19 @@ public void testProcessImplicitConstraints() throws Exception { expectedConstraints2 = "((Class)field1).field2 != null"; expectedExpr = "((Class)field1).field2.field3"; atomicExpr = new AtomicExprDescr(expr); - ccd = new ConstraintConnectiveDescr( ); - constraintsAndExpr = dumper.processImplicitConstraints( expr, atomicExpr, ccd, ccd.getDescrs().indexOf( atomicExpr ), null ); + ccd = new ConstraintConnectiveDescr(); + constraintsAndExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints1); assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedConstraints2); assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); } - public ConstraintConnectiveDescr parse( final String constraint ) { + public ConstraintConnectiveDescr parse(final String constraint) { DrlExprParser parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); - ConstraintConnectiveDescr result = parser.parse( constraint ); + ConstraintConnectiveDescr result = parser.parse(constraint); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); return result; } - } 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 4769ce9f3ba..3fc2cdbca39 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 @@ -91,7 +91,7 @@ class MiscDRLParserTest { private DrlParser parser; @BeforeEach - public void setUp() { + void setUp() { parser = ParserTestUtils.getParser(); } @@ -116,7 +116,7 @@ private String readResource(final String filename) { private PackageDescr parseAndGetPackageDescr(String drl) { try { - PackageDescr pkg = parser.parse(null, drl); + PackageDescr pkg = parser.parse(null, drl); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); return pkg; } catch (DroolsParserException e) { @@ -185,14 +185,14 @@ void emptySource() { } @Test - void parse_validPackage() { + void validPackage() { final String source = "package foo.bar.baz"; final PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); } @Test - void parse_packageWithErrorNode() { + void packageWithErrorNode() { final String source = "package 12 foo.bar.baz"; final PackageDescr pkg = parseAndGetPackageDescrWithoutErrorCheck(source); assertThat(parser.hasErrors()).isTrue(); @@ -200,7 +200,7 @@ void parse_packageWithErrorNode() { } @Test - void parse_packageWithAllErrorNode() { + void packageWithAllErrorNode() { final String source = "package 12 12312 231"; final PackageDescr pkg = parseAndGetPackageDescrWithoutErrorCheck(source); assertThat(parser.hasErrors()).isTrue(); @@ -208,9 +208,9 @@ void parse_packageWithAllErrorNode() { } @Test - void parse_import() { + void importDef() { final String source = "package foo; import com.foo.Bar; import com.foo.Baz;"; - PackageDescr pkg =parseAndGetPackageDescr(source); + PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("foo"); assertThat(pkg.getImports()).hasSize(2); ImportDescr impdescr = pkg.getImports().get(0); @@ -225,7 +225,7 @@ void parse_import() { } @Test - void parse_functionImport() { + void functionImport() { final String source = "package foo\n" + "import function java.lang.Math.max\n" + "import function java.lang.Math.min;\n" + @@ -258,7 +258,7 @@ void parse_functionImport() { } @Test - void parse_globalWithComplexType() { + void globalWithComplexType() { final String source = "package foo.bar.baz\n" + "import com.foo.Bar\n" + "global java.util.List> aList;\n" + @@ -290,7 +290,7 @@ void parse_globalWithComplexType() { } @Test - void parse_globalWithOrWithoutSemi() throws Exception { + void globalWithOrWithoutSemi() { String source = readResource("globals.drl"); PackageDescr pkg = parseAndGetPackageDescr(source); @@ -311,7 +311,7 @@ void parse_globalWithOrWithoutSemi() throws Exception { } @Test - void parse_functionImportWithNotExist() throws Exception { + void functionImportWithNotExist() { String source = readResource("test_FunctionImport.drl"); PackageDescr pkg = parseAndGetPackageDescr(source); @@ -326,7 +326,7 @@ void parse_functionImportWithNotExist() throws Exception { } @Test - void parse_fromComplexAccessor() { + void fromComplexAccessor() { String source = "rule \"Invalid customer id\" ruleflow-group \"validate\" lock-on-active true \n" + " when \n" + " o: Order( ) \n" + @@ -351,7 +351,7 @@ void parse_fromComplexAccessor() { } @Test - void parse_fromWithInlineList() { + void fromWithInlineList() { String source = "rule XYZ \n" + " when \n" + " o: Order( ) \n" + @@ -370,7 +370,7 @@ void parse_fromWithInlineList() { } @Test - void parse_fromWithInlineListMethod() { + void fromWithInlineListMethod() { String source = "rule XYZ \n" + " when \n" + " o: Order( ) \n" + @@ -390,7 +390,7 @@ void parse_fromWithInlineListMethod() { } @Test - void parse_fromWithInlineListIndex() { + void fromWithInlineListIndex() { String source = "rule XYZ \n" + " when \n" + " o: Order( ) \n" + @@ -409,7 +409,7 @@ void parse_fromWithInlineListIndex() { } @Test - void parse_ruleWithoutEnd() { + void ruleWithoutEnd() { String source = "rule \"Invalid customer id\" \n" + " when \n" + " o: Order( ) \n" + @@ -420,7 +420,7 @@ void parse_ruleWithoutEnd() { } @Test - void parse_orWithSpecialBind() { + void orWithSpecialBind() { String source = "rule \"A and (B or C or D)\" \n" + " when \n" + " pdo1 : ParametricDataObject( paramID == 101, stringValue == \"1000\" ) and \n" + @@ -447,7 +447,7 @@ void parse_orWithSpecialBind() { } @Test - void parse_compatibleRestriction() { + void compatibleRestriction() { String source = "package com.sample rule test when Test( ( text == null || text2 matches \"\" ) ) then end"; PackageDescr pkg = parseAndGetPackageDescr(source); @@ -459,7 +459,7 @@ void parse_compatibleRestriction() { } @Test - void parse_simpleConstraint() { + void simpleConstraint() { String source = "package com.sample rule test when Cheese( type == 'stilton', price > 10 ) then end"; PackageDescr pkg = parseAndGetPackageDescr(source); @@ -477,7 +477,7 @@ void parse_simpleConstraint() { } @Test - void parse_stringEscapes() { + void stringEscapes() { String source = "package com.sample rule test when Cheese( type matches \"\\..*\\\\.\" ) then end"; PackageDescr pkg = parseAndGetPackageDescr(source); assertThat(pkg.getName()).isEqualTo("com.sample"); @@ -493,7 +493,7 @@ void parse_stringEscapes() { } @Test - void parse_dialectWithSingleQuotation() { + void dialectWithSingleQuotation() { final String source = "dialect 'mvel'"; PackageDescr pkg = parseAndGetPackageDescr(source); AttributeDescr attr = pkg.getAttributes().get(0); @@ -502,7 +502,7 @@ void parse_dialectWithSingleQuotation() { } @Test - void parse_dialectWithDoubleQuotation() { + void dialectWithDoubleQuotation() { final String source = "dialect \"mvel\""; PackageDescr pkg = parseAndGetPackageDescr(source); AttributeDescr attr = pkg.getAttributes().get(0); @@ -511,7 +511,7 @@ void parse_dialectWithDoubleQuotation() { } @Test - void parse_emptyRuleWithoutWhen() throws Exception { + void emptyRuleWithoutWhen() { String source = readResource("empty_rule.drl"); // without WHEN RuleDescr ruleDescr = parseAndGetFirstRuleDescr(source); @@ -523,7 +523,7 @@ void parse_emptyRuleWithoutWhen() throws Exception { } @Test - void parse_keywordCollisions() throws Exception { + void keywordCollisions() { String source = readResource("eol_funny_business.drl"); // keywords everywhere // Note: eol_funny_business.drl is modified from the one under drools-test-coverage to be more realistic. @@ -535,7 +535,7 @@ void parse_keywordCollisions() throws Exception { } @Test - void parse_ternaryExpression() throws Exception { + void ternaryExpression() { String source = readResource("ternary_expression.drl"); PackageDescr pkg = parseAndGetPackageDescr(source); @@ -546,7 +546,7 @@ void parse_ternaryExpression() throws Exception { } @Test - void parse_functionWithArrays() throws Exception { + void functionWithArrays() { String source = readResource("function_arrays.drl"); // Note: function_arrays.drl is modified from the one under drools-test-coverage to be more realistic. @@ -570,7 +570,7 @@ void parse_functionWithArrays() throws Exception { } @Test - void parse_almostEmptyRule() throws Exception { + void almostEmptyRule() { String source = readResource("almost_empty_rule.drl"); PackageDescr pkg = parseAndGetPackageDescr(source); @@ -580,11 +580,11 @@ void parse_almostEmptyRule() throws Exception { assertThat(rule.getName()).isEqualTo("almost_empty"); assertThat(rule.getLhs()).isNotNull(); - assertThat(((String) rule.getConsequence()).trim()).isEmpty(); + assertThat(((String) rule.getConsequence())).isBlank(); } @Test - void parse_quotedStringNameRule() throws Exception { + void quotedStringNameRule() { String source = readResource("quoted_string_name_rule.drl"); PackageDescr pkg = parseAndGetPackageDescr(source); @@ -593,11 +593,11 @@ void parse_quotedStringNameRule() throws Exception { assertThat(rule.getName()).isEqualTo("quoted string name"); assertThat(rule.getLhs()).isNotNull(); - assertThat(((String) rule.getConsequence()).trim()).isEmpty(); + assertThat(((String) rule.getConsequence())).isBlank(); } @Test - void parse_noLoop() throws Exception { + void noLoop() { String source = readResource("no-loop.drl"); PackageDescr pkg = parseAndGetPackageDescr(source); @@ -611,7 +611,7 @@ void parse_noLoop() throws Exception { } @Test - void parse_autofocus() throws Exception { + void autofocus() { String source = readResource("autofocus.drl"); PackageDescr pkg = parseAndGetPackageDescr(source); @@ -625,12 +625,10 @@ void parse_autofocus() throws Exception { } @Test - void parse_ruleFlowGroup() throws Exception { + void ruleFlowGroup() { String source = readResource("ruleflowgroup.drl"); PackageDescr pkg = parseAndGetPackageDescr(source); - - RuleDescr rule = pkg.getRules().get(0); assertThat(rule).isNotNull(); @@ -641,15 +639,13 @@ void parse_ruleFlowGroup() throws Exception { } @Test - void parse_consequenceWithDeclaration() throws Exception { + void consequenceWithDeclaration() { String source = readResource("declaration-in-consequence.drl"); PackageDescr pkg = parseAndGetPackageDescr(source); // Note : Removed "i\i;" from the original declaration-in-consequence.drl under drools-test-coverage // because it's not a valid java expression and doesn't make sense to test. (Right to raise a parser error) - - RuleDescr rule = pkg.getRules().get(0); assertThat(rule).isNotNull(); @@ -672,13 +668,11 @@ void parse_consequenceWithDeclaration() throws Exception { } @Test - void parse_or() { + void or() { final String text = "rule X when Person(age < 42, location==\"atlanta\") \nor\nPerson(name==\"bob\") then end"; PackageDescr pkg = parseAndGetPackageDescr(text); RuleDescr rule = pkg.getRules().get(0); - - assertThat(rule).isNotNull(); AndDescr lhs = rule.getLhs(); @@ -687,13 +681,11 @@ void parse_or() { } @Test - void parse_lhsWithStringQuotes() { + void lhsWithStringQuotes() { final String text = "rule X when Person( location==\"atlanta\\\"\") then end\n"; PackageDescr pkg = parseAndGetPackageDescr(text); RuleDescr rule = pkg.getRules().get(0); - - assertThat(rule).isNotNull(); AndDescr lhs = rule.getLhs(); @@ -703,12 +695,11 @@ void parse_lhsWithStringQuotes() { } @Test - void parse_lhsWithStringQuotesEscapeChars() { + void lhsWithStringQuotesEscapeChars() { final String text = "rule X when Cheese( $x: type, type == \"s\\tti\\\"lto\\nn\" ) then end\n"; PackageDescr pkg = parseAndGetPackageDescr(text); RuleDescr rule = pkg.getRules().get(0); - assertThat(rule).isNotNull(); AndDescr lhs = rule.getLhs(); @@ -718,7 +709,7 @@ void parse_lhsWithStringQuotesEscapeChars() { } @Test - void parse_literalBoolAndNegativeNumbersRule() throws Exception { + void literalBoolAndNegativeNumbersRule() { RuleDescr rule = parseAndGetFirstRuleDescrFromFile("literal_bool_and_negative.drl"); assertThat(rule).isNotNull(); @@ -755,12 +746,10 @@ void parse_literalBoolAndNegativeNumbersRule() throws Exception { } @Test - void parse_emptyPattern() throws Exception { + void emptyPattern() { String source = readResource("test_EmptyPattern.drl"); PackageDescr pkg = parseAndGetPackageDescr(source); - - assertThat(pkg.getRules()).hasSize(1); final RuleDescr ruleDescr = pkg.getRules().get(0); assertThat(ruleDescr.getName()).isEqualTo("simple rule"); @@ -772,7 +761,7 @@ void parse_emptyPattern() throws Exception { } @Test - void parse_simpleMethodCallWithFrom() throws Exception { + void simpleMethodCallWithFrom() { RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleMethodCallWithFrom.drl"); final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final FromDescr from = (FromDescr) pattern.getSource(); @@ -782,7 +771,7 @@ void parse_simpleMethodCallWithFrom() throws Exception { } @Test - void parse_simpleFunctionCallWithFrom() throws Exception { + void simpleFunctionCallWithFrom() { RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleFunctionCallWithFrom.drl"); final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final FromDescr from = (FromDescr) pattern.getSource(); @@ -792,9 +781,9 @@ void parse_simpleFunctionCallWithFrom() throws Exception { } @Test - void parse_simpleAccessorWithFrom() throws Exception { + void simpleAccessorWithFrom() { RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleAccessorWithFrom.drl"); - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final FromDescr from = (FromDescr) pattern.getSource(); final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); @@ -802,9 +791,9 @@ void parse_simpleAccessorWithFrom() throws Exception { } @Test - void parse_simpleAccessorAndArgWithFrom() throws Exception { + void simpleAccessorAndArgWithFrom() { RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleAccessorArgWithFrom.drl"); - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final FromDescr from = (FromDescr) pattern.getSource(); final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); @@ -812,10 +801,10 @@ void parse_simpleAccessorAndArgWithFrom() throws Exception { } @Test - void parse_complexChainedAccessor() throws Exception { + void complexChainedAccessor() { RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_ComplexChainedCallWithFrom.drl"); - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final FromDescr from = (FromDescr) pattern.getSource(); final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); @@ -823,7 +812,7 @@ void parse_complexChainedAccessor() throws Exception { } @Test - void parse_from() throws Exception { + void from() { RuleDescr rule = parseAndGetFirstRuleDescrFromFile("from.drl"); assertThat(rule).isNotNull(); @@ -833,7 +822,7 @@ void parse_from() throws Exception { } @Test - void parse_simpleRuleWithBindings() throws Exception { + void simpleRuleWithBindings() { RuleDescr rule = parseAndGetFirstRuleDescrFromFile("simple_rule.drl"); assertThat(rule).isNotNull(); @@ -885,7 +874,7 @@ void parse_simpleRuleWithBindings() throws Exception { } @Test - void parse_multipleRestrictionsConstraint() throws Exception { + void multipleRestrictionsConstraint() { RuleDescr rule = parseAndGetFirstRuleDescrFromFile("restrictions_test.drl"); assertThat(rule).isNotNull(); @@ -895,41 +884,36 @@ void parse_multipleRestrictionsConstraint() throws Exception { // The first pattern, with 2 restrictions on a single field (plus a // connective) - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat( pattern.getConstraint().getDescrs()).hasSize(1); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); AndDescr and = (AndDescr) pattern.getConstraint(); - ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get(0); assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); // the second col, with 2 fields, the first with 2 restrictions, the // second field with one - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); assertThat(pattern.getConstraint().getDescrs()).hasSize(2); and = (AndDescr) pattern.getConstraint(); - fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); - assertThat(fld.getExpression()).isEqualToIgnoringWhitespace( "type == \"sedan\" || == \"wagon\""); + fld = (ExprConstraintDescr) and.getDescrs().get(0); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type == \"sedan\" || == \"wagon\""); // now the second field - fld = (ExprConstraintDescr) and.getDescrs().get( 1 ); - assertThat(fld.getExpression()).isEqualToIgnoringWhitespace( "age < 3"); + fld = (ExprConstraintDescr) and.getDescrs().get(1); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("age < 3"); } -//------------------------------------------------------------------------- -// DROOLS-7271 : ported from RuleParserTest -// Failing tests are annotated with @Disabled. We can fix issues one by one -//------------------------------------------------------------------------- - @Test - public void parse_LineNumberInAST() throws Exception { + void lineNumberInAST() { // also see testSimpleExpander to see how this works with an expander // (should be the same). final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "simple_rule.drl" ); + "simple_rule.drl"); assertThat(rule).isNotNull(); @@ -942,20 +926,20 @@ public void parse_LineNumberInAST() throws Exception { assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(3); + assertThat(lhs.getDescrs()).hasSize(3); // Check first pattern - final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + final PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); assertThat(first.getIdentifier()).isEqualTo("foo3"); assertThat(first.getObjectType()).isEqualTo("Bar"); - assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(first.getConstraint().getDescrs()).hasSize(1); // Check second pattern - final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); + final PatternDescr second = (PatternDescr) lhs.getDescrs().get(1); assertThat(second.getIdentifier()).isEqualTo("foo4"); assertThat(second.getObjectType()).isEqualTo("Bar"); - final PatternDescr third = (PatternDescr) lhs.getDescrs().get( 2 ); + final PatternDescr third = (PatternDescr) lhs.getDescrs().get(2); assertThat(third.getObjectType()).isEqualTo("Baz"); assertThat(first.getLine()).isEqualTo(19); @@ -964,24 +948,20 @@ public void parse_LineNumberInAST() throws Exception { } @Test - public void parse_LineNumberIncludingCommentsInRHS() throws Exception { + void lineNumberIncludingCommentsInRHS() { PackageDescr pkg = parseAndGetPackageDescrFromFile( - "test_CommentLineNumbersInConsequence.drl" ); - + "test_CommentLineNumbersInConsequence.drl"); - - final String rhs = (String) ((RuleDescr) pkg.getRules().get( 0 )).getConsequence(); + final String rhs = (String) ((RuleDescr) pkg.getRules().get(0)).getConsequence(); String expected = "\\s*//woot$\\s*first;$\\s*$\\s*//$\\s*$\\s*/\\* lala$\\s*$\\s*\\*/$\\s*second;$\\s*"; assertThat(Pattern.compile(expected, Pattern.DOTALL | Pattern.MULTILINE).matcher(rhs).matches()).isTrue(); } @Test - public void parse_LhsSemicolonDelim() throws Exception { + void lhsSemicolonDelim() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "lhs_semicolon_delim.drl" ); - - + "lhs_semicolon_delim.drl"); assertThat(rule).isNotNull(); @@ -991,36 +971,36 @@ public void parse_LhsSemicolonDelim() throws Exception { assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(3); + assertThat(lhs.getDescrs()).hasSize(3); // System.err.println( lhs.getDescrs() ); // Check first pattern - final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + final PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); assertThat(first.getIdentifier()).isEqualTo("foo3"); assertThat(first.getObjectType()).isEqualTo("Bar"); - assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(first.getConstraint().getDescrs()).hasSize(1); // LiteralDescr constraint = (LiteralDescr) first.getDescrs().get( 0 ); AndDescr and = (AndDescr) first.getConstraint(); - ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get(0); assertThat(fld).isNotNull(); assertThat(fld.getExpression()).isEqualTo("a==3"); // Check second pattern - final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); + final PatternDescr second = (PatternDescr) lhs.getDescrs().get(1); assertThat(second.getIdentifier()).isEqualTo("foo4"); assertThat(second.getObjectType()).isEqualTo("Bar"); - assertThat(second.getDescrs().size()).isEqualTo(1); + assertThat(second.getDescrs()).hasSize(1); - final ExprConstraintDescr fieldBindingDescr = (ExprConstraintDescr) second.getDescrs().get( 0 ); + final ExprConstraintDescr fieldBindingDescr = (ExprConstraintDescr) second.getDescrs().get(0); assertThat(fieldBindingDescr.getExpression()).isEqualTo("a4:a==4"); // Check third pattern - final PatternDescr third = (PatternDescr) lhs.getDescrs().get( 2 ); + final PatternDescr third = (PatternDescr) lhs.getDescrs().get(2); assertThat(third.getIdentifier()).isNull(); assertThat(third.getObjectType()).isEqualTo("Baz"); @@ -1028,61 +1008,57 @@ public void parse_LhsSemicolonDelim() throws Exception { } @Test - public void parse_NotNode() throws Exception { + void notNode() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_not.drl" ); - - + "rule_not.drl"); assertThat(rule).isNotNull(); assertThat(rule.getName()).isEqualTo("simple_rule"); final AndDescr lhs = rule.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); - final NotDescr not = (NotDescr) lhs.getDescrs().get( 0 ); - assertThat(not.getDescrs().size()).isEqualTo(1); - final PatternDescr pattern = (PatternDescr) not.getDescrs().get( 0 ); + assertThat(lhs.getDescrs()).hasSize(1); + final NotDescr not = (NotDescr) lhs.getDescrs().get(0); + assertThat(not.getDescrs()).hasSize(1); + final PatternDescr pattern = (PatternDescr) not.getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); final AndDescr and = (AndDescr) pattern.getConstraint(); - final ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + final ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get(0); assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); } @Test - public void parse_NotExistWithBrackets() throws Exception { + void notExistWithBrackets() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "not_exist_with_brackets.drl" ); - - + "not_exist_with_brackets.drl"); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule).isNotNull(); assertThat(rule.getName()).isEqualTo("simple_rule"); final AndDescr lhs = rule.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(2); - final NotDescr not = (NotDescr) lhs.getDescrs().get( 0 ); - assertThat(not.getDescrs().size()).isEqualTo(1); - final PatternDescr pattern = (PatternDescr) not.getDescrs().get( 0 ); + assertThat(lhs.getDescrs()).hasSize(2); + final NotDescr not = (NotDescr) lhs.getDescrs().get(0); + assertThat(not.getDescrs()).hasSize(1); + final PatternDescr pattern = (PatternDescr) not.getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Cheese"); - final ExistsDescr ex = (ExistsDescr) lhs.getDescrs().get(1 ); - assertThat(ex.getDescrs().size()).isEqualTo(1); - final PatternDescr exPattern = (PatternDescr) ex.getDescrs().get( 0 ); + final ExistsDescr ex = (ExistsDescr) lhs.getDescrs().get(1); + assertThat(ex.getDescrs()).hasSize(1); + final PatternDescr exPattern = (PatternDescr) ex.getDescrs().get(0); assertThat(exPattern.getObjectType()).isEqualTo("Foo"); } @Test - public void parse_SimpleQuery() throws Exception { + void simpleQuery() { final QueryDescr query = parseAndGetFirstQueryDescrFromFile( - "simple_query.drl" ); + "simple_query.drl"); assertThat(query).isNotNull(); @@ -1092,110 +1068,110 @@ public void parse_SimpleQuery() throws Exception { assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(3); + assertThat(lhs.getDescrs()).hasSize(3); // Check first pattern - final PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + final PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); assertThat(first.getIdentifier()).isEqualTo("foo3"); assertThat(first.getObjectType()).isEqualTo("Bar"); - assertThat(first.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(first.getConstraint().getDescrs()).hasSize(1); AndDescr and = (AndDescr) first.getConstraint(); - ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get( 0 ); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get(0); assertThat(fld).isNotNull(); assertThat(fld.getExpression()).isEqualTo("a==3"); // Check second pattern - final PatternDescr second = (PatternDescr) lhs.getDescrs().get( 1 ); + final PatternDescr second = (PatternDescr) lhs.getDescrs().get(1); assertThat(second.getIdentifier()).isEqualTo("foo4"); assertThat(second.getObjectType()).isEqualTo("Bar"); - assertThat(second.getDescrs().size()).isEqualTo(1); + assertThat(second.getDescrs()).hasSize(1); // check it has field bindings. - final ExprConstraintDescr bindingDescr = (ExprConstraintDescr) second.getDescrs().get( 0 ); + final ExprConstraintDescr bindingDescr = (ExprConstraintDescr) second.getDescrs().get(0); assertThat(bindingDescr.getExpression()).isEqualTo("a4:a==4"); } @Test - public void parse_QueryRuleMixed() throws Exception { + void queryRuleMixed() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "query_and_rule.drl" ); + "query_and_rule.drl"); - assertThat(pkg.getRules().size()).isEqualTo(4); // as queries are rules - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(pkg.getRules()).hasSize(4); // as queries are rules + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("bar"); - QueryDescr query = (QueryDescr) pkg.getRules().get( 1 ); + QueryDescr query = (QueryDescr) pkg.getRules().get(1); assertThat(query.getName()).isEqualTo("simple_query"); - rule = (RuleDescr) pkg.getRules().get( 2 ); + rule = (RuleDescr) pkg.getRules().get(2); assertThat(rule.getName()).isEqualTo("bar2"); - query = (QueryDescr) pkg.getRules().get( 3 ); + query = (QueryDescr) pkg.getRules().get(3); assertThat(query.getName()).isEqualTo("simple_query2"); } @Test - public void parse_MultipleRules() throws Exception { + void multipleRules() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "multiple_rules.drl" ); + "multiple_rules.drl"); final List rules = pkg.getRules(); - assertThat(rules.size()).isEqualTo(2); + assertThat(rules).hasSize(2); - final RuleDescr rule0 = rules.get( 0 ); + final RuleDescr rule0 = rules.get(0); assertThat(rule0.getName()).isEqualTo("Like Stilton"); - final RuleDescr rule1 = rules.get( 1 ); + final RuleDescr rule1 = rules.get(1); assertThat(rule1.getName()).isEqualTo("Like Cheddar"); // checkout the first rule AndDescr lhs = rule1.getLhs(); assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); - assertThat((String) rule0.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"I like \" + t);"); + assertThat(lhs.getDescrs()).hasSize(1); + assertThat((String) rule0.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(\"I like \" + t);"); // Check first pattern - PatternDescr first = (PatternDescr) lhs.getDescrs().get( 0 ); + PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); assertThat(first.getObjectType()).isEqualTo("Cheese"); // checkout the second rule lhs = rule1.getLhs(); assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); - assertThat((String) rule1.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"I like \" + t);"); + assertThat(lhs.getDescrs()).hasSize(1); + assertThat((String) rule1.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(\"I like \" + t);"); // Check first pattern - first = (PatternDescr) lhs.getDescrs().get( 0 ); + first = (PatternDescr) lhs.getDescrs().get(0); assertThat(first.getObjectType()).isEqualTo("Cheese"); } @Test - public void parse_ExpanderLineSpread() { + void expanderLineSpread() { final PackageDescr pkg = parseAndGetPackageDescrWithDsl("expander_spread_lines.dslr", "complex.dsl"); final RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(rule.getLhs().getDescrs()).hasSize(1); final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); - assertThat(or.getDescrs().size()).isEqualTo(2); + assertThat(or.getDescrs()).hasSize(2); assertThat((String) rule.getConsequence()).isNotNull(); } @Test - public void parse_ExpanderMultipleConstraints() { + void expanderMultipleConstraints() { final PackageDescr pkg = parseAndGetPackageDescrWithDsl("expander_multiple_constraints.dslr", "multiple_constraints.dsl"); final RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + assertThat(rule.getLhs().getDescrs()).hasSize(2); PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); @@ -1206,18 +1182,18 @@ public void parse_ExpanderMultipleConstraints() { } @Test - public void parse_ExpanderMultipleConstraintsFlush() { + void expanderMultipleConstraintsFlush() { // this is similar to the other test, but it requires a flush to add the // constraints final PackageDescr pkg = parseAndGetPackageDescrWithDsl("expander_multiple_constraints_flush.dslr", "multiple_constraints.dsl"); final RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(rule.getLhs().getDescrs()).hasSize(1); final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); @@ -1225,238 +1201,244 @@ public void parse_ExpanderMultipleConstraintsFlush() { } @Test - public void parse_BasicBinding() throws Exception { + void basicBinding() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "basic_binding.drl" ); + "basic_binding.drl"); - final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get( 0 ); + final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get(0); final AndDescr lhs = ruleDescr.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); - final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(lhs.getDescrs()).hasSize(1); + final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get(0); assertThat(cheese.getObjectType()).isEqualTo("Cheese"); - assertThat(cheese.getConstraint().getDescrs().size()).isEqualTo(1); - final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get( 0 ); + assertThat(cheese.getConstraint().getDescrs()).hasSize(1); + final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get(0); assertThat(fieldBinding.getExpression()).isEqualToIgnoringWhitespace("$type:type"); } @Test - public void parse_BoundVariables() throws Exception { + void boundVariables() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "bindings.drl" ); + "bindings.drl"); - final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get( 0 ); + final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get(0); final AndDescr lhs = ruleDescr.getLhs(); - assertThat(lhs.getDescrs().size()).isEqualTo(2); - final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get( 0 ); + assertThat(lhs.getDescrs()).hasSize(2); + final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get(0); assertThat(cheese.getObjectType()).isEqualTo("Cheese"); - assertThat(cheese.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get( 0 ); + assertThat(cheese.getDescrs()).hasSize(1); + ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get(0); assertThat(fieldBinding.getExpression()).isEqualTo("$type : type == \"stilton\""); - final PatternDescr person = (PatternDescr) lhs.getDescrs().get( 1 ); - assertThat(person.getDescrs().size()).isEqualTo(2); - fieldBinding = (ExprConstraintDescr) person.getDescrs().get( 0 ); + final PatternDescr person = (PatternDescr) lhs.getDescrs().get(1); + assertThat(person.getDescrs()).hasSize(2); + fieldBinding = (ExprConstraintDescr) person.getDescrs().get(0); assertThat(fieldBinding.getExpression()).isEqualTo("$name : name == \"bob\""); - ExprConstraintDescr fld = (ExprConstraintDescr) person.getDescrs().get( 1 ); + ExprConstraintDescr fld = (ExprConstraintDescr) person.getDescrs().get(1); assertThat(fld.getExpression()).isEqualTo("likes == $type"); } @Test - public void parse_OrNesting() throws Exception { + void orNesting() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "or_nesting.drl" ); + "or_nesting.drl"); assertThat(pkg).isNotNull(); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(or.getDescrs().size()).isEqualTo(2); + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); - final PatternDescr first = (PatternDescr) or.getDescrs().get( 0 ); + final PatternDescr first = (PatternDescr) or.getDescrs().get(0); assertThat(first.getObjectType()).isEqualTo("Person"); - final AndDescr and = (AndDescr) or.getDescrs().get( 1 ); - assertThat(and.getDescrs().size()).isEqualTo(2); + final AndDescr and = (AndDescr) or.getDescrs().get(1); + assertThat(and.getDescrs()).hasSize(2); - final PatternDescr left = (PatternDescr) and.getDescrs().get( 0 ); + final PatternDescr left = (PatternDescr) and.getDescrs().get(0); assertThat(left.getObjectType()).isEqualTo("Person"); - final PatternDescr right = (PatternDescr) and.getDescrs().get( 1 ); + final PatternDescr right = (PatternDescr) and.getDescrs().get(1); assertThat(right.getObjectType()).isEqualTo("Cheese"); } - /** Test that explicit "&&", "||" works as expected */ + /** + * Test that explicit "&&", "||" works as expected + */ @Test - public void parse_AndOrRules() throws Exception { + void andOrRules() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "and_or_rule.drl" ); + "and_or_rule.drl"); assertThat(pkg).isNotNull(); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("simple_rule"); // we will have 3 children under the main And node final AndDescr and = rule.getLhs(); - assertThat(and.getDescrs().size()).isEqualTo(3); + assertThat(and.getDescrs()).hasSize(3); - PatternDescr left = (PatternDescr) and.getDescrs().get( 0 ); - PatternDescr right = (PatternDescr) and.getDescrs().get( 1 ); + PatternDescr left = (PatternDescr) and.getDescrs().get(0); + PatternDescr right = (PatternDescr) and.getDescrs().get(1); assertThat(left.getObjectType()).isEqualTo("Person"); assertThat(right.getObjectType()).isEqualTo("Cheese"); - assertThat(left.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(left.getConstraint().getDescrs()).hasSize(1); - ExprConstraintDescr fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get( 0 ); + ExprConstraintDescr fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualTo("name == \"mark\""); - assertThat(right.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(right.getConstraint().getDescrs()).hasSize(1); - fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get( 0 ); + fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); // now the "||" part - final OrDescr or = (OrDescr) and.getDescrs().get( 2 ); - assertThat(or.getDescrs().size()).isEqualTo(2); - left = (PatternDescr) or.getDescrs().get( 0 ); - right = (PatternDescr) or.getDescrs().get( 1 ); + final OrDescr or = (OrDescr) and.getDescrs().get(2); + assertThat(or.getDescrs()).hasSize(2); + left = (PatternDescr) or.getDescrs().get(0); + right = (PatternDescr) or.getDescrs().get(1); assertThat(left.getObjectType()).isEqualTo("Person"); assertThat(right.getObjectType()).isEqualTo("Cheese"); - assertThat(left.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(left.getConstraint().getDescrs()).hasSize(1); - fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get( 0 ); + fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualTo("name == \"mark\""); - assertThat(right.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(right.getConstraint().getDescrs()).hasSize(1); - fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get( 0 ); + fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" );"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println( \"Mark and Michael\" );"); } - /** test basic foo : Fact() || Fact() stuff */ + /** + * test basic foo : Fact() || Fact() stuff + */ @Test - public void parse_OrWithBinding() throws Exception { + void orWithBinding() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "or_binding.drl" ); + "or_binding.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(2); - final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(or.getDescrs().size()).isEqualTo(2); + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); - final PatternDescr leftPattern = (PatternDescr) or.getDescrs().get( 0 ); + final PatternDescr leftPattern = (PatternDescr) or.getDescrs().get(0); assertThat(leftPattern.getObjectType()).isEqualTo("Person"); assertThat(leftPattern.getIdentifier()).isEqualTo("foo"); - final PatternDescr rightPattern = (PatternDescr) or.getDescrs().get( 1 ); + final PatternDescr rightPattern = (PatternDescr) or.getDescrs().get(1); assertThat(rightPattern.getObjectType()).isEqualTo("Person"); assertThat(rightPattern.getIdentifier()).isEqualTo("foo"); - final PatternDescr cheeseDescr = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + final PatternDescr cheeseDescr = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(cheeseDescr.getObjectType()).isEqualTo("Cheese"); assertThat(cheeseDescr.getIdentifier()).isEqualTo(null); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println( \"Mark and Michael\" + bar );"); } - /** test basic foo : Fact() || Fact() stuff binding to an "or" */ + /** + * test basic foo : Fact() || Fact() stuff binding to an "or" + */ @Test - public void parse_OrBindingComplex() throws Exception { + void orBindingComplex() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "or_binding_complex.drl" ); + "or_binding_complex.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(or.getDescrs().size()).isEqualTo(2); + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); // first fact - final PatternDescr firstFact = (PatternDescr) or.getDescrs().get( 0 ); + final PatternDescr firstFact = (PatternDescr) or.getDescrs().get(0); assertThat(firstFact.getObjectType()).isEqualTo("Person"); assertThat(firstFact.getIdentifier()).isEqualTo("foo"); // second "option" - final PatternDescr secondFact = (PatternDescr) or.getDescrs().get( 1 ); + final PatternDescr secondFact = (PatternDescr) or.getDescrs().get(1); assertThat(secondFact.getObjectType()).isEqualTo("Person"); - assertThat(secondFact.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(secondFact.getConstraint().getDescrs()).hasSize(1); assertThat(secondFact.getIdentifier()).isEqualTo("foo"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println( \"Mark and Michael\" + bar );"); } @Test - public void parse_OrBindingWithBrackets() throws Exception { + void orBindingWithBrackets() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "or_binding_with_brackets.drl" ); + "or_binding_with_brackets.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(or.getDescrs().size()).isEqualTo(2); + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); // first fact - final PatternDescr firstFact = (PatternDescr) or.getDescrs().get( 0 ); + final PatternDescr firstFact = (PatternDescr) or.getDescrs().get(0); assertThat(firstFact.getObjectType()).isEqualTo("Person"); assertThat(firstFact.getIdentifier()).isEqualTo("foo"); // second "option" - final PatternDescr secondFact = (PatternDescr) or.getDescrs().get( 0 ); + final PatternDescr secondFact = (PatternDescr) or.getDescrs().get(0); assertThat(secondFact.getObjectType()).isEqualTo("Person"); assertThat(secondFact.getIdentifier()).isEqualTo("foo"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println( \"Mark and Michael\" + bar );"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println( \"Mark and Michael\" + bar );"); } @Test - void parenthesesOrAndOr() throws Exception { + void parenthesesOrAndOr() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "brackets_precedence.drl" ); + "brackets_precedence.drl"); assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); final AndDescr rootAnd = (AndDescr) rule.getLhs(); assertThat(rootAnd.getDescrs()).hasSize(2); - final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get( 0 ); + final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get(0); assertThat(leftOr.getDescrs()).hasSize(2); - final NotDescr not = (NotDescr) leftOr.getDescrs().get( 0 ); - final PatternDescr foo1 = (PatternDescr) not.getDescrs().get( 0 ); + final NotDescr not = (NotDescr) leftOr.getDescrs().get(0); + final PatternDescr foo1 = (PatternDescr) not.getDescrs().get(0); assertThat(foo1.getObjectType()).isEqualTo("Foo"); - final PatternDescr foo2 = (PatternDescr) leftOr.getDescrs().get( 1 ); + final PatternDescr foo2 = (PatternDescr) leftOr.getDescrs().get(1); assertThat(foo2.getObjectType()).isEqualTo("Foo"); - final OrDescr rightOr = (OrDescr) rootAnd.getDescrs().get( 1 ); + final OrDescr rightOr = (OrDescr) rootAnd.getDescrs().get(1); assertThat(rightOr.getDescrs()).hasSize(2); - final PatternDescr shoes = (PatternDescr) rightOr.getDescrs().get( 0 ); + final PatternDescr shoes = (PatternDescr) rightOr.getDescrs().get(0); assertThat(shoes.getObjectType()).isEqualTo("Shoes"); - final PatternDescr butt = (PatternDescr) rightOr.getDescrs().get( 1 ); + final PatternDescr butt = (PatternDescr) rightOr.getDescrs().get(1); assertThat(butt.getObjectType()).isEqualTo("Butt"); } @@ -1522,7 +1504,7 @@ void parenthesesOrAndAnd() { } @Test - void multipleLevelNestAndOrOrOrAnd() throws Exception { + void multipleLevelNestAndOrOrOrAnd() { final String drl = "rule and_or_or_or_and\n" + " when\n" + " (Foo(x == 1) and (Bar(x == 2) or Foo(x == 3))) or (Bar(x == 4) or (Foo(x == 5) and Bar(x == 6)))\n" + @@ -1562,7 +1544,7 @@ void multipleLevelNestAndOrOrOrAnd() throws Exception { } @Test - void multipleLevelNestWithThreeOrSiblings() throws Exception { + void multipleLevelNestWithThreeOrSiblings() { final String drl = "rule nest_or_siblings\n" + " when\n" + " (A() or (B() or C() or (D() and E())))\n" + @@ -1597,7 +1579,7 @@ void multipleLevelNestWithThreeOrSiblings() throws Exception { } @Test - public void existsMultipleLevelNestWithThreeOrSiblings() throws Exception { + void existsMultipleLevelNestWithThreeOrSiblings() { final String drl = "rule nest_or_siblings\n" + " when\n" + " exists(A() or (B() or C() or (D() and E())))\n" + @@ -1635,113 +1617,112 @@ public void existsMultipleLevelNestWithThreeOrSiblings() throws Exception { } @Test - public void parse_EvalMultiple() throws Exception { + void evalMultiple() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "eval_multiple.drl" ); + "eval_multiple.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(4); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(4); - final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(0 ); - assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace( "abc(\"foo\") + 5"); + final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(0); + assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace("abc(\"foo\") + 5"); - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(pattern.getObjectType()).isEqualTo("Foo"); - } @Test - public void parse_WithEval() throws Exception { + void withEval() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "with_eval.drl" ); + "with_eval.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(3); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(3); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Foo"); - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(pattern.getObjectType()).isEqualTo("Bar"); - final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get( 2 ); - assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace( "abc(\"foo\")"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "Kapow"); + final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(2); + assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace("abc(\"foo\")"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("Kapow"); } @Test - public void parse_WithRetval() throws Exception { + void withRetval() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "with_retval.drl" ); + "with_retval.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - assertThat(col.getConstraint().getDescrs().size()).isEqualTo(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(col.getConstraint().getDescrs()).hasSize(1); assertThat(col.getObjectType()).isEqualTo("Foo"); - final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get( 0 ); + final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("name== (a + b)"); } @Test - public void parse_WithPredicate() throws Exception { + void withPredicate() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "with_predicate.drl" ); + "with_predicate.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get(0); AndDescr and = (AndDescr) col.getConstraint(); - assertThat(and.getDescrs().size()).isEqualTo(2); + assertThat(and.getDescrs()).hasSize(2); - final ExprConstraintDescr field = (ExprConstraintDescr) col.getDescrs().get( 0 ); - final ExprConstraintDescr pred = (ExprConstraintDescr) and.getDescrs().get( 1 ); + final ExprConstraintDescr field = (ExprConstraintDescr) col.getDescrs().get(0); + final ExprConstraintDescr pred = (ExprConstraintDescr) and.getDescrs().get(1); assertThat(field.getExpression()).isEqualToIgnoringWhitespace("$age2:age"); - assertThat(pred.getExpression()).isEqualToIgnoringWhitespace( "$age2 == $age1+2"); + assertThat(pred.getExpression()).isEqualToIgnoringWhitespace("$age2 == $age1+2"); } @Test - public void parse_NotWithConstraint() throws Exception { + void notWithConstraint() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "not_with_constraint.drl" ); + "not_with_constraint.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(2); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(fieldBinding.getExpression()).isEqualToIgnoringWhitespace("$likes:like"); - final NotDescr not = (NotDescr) rule.getLhs().getDescrs().get( 1 ); - pattern = (PatternDescr) not.getDescrs().get( 0 ); + final NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(1); + pattern = (PatternDescr) not.getDescrs().get(0); - final ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + final ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type == $likes"); } @Test - public void parse_Functions() throws Exception { + void functions() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "functions.drl" ); + "functions.drl"); - assertThat(pkg.getRules().size()).isEqualTo(2); + assertThat(pkg.getRules()).hasSize(2); final List functions = pkg.getFunctions(); - assertThat(functions.size()).isEqualTo(2); + assertThat(functions).hasSize(2); - FunctionDescr func = functions.get( 0 ); + FunctionDescr func = functions.get(0); assertThat(func.getName()).isEqualTo("functionA"); assertThat(func.getReturnType()).isEqualTo("String"); - assertThat(func.getParameterNames().size()).isEqualTo(2); - assertThat(func.getParameterTypes().size()).isEqualTo(2); + assertThat(func.getParameterNames()).hasSize(2); + assertThat(func.getParameterTypes()).hasSize(2); assertThat(func.getLine()).isEqualTo(21); assertThat(func.getColumn()).isEqualTo(0); @@ -1751,17 +1732,17 @@ public void parse_Functions() throws Exception { assertThat(func.getParameterTypes().get(1)).isEqualTo("Integer"); assertThat(func.getParameterNames().get(1)).isEqualTo("i"); - assertThat(func.getBody()).isEqualToIgnoringWhitespace( "foo();"); + assertThat(func.getBody()).isEqualToIgnoringWhitespace("foo();"); - func = functions.get( 1 ); + func = functions.get(1); assertThat(func.getName()).isEqualTo("functionB"); - assertThat(func.getText()).isEqualToIgnoringWhitespace( "bar();"); + assertThat(func.getText()).isEqualToIgnoringWhitespace("bar();"); } @Test - public void parse_Comment() throws Exception { + void comment() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "comment.drl" ); + "comment.drl"); assertThat(pkg).isNotNull(); @@ -1769,320 +1750,314 @@ public void parse_Comment() throws Exception { } @Test - public void parse_Attributes() throws Exception { + void attributes() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_attributes.drl" ); + "rule_attributes.drl"); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(6); + assertThat(attrs).hasSize(6); - AttributeDescr at = (AttributeDescr) attrs.get( "salience" ); + AttributeDescr at = (AttributeDescr) attrs.get("salience"); assertThat(at.getName()).isEqualTo("salience"); assertThat(at.getValue()).isEqualTo("42"); - at = (AttributeDescr) attrs.get( "agenda-group" ); + at = (AttributeDescr) attrs.get("agenda-group"); assertThat(at.getName()).isEqualTo("agenda-group"); assertThat(at.getValue()).isEqualTo("my_group"); - at = (AttributeDescr) attrs.get( "no-loop" ); + at = (AttributeDescr) attrs.get("no-loop"); assertThat(at.getName()).isEqualTo("no-loop"); assertThat(at.getValue()).isEqualTo("true"); - at = (AttributeDescr) attrs.get( "duration" ); + at = (AttributeDescr) attrs.get("duration"); assertThat(at.getName()).isEqualTo("duration"); assertThat(at.getValue()).isEqualTo("42"); - at = (AttributeDescr) attrs.get( "activation-group" ); + at = (AttributeDescr) attrs.get("activation-group"); assertThat(at.getName()).isEqualTo("activation-group"); assertThat(at.getValue()).isEqualTo("my_activation_group"); - at = (AttributeDescr) attrs.get( "lock-on-active" ); + at = (AttributeDescr) attrs.get("lock-on-active"); assertThat(at.getName()).isEqualTo("lock-on-active"); assertThat(at.getValue()).isEqualTo("true"); } @Test - public void parse_Attributes2() throws Exception { + void attributes2() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "rule_attributes2.drl" ); - + "rule_attributes2.drl"); List rules = pkg.getRules(); - assertThat(rules.size()).isEqualTo(3); + assertThat(rules).hasSize(3); - RuleDescr rule = rules.get( 0 ); + RuleDescr rule = rules.get(0); assertThat(rule.getName()).isEqualTo("rule1"); Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); - AttributeDescr at = (AttributeDescr) attrs.get( "salience" ); + assertThat(attrs).hasSize(2); + AttributeDescr at = (AttributeDescr) attrs.get("salience"); assertThat(at.getName()).isEqualTo("salience"); assertThat(at.getValue()).isEqualTo("(42)"); - at = (AttributeDescr) attrs.get( "agenda-group" ); + at = (AttributeDescr) attrs.get("agenda-group"); assertThat(at.getName()).isEqualTo("agenda-group"); assertThat(at.getValue()).isEqualTo("my_group"); - rule = rules.get( 1 ); + rule = rules.get(1); assertThat(rule.getName()).isEqualTo("rule2"); attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); - at = (AttributeDescr) attrs.get( "salience" ); + assertThat(attrs).hasSize(2); + at = (AttributeDescr) attrs.get("salience"); assertThat(at.getName()).isEqualTo("salience"); assertThat(at.getValue()).isEqualTo("(Integer.MIN_VALUE)"); - at = (AttributeDescr) attrs.get( "no-loop" ); + at = (AttributeDescr) attrs.get("no-loop"); assertThat(at.getName()).isEqualTo("no-loop"); - rule = rules.get( 2 ); + rule = rules.get(2); assertThat(rule.getName()).isEqualTo("rule3"); attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); - at = (AttributeDescr) attrs.get( "enabled" ); + assertThat(attrs).hasSize(2); + at = (AttributeDescr) attrs.get("enabled"); assertThat(at.getName()).isEqualTo("enabled"); assertThat(at.getValue()).isEqualTo("(Boolean.TRUE)"); - at = (AttributeDescr) attrs.get( "activation-group" ); + at = (AttributeDescr) attrs.get("activation-group"); assertThat(at.getName()).isEqualTo("activation-group"); assertThat(at.getValue()).isEqualTo("my_activation_group"); - } @Test - public void parse_AttributeRefract() throws Exception { + void attributeRefract() { final String source = "rule Test refract when Person() then end"; PackageDescr pkg = parseAndGetPackageDescr( - source ); - + source); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("Test"); Map attributes = rule.getAttributes(); - assertThat(attributes.size()).isEqualTo(1); - AttributeDescr refract = attributes.get( "refract" ); + assertThat(attributes).hasSize(1); + AttributeDescr refract = attributes.get("refract"); assertThat(refract).isNotNull(); assertThat(refract.getValue()).isEqualTo("true"); - } @Test - public void parse_EnabledExpression() throws Exception { + void enabledExpression() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_enabled_expression.drl" ); + "rule_enabled_expression.drl"); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(3); + assertThat(attrs).hasSize(3); - AttributeDescr at = (AttributeDescr) attrs.get( "enabled" ); + AttributeDescr at = (AttributeDescr) attrs.get("enabled"); assertThat(at.getName()).isEqualTo("enabled"); assertThat(at.getValue()).isEqualTo("( 1 + 1 == 2 )"); - at = (AttributeDescr) attrs.get( "salience" ); + at = (AttributeDescr) attrs.get("salience"); assertThat(at.getName()).isEqualTo("salience"); assertThat(at.getValue()).isEqualTo("( 1+2 )"); - at = (AttributeDescr) attrs.get( "lock-on-active" ); + at = (AttributeDescr) attrs.get("lock-on-active"); assertThat(at.getName()).isEqualTo("lock-on-active"); assertThat(at.getValue()).isEqualTo("true"); } @Test - public void parse_DurationExpression() throws Exception { + void durationExpression() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_duration_expression.drl" ); + "rule_duration_expression.drl"); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); + assertThat(attrs).hasSize(2); - AttributeDescr at = (AttributeDescr) attrs.get( "duration" ); + AttributeDescr at = (AttributeDescr) attrs.get("duration"); assertThat(at.getName()).isEqualTo("duration"); assertThat(at.getValue()).isEqualTo("1h30m"); - at = (AttributeDescr) attrs.get( "lock-on-active" ); + at = (AttributeDescr) attrs.get("lock-on-active"); assertThat(at.getName()).isEqualTo("lock-on-active"); assertThat(at.getValue()).isEqualTo("true"); } @Test - public void parse_Calendars() throws Exception { + void calendars() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_calendars_attribute.drl" ); + "rule_calendars_attribute.drl"); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); + assertThat(attrs).hasSize(2); - AttributeDescr at = (AttributeDescr) attrs.get( "calendars" ); + AttributeDescr at = (AttributeDescr) attrs.get("calendars"); assertThat(at.getName()).isEqualTo("calendars"); assertThat(at.getValue()).isEqualTo("[ \"cal1\" ]"); - at = (AttributeDescr) attrs.get( "lock-on-active" ); + at = (AttributeDescr) attrs.get("lock-on-active"); assertThat(at.getName()).isEqualTo("lock-on-active"); assertThat(at.getValue()).isEqualTo("true"); } @Test - public void parse_Calendars2() throws Exception { + void calendars2() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_calendars_attribute2.drl" ); + "rule_calendars_attribute2.drl"); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); + assertThat(attrs).hasSize(2); - AttributeDescr at = (AttributeDescr) attrs.get( "calendars" ); + AttributeDescr at = (AttributeDescr) attrs.get("calendars"); assertThat(at.getName()).isEqualTo("calendars"); assertThat(at.getValue()).isEqualTo("[ \"cal 1\", \"cal 2\", \"cal 3\" ]"); - at = (AttributeDescr) attrs.get( "lock-on-active" ); + at = (AttributeDescr) attrs.get("lock-on-active"); assertThat(at.getName()).isEqualTo("lock-on-active"); assertThat(at.getValue()).isEqualTo("true"); } @Test - public void parse_Timer() throws Exception { - final RuleDescr rule = parseAndGetFirstRuleDescrFromFile("rule_timer_attribute.drl" ); + void timer() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile("rule_timer_attribute.drl"); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(2); + assertThat(attrs).hasSize(2); - AttributeDescr at = (AttributeDescr) attrs.get( "timer" ); + AttributeDescr at = (AttributeDescr) attrs.get("timer"); assertThat(at.getName()).isEqualTo("timer"); assertThat(at.getValue()).isEqualTo("int: 0 1; start=1_000_000, repeat-limit=0"); - at = (AttributeDescr) attrs.get( "lock-on-active" ); + at = (AttributeDescr) attrs.get("lock-on-active"); assertThat(at.getName()).isEqualTo("lock-on-active"); assertThat(at.getValue()).isEqualTo("true"); } @Test - public void parse_Attributes_alternateSyntax() { + void attributes_alternateSyntax() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "rule_attributes_alt.drl" ); + "rule_attributes_alt.drl"); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "bar();"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); final Map attrs = rule.getAttributes(); - assertThat(attrs.size()).isEqualTo(6); + assertThat(attrs).hasSize(6); - AttributeDescr at = attrs.get( "salience" ); + AttributeDescr at = attrs.get("salience"); assertThat(at.getName()).isEqualTo("salience"); assertThat(at.getValue()).isEqualTo("42"); - at = attrs.get( "agenda-group" ); + at = attrs.get("agenda-group"); assertThat(at.getName()).isEqualTo("agenda-group"); assertThat(at.getValue()).isEqualTo("my_group"); - at = attrs.get( "no-loop" ); + at = attrs.get("no-loop"); assertThat(at.getName()).isEqualTo("no-loop"); assertThat(at.getValue()).isEqualTo("true"); - at = attrs.get( "lock-on-active" ); + at = attrs.get("lock-on-active"); assertThat(at.getName()).isEqualTo("lock-on-active"); assertThat(at.getValue()).isEqualTo("true"); - at = attrs.get( "duration" ); + at = attrs.get("duration"); assertThat(at.getName()).isEqualTo("duration"); assertThat(at.getValue()).isEqualTo("42"); - at = attrs.get( "activation-group" ); + at = attrs.get("activation-group"); assertThat(at.getName()).isEqualTo("activation-group"); assertThat(at.getValue()).isEqualTo("my_activation_group"); } @Test - public void parse_Enumeration() throws Exception { + void enumeration() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "enumeration.drl" ); + "enumeration.drl"); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(col.getObjectType()).isEqualTo("Foo"); - assertThat(col.getConstraint().getDescrs().size()).isEqualTo(1); - final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get( 0 ); + assertThat(col.getConstraint().getDescrs()).hasSize(1); + final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == Foo.BAR"); } @Test - public void parse_ExtraLhsNewline() throws Exception { + void extraLhsNewline() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "extra_lhs_newline.drl" ); - + "extra_lhs_newline.drl"); } @Test - public void parse_SoundsLike() throws Exception { + void soundsLike() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "soundslike_operator.drl" ); + "soundslike_operator.drl"); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - PatternDescr pat = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + PatternDescr pat = (PatternDescr) rule.getLhs().getDescrs().get(0); pat.getConstraint(); } @Test - public void parse_PackageAttributes() throws Exception { + void packageAttributes() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "package_attributes.drl" ); + "package_attributes.drl"); - AttributeDescr at = (AttributeDescr) pkg.getAttributes().get( 0 ); + AttributeDescr at = (AttributeDescr) pkg.getAttributes().get(0); assertThat(at.getName()).isEqualTo("agenda-group"); assertThat(at.getValue()).isEqualTo("x"); - at = (AttributeDescr) pkg.getAttributes().get( 1 ); + at = (AttributeDescr) pkg.getAttributes().get(1); assertThat(at.getName()).isEqualTo("dialect"); assertThat(at.getValue()).isEqualTo("java"); - assertThat(pkg.getRules().size()).isEqualTo(2); + assertThat(pkg.getRules()).hasSize(2); - assertThat(pkg.getImports().size()).isEqualTo(2); + assertThat(pkg.getImports()).hasSize(2); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("bar"); - at = (AttributeDescr) rule.getAttributes().get( "agenda-group" ); + at = (AttributeDescr) rule.getAttributes().get("agenda-group"); assertThat(at.getName()).isEqualTo("agenda-group"); assertThat(at.getValue()).isEqualTo("x"); - at = (AttributeDescr) rule.getAttributes().get( "dialect" ); + at = (AttributeDescr) rule.getAttributes().get("dialect"); assertThat(at.getName()).isEqualTo("dialect"); assertThat(at.getValue()).isEqualTo("java"); - rule = (RuleDescr) pkg.getRules().get( 1 ); + rule = (RuleDescr) pkg.getRules().get(1); assertThat(rule.getName()).isEqualTo("baz"); - at = (AttributeDescr) rule.getAttributes().get( "dialect" ); + at = (AttributeDescr) rule.getAttributes().get("dialect"); assertThat(at.getName()).isEqualTo("dialect"); assertThat(at.getValue()).isEqualTo("mvel"); - at = (AttributeDescr) rule.getAttributes().get( "agenda-group" ); + at = (AttributeDescr) rule.getAttributes().get("agenda-group"); assertThat(at.getName()).isEqualTo("agenda-group"); assertThat(at.getValue()).isEqualTo("x"); - } @Test - public void parse_StatementOrdering1() throws Exception { + void statementOrdering1() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "statement_ordering_1.drl" ); + "statement_ordering_1.drl"); - assertThat(pkg.getRules().size()).isEqualTo(2); + assertThat(pkg.getRules()).hasSize(2); assertThat(((RuleDescr) pkg.getRules().get(0)).getName()).isEqualTo("foo"); assertThat(((RuleDescr) pkg.getRules().get(1)).getName()).isEqualTo("bar"); - assertThat(pkg.getFunctions().size()).isEqualTo(2); + assertThat(pkg.getFunctions()).hasSize(2); assertThat(((FunctionDescr) pkg.getFunctions().get(0)).getName()).isEqualTo("cheeseIt"); assertThat(((FunctionDescr) pkg.getFunctions().get(1)).getName()).isEqualTo("uncheeseIt"); - assertThat(pkg.getImports().size()).isEqualTo(4); + assertThat(pkg.getImports()).hasSize(4); assertThat(((ImportDescr) pkg.getImports().get(0)).getTarget()).isEqualTo("im.one"); assertThat(((ImportDescr) pkg.getImports().get(1)).getTarget()).isEqualTo("im.two"); assertThat(((ImportDescr) pkg.getImports().get(2)).getTarget()).isEqualTo("im.three"); @@ -2090,42 +2065,41 @@ public void parse_StatementOrdering1() throws Exception { } @Test - public void parse_RuleNamesStartingWithNumbers() throws Exception { + void ruleNamesStartingWithNumbers() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "rule_names_number_prefix.drl" ); + "rule_names_number_prefix.drl"); - assertThat(pkg.getRules().size()).isEqualTo(2); + assertThat(pkg.getRules()).hasSize(2); assertThat(((RuleDescr) pkg.getRules().get(0)).getName()).isEqualTo("1. Do Stuff!"); assertThat(((RuleDescr) pkg.getRules().get(1)).getName()).isEqualTo("2. Do More Stuff!"); } @Test - public void parse_EvalWithNewline() throws Exception { + void evalWithNewline() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "eval_with_newline.drl"); - + "eval_with_newline.drl"); } @Test - public void parse_EndPosition() throws Exception { + void endPosition() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "test_EndPosition.drl" ); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + "test_EndPosition.drl"); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(col.getLine()).isEqualTo(23); assertThat(col.getEndLine()).isEqualTo(25); } @Test - public void parse_GroupBy() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( "groupBy.drl" ); + void groupBy() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile("groupBy.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); final RuleDescr rule = pkg.getRules().get(0); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final GroupByDescr groupBy = (GroupByDescr) outPattern.getSource(); assertThat(groupBy.getGroupingKey()).isEqualToIgnoringWhitespace("$initial"); assertThat(groupBy.getGroupingFunction()).isEqualToIgnoringWhitespace("$p.getName().substring(0, 1)"); @@ -2155,13 +2129,13 @@ public void parse_GroupBy() throws Exception { } @Test - public void parse_QualifiedClassname() throws Exception { + void qualifiedClassname() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "qualified_classname.drl" ); + "qualified_classname.drl"); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); - final PatternDescr p = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr p = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(p.getObjectType()).isEqualTo("com.cheeseco.Cheese"); } @@ -2176,13 +2150,13 @@ void accumulate() { "end"; RuleDescr rule = parseAndGetFirstRuleDescr(drl); - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(out.getObjectType()).isEqualTo("Object"); AccumulateDescr accum = (AccumulateDescr) out.getSource(); assertThat(accum.isExternalFunction()).isTrue(); List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(1); + assertThat(functions).hasSize(1); assertThat(functions.get(0).getFunction()).isEqualTo("average"); assertThat(functions.get(0).getBind()).isEqualTo("$avg"); assertThat(functions.get(0).getParams()[0]).isEqualTo("$age"); @@ -2201,18 +2175,18 @@ void accumulate() { @Test void fromAccumulate() { - final PackageDescr pkg = parseAndGetPackageDescrFromFile("from_accumulate.drl" ); + final PackageDescr pkg = parseAndGetPackageDescrFromFile("from_accumulate.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(accum.getInitCode()).isEqualTo( "int x = 0;"); - assertThat(accum.getActionCode()).isEqualTo( "x++;"); + assertThat(accum.getInitCode()).isEqualTo("int x = 0;"); + assertThat(accum.getActionCode()).isEqualTo("x++;"); assertThat(accum.getReverseCode()).isNull(); - assertThat(accum.getResultCode()).isEqualTo( "new Integer(x)"); + assertThat(accum.getResultCode()).isEqualTo("new Integer(x)"); assertThat(accum.isExternalFunction()).isFalse(); @@ -2229,20 +2203,20 @@ void fromAccumulate() { } @Test - public void parse_AccumulateWithBindings() throws Exception { + void accumulateWithBindings() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulate_with_bindings.drl" ); + "accumulate_with_bindings.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(outPattern.getIdentifier()).isEqualTo( "$counter"); - assertThat(accum.getInitCode()).isEqualTo( "int x = 0;"); - assertThat(accum.getActionCode()).isEqualTo( "x++;"); - assertThat(accum.getResultCode()).isEqualTo( "new Integer(x)"); + assertThat(outPattern.getIdentifier()).isEqualTo("$counter"); + assertThat(accum.getInitCode()).isEqualTo("int x = 0;"); + assertThat(accum.getActionCode()).isEqualTo("x++;"); + assertThat(accum.getResultCode()).isEqualTo("new Integer(x)"); final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); assertThat(pattern.getObjectType()).isEqualTo("Person"); @@ -2253,7 +2227,7 @@ public void parse_AccumulateWithBindings() throws Exception { * - Optional comma delimiting init, action, and result. */ @Test - public void accumulateWithoutOptionalDelimiters() throws Exception { + void accumulateWithoutOptionalDelimiters() { String source = "rule \"AccumulateParserTest\"\n" + "when\n" + " $counter:Integer() from accumulate( $person : Person( age > 21 ),\n" @@ -2262,18 +2236,18 @@ public void accumulateWithoutOptionalDelimiters() throws Exception { + " result( new Integer(x) ) );\n" + "then\n" + "end\n"; - final PackageDescr pkg = parseAndGetPackageDescr( source ); + final PackageDescr pkg = parseAndGetPackageDescr(source); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(outPattern.getIdentifier()).isEqualTo( "$counter"); - assertThat(accum.getInitCode()).isEqualTo( "int x = 0"); - assertThat(accum.getActionCode()).isEqualTo( "x++"); - assertThat(accum.getResultCode()).isEqualTo( "new Integer(x)"); + assertThat(outPattern.getIdentifier()).isEqualTo("$counter"); + assertThat(accum.getInitCode()).isEqualTo("int x = 0"); + assertThat(accum.getActionCode()).isEqualTo("x++"); + assertThat(accum.getResultCode()).isEqualTo("new Integer(x)"); final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); assertThat(pattern.getObjectType()).isEqualTo("Person"); @@ -2283,20 +2257,20 @@ public void accumulateWithoutOptionalDelimiters() throws Exception { * When the accumulate function (e.g. count()) has no arguments. */ @Test - public void accumulateCount() throws Exception { + void accumulateCount() { String source = "rule R when\n" + - " accumulate (\n" + - " Person(), $result : count() " + - " )" + - "then\n" + - "end"; - final PackageDescr pkg = parseAndGetPackageDescr( source ); + " accumulate (\n" + + " Person(), $result : count() " + + " )" + + "then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); assertThat(accum).isNotNull(); @@ -2311,15 +2285,15 @@ public void accumulateCount() throws Exception { } @Test - public void parse_Collect() throws Exception { + void collect() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "collect.drl" ); + "collect.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final CollectDescr collect = (CollectDescr) outPattern.getSource(); final PatternDescr pattern = (PatternDescr) collect.getInputPattern(); @@ -2327,23 +2301,23 @@ public void parse_Collect() throws Exception { } @Test - public void parse_Predicate2() throws Exception { + void predicate2() { // predicates are also prefixed by the eval keyword final RuleDescr rule = parseAndGetFirstRuleDescr( - "rule X when Foo(eval( $var.equals(\"xyz\") )) then end" ); + "rule X when Foo(eval( $var.equals(\"xyz\") )) then end"); - final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - final List< ? > constraints = pattern.getConstraint().getDescrs(); - assertThat(constraints.size()).isEqualTo(1); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final List constraints = pattern.getConstraint().getDescrs(); + assertThat(constraints).hasSize(1); - final ExprConstraintDescr predicate = (ExprConstraintDescr) constraints.get( 0 ); + final ExprConstraintDescr predicate = (ExprConstraintDescr) constraints.get(0); assertThat(predicate.getExpression()).isEqualToIgnoringWhitespace("eval( $var.equals(\"xyz\") )"); } @Test - public void parse_EscapedStrings() throws Exception { + void escapedStrings() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "escaped-string.drl" ); + "escaped-string.drl"); assertThat(rule).isNotNull(); @@ -2351,30 +2325,30 @@ public void parse_EscapedStrings() throws Exception { final String expected = "String s = \"\\\"\\n\\t\\\\\";"; - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( expected); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace(expected); } @Test - public void parse_NestedCEs() throws Exception { + void nestedCEs() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "nested_conditional_elements.drl" ); + "nested_conditional_elements.drl"); assertThat(rule).isNotNull(); final AndDescr root = rule.getLhs(); - final NotDescr not1 = (NotDescr) root.getDescrs().get( 0 ); - final AndDescr and1 = (AndDescr) not1.getDescrs().get( 0 ); + final NotDescr not1 = (NotDescr) root.getDescrs().get(0); + final AndDescr and1 = (AndDescr) not1.getDescrs().get(0); - final PatternDescr state = (PatternDescr) and1.getDescrs().get( 0 ); - final NotDescr not2 = (NotDescr) and1.getDescrs().get( 1 ); - final AndDescr and2 = (AndDescr) not2.getDescrs().get( 0 ); - final PatternDescr person = (PatternDescr) and2.getDescrs().get( 0 ); - final PatternDescr cheese = (PatternDescr) and2.getDescrs().get( 1 ); + final PatternDescr state = (PatternDescr) and1.getDescrs().get(0); + final NotDescr not2 = (NotDescr) and1.getDescrs().get(1); + final AndDescr and2 = (AndDescr) not2.getDescrs().get(0); + final PatternDescr person = (PatternDescr) and2.getDescrs().get(0); + final PatternDescr cheese = (PatternDescr) and2.getDescrs().get(1); - final PatternDescr person2 = (PatternDescr) root.getDescrs().get( 1 ); - final OrDescr or = (OrDescr) root.getDescrs().get( 2 ); - final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get( 0 ); - final PatternDescr cheese3 = (PatternDescr) or.getDescrs().get( 1 ); + final PatternDescr person2 = (PatternDescr) root.getDescrs().get(1); + final OrDescr or = (OrDescr) root.getDescrs().get(2); + final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get(0); + final PatternDescr cheese3 = (PatternDescr) or.getDescrs().get(1); assertThat("State").isEqualTo(state.getObjectType()); assertThat("Person").isEqualTo(person.getObjectType()); @@ -2385,244 +2359,239 @@ public void parse_NestedCEs() throws Exception { } @Test - public void parse_Forall() throws Exception { + void forall() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "forall.drl" ); + "forall.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0 ); + final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0); - assertThat(forall.getDescrs().size()).isEqualTo(2); + assertThat(forall.getDescrs()).hasSize(2); final PatternDescr pattern = forall.getBasePattern(); assertThat(pattern.getObjectType()).isEqualTo("Person"); final List remaining = forall.getRemainingPatterns(); - assertThat(remaining.size()).isEqualTo(1); - final PatternDescr cheese = (PatternDescr) remaining.get( 0 ); + assertThat(remaining).hasSize(1); + final PatternDescr cheese = (PatternDescr) remaining.get(0); assertThat(cheese.getObjectType()).isEqualTo("Cheese"); } @Test - public void parse_ForallWithFrom() throws Exception { + void forallWithFrom() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "forallwithfrom.drl" ); + "forallwithfrom.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get( 0 ); + final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0); - assertThat(forall.getDescrs().size()).isEqualTo(2); + assertThat(forall.getDescrs()).hasSize(2); final PatternDescr pattern = forall.getBasePattern(); assertThat(pattern.getObjectType()).isEqualTo("Person"); assertThat(((FromDescr) pattern.getSource()).getDataSource().toString()).isEqualTo("$village"); final List remaining = forall.getRemainingPatterns(); - assertThat(remaining.size()).isEqualTo(1); - final PatternDescr cheese = (PatternDescr) remaining.get( 0 ); + assertThat(remaining).hasSize(1); + final PatternDescr cheese = (PatternDescr) remaining.get(0); assertThat(cheese.getObjectType()).isEqualTo("Cheese"); assertThat(((FromDescr) cheese.getSource()).getDataSource().toString()).isEqualTo("$cheesery"); } @Test - public void parse_Memberof() throws Exception { + void memberof() { final String text = "rule X when Country( $cities : city )\nPerson( city memberOf $cities )\n then end"; AndDescr descrs = parseAndGetFirstRuleDescr( - text).getLhs(); + text).getLhs(); - assertThat(descrs.getDescrs().size()).isEqualTo(2); - PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 1 ); - ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); + assertThat(descrs.getDescrs()).hasSize(2); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get(1); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get(0); assertThat(fieldConstr.getExpression()).isEqualTo("city memberOf $cities"); } @Test - public void parse_NotMemberof() throws Exception { + void notMemberof() { final String text = "rule X when Country( $cities : city )\nPerson( city not memberOf $cities ) then end\n"; AndDescr descrs = parseAndGetFirstRuleDescr( - text).getLhs(); + text).getLhs(); - assertThat(descrs.getDescrs().size()).isEqualTo(2); - PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 1 ); - ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); + assertThat(descrs.getDescrs()).hasSize(2); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get(1); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get(0); assertThat(fieldConstr.getExpression()).isEqualTo("city not memberOf $cities"); } @Test - public void parse_InOperator() throws Exception { + void inOperator() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "in_operator_test.drl" ); + "in_operator_test.drl"); assertThat(rule).isNotNull(); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "consequence();"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("consequence();"); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + assertThat(rule.getLhs().getDescrs()).hasSize(2); // The first pattern, with 2 restrictions on a single field (plus a // connective) - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); - ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); // the second col, with 2 fields, the first with 2 restrictions, the // second field with one - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); - fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type in ( \"sedan\", \"wagon\" )"); // now the second field - fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 1 ); + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1); assertThat(fld.getExpression()).isEqualTo("age < 3"); - } @Test - public void parse_NotInOperator() throws Exception { + void notInOperator() { final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( - "notin_operator_test.drl" ); + "notin_operator_test.drl"); assertThat(rule).isNotNull(); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "consequence();"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("consequence();"); assertThat(rule.getName()).isEqualTo("simple_rule"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + assertThat(rule.getLhs().getDescrs()).hasSize(2); // The first pattern, with 2 restrictions on a single field (plus a // connective) - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Person"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); - ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); // the second col, with 2 fields, the first with 2 restrictions, the // second field with one - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); - assertThat(pattern.getConstraint().getDescrs().size()).isEqualTo(2); + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); - fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type not in ( \"sedan\", \"wagon\" )"); // now the second field - fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 1 ); + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1); assertThat(fld.getExpression()).isEqualTo("age < 3"); - } @Test - public void parse_CheckOrDescr() throws Exception { + void checkOrDescr() { final String text = "rule X when Person( eval( age == 25 ) || ( eval( name.equals( \"bob\" ) ) && eval( age == 30 ) ) ) then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); - assertThat(pattern.getDescrs().size()).isEqualTo(1); + assertThat(pattern.getDescrs()).hasSize(1); assertThat(AndDescr.class).isEqualTo(pattern.getConstraint().getClass()); assertThat(pattern.getConstraint().getDescrs().get(0).getClass()).isEqualTo(ExprConstraintDescr.class); - } @Test - public void parse_ConstraintAndConnective() throws Exception { + void constraintAndConnective() { final String text = "rule X when Person( age < 42 && location==\"atlanta\") then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 && location==\"atlanta\""); } @Test - public void parse_ConstraintOrConnective() throws Exception { + void constraintOrConnective() { final String text = "rule X when Person( age < 42 || location==\"atlanta\") then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 || location==\"atlanta\""); } @Test - public void parse_Restrictions() throws Exception { + void restrictions() { final String text = "rule X when Foo( bar > 1 || == 1 ) then end\n"; AndDescr descrs = (AndDescr) parseAndGetFirstRuleDescr( - text ).getLhs(); + text).getLhs(); - assertThat(descrs.getDescrs().size()).isEqualTo(1); - PatternDescr pat = (PatternDescr) descrs.getDescrs().get( 0 ); - ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get( 0 ); + assertThat(descrs.getDescrs()).hasSize(1); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get(0); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get(0); assertThat(fieldConstr.getExpression()).isEqualTo("bar > 1 || == 1"); } @Test - public void parse_Semicolon() throws Exception { + void semicolon() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "semicolon.drl" ); - - + "semicolon.drl"); assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); - assertThat(pkg.getGlobals().size()).isEqualTo(1); - assertThat(pkg.getRules().size()).isEqualTo(3); + assertThat(pkg.getGlobals()).hasSize(1); + assertThat(pkg.getRules()).hasSize(3); - final RuleDescr rule1 = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule1.getLhs().getDescrs().size()).isEqualTo(2); + final RuleDescr rule1 = (RuleDescr) pkg.getRules().get(0); + assertThat(rule1.getLhs().getDescrs()).hasSize(2); - final RuleDescr query1 = (RuleDescr) pkg.getRules().get( 1 ); - assertThat(query1.getLhs().getDescrs().size()).isEqualTo(3); + final RuleDescr query1 = (RuleDescr) pkg.getRules().get(1); + assertThat(query1.getLhs().getDescrs()).hasSize(3); - final RuleDescr rule2 = (RuleDescr) pkg.getRules().get( 2 ); - assertThat(rule2.getLhs().getDescrs().size()).isEqualTo(2); + final RuleDescr rule2 = (RuleDescr) pkg.getRules().get(2); + assertThat(rule2.getLhs().getDescrs()).hasSize(2); } @Test - public void parse_Eval() throws Exception { + void eval() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "eval_parsing.drl" ); + "eval_parsing.drl"); assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); - final RuleDescr rule1 = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule1.getLhs().getDescrs().size()).isEqualTo(1); + final RuleDescr rule1 = (RuleDescr) pkg.getRules().get(0); + assertThat(rule1.getLhs().getDescrs()).hasSize(1); } @Test - public void parse_AccumulateReverse() throws Exception { + void accumulateReverse() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulateReverse.drl" ); + "accumulateReverse.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); final AccumulateDescr accum = (AccumulateDescr) out.getSource(); - assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;" - ); - assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;" - ); - assertThat(accum.getReverseCode()).isEqualToIgnoringWhitespace( "x--;" - ); - assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)" - ); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace("int x = 0 ;" + ); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace("x++;" + ); + assertThat(accum.getReverseCode()).isEqualToIgnoringWhitespace("x--;" + ); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace("new Integer(x)" + ); assertThat(accum.isExternalFunction()).isFalse(); final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); @@ -2630,20 +2599,20 @@ public void parse_AccumulateReverse() throws Exception { } @Test - public void parse_AccumulateExternalFunction() throws Exception { + void accumulateExternalFunction() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulateExternalFunction.drl" ); + "accumulateExternalFunction.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); final AccumulateDescr accum = (AccumulateDescr) out.getSource(); - assertThat(accum.getFunctions().get( 0 ).getParams()[0]).isEqualToIgnoringWhitespace( "$age" - ); - assertThat(accum.getFunctions().get( 0 ).getFunction()).isEqualToIgnoringWhitespace( "average" - ); + assertThat(accum.getFunctions().get(0).getParams()[0]).isEqualToIgnoringWhitespace("$age" + ); + assertThat(accum.getFunctions().get(0).getFunction()).isEqualToIgnoringWhitespace("average" + ); assertThat(accum.isExternalFunction()).isTrue(); final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); @@ -2651,15 +2620,15 @@ public void parse_AccumulateExternalFunction() throws Exception { } @Test - public void parse_CollectWithNestedFrom() throws Exception { + void collectWithNestedFrom() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "collect_with_nested_from.drl" ); + "collect_with_nested_from.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); final CollectDescr collect = (CollectDescr) out.getSource(); PatternDescr person = (PatternDescr) collect.getInputPattern(); @@ -2672,15 +2641,15 @@ public void parse_CollectWithNestedFrom() throws Exception { } @Test - public void parse_AccumulateWithNestedFrom() throws Exception { + void accumulateWithNestedFrom() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulate_with_nested_from.drl" ); + "accumulate_with_nested_from.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); final AccumulateDescr accumulate = (AccumulateDescr) out.getSource(); PatternDescr person = (PatternDescr) accumulate.getInputPattern(); @@ -2693,22 +2662,22 @@ public void parse_AccumulateWithNestedFrom() throws Exception { } @Test - public void parse_AccumulateMultipleFunctions() throws Exception { + void accumulateMultipleFunctions() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulateMultipleFunctions.drl" ); + "accumulateMultipleFunctions.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(out.getObjectType()).isEqualTo("Object"); AccumulateDescr accum = (AccumulateDescr) out.getSource(); assertThat(accum.isExternalFunction()).isTrue(); List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(3); + assertThat(functions).hasSize(3); assertThat(functions.get(0).getFunction()).isEqualTo("average"); assertThat(functions.get(0).getBind()).isEqualTo("$a1"); assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); @@ -2726,7 +2695,7 @@ public void parse_AccumulateMultipleFunctions() throws Exception { } @Test - public void parse_AccumulateMnemonic() throws Exception { + void accumulateMnemonic() { String drl = "package org.drools.mvel.compiler\n" + "rule \"Accumulate 1\"\n" + "when\n" + @@ -2735,20 +2704,20 @@ public void parse_AccumulateMnemonic() throws Exception { "then\n" + "end\n"; PackageDescr pkg = parseAndGetPackageDescr( - drl ); + drl); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(out.getObjectType()).isEqualTo("Object"); AccumulateDescr accum = (AccumulateDescr) out.getSource(); assertThat(accum.isExternalFunction()).isTrue(); List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(1); + assertThat(functions).hasSize(1); assertThat(functions.get(0).getFunction()).isEqualTo("average"); assertThat(functions.get(0).getBind()).isEqualTo("$a1"); assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); @@ -2758,7 +2727,7 @@ public void parse_AccumulateMnemonic() throws Exception { } @Test - public void parse_AccumulateMnemonic2() throws Exception { + void accumulateMnemonic2() { String drl = "package org.drools.mvel.compiler\n" + "rule \"Accumulate 1\"\n" + "when\n" + @@ -2767,20 +2736,20 @@ public void parse_AccumulateMnemonic2() throws Exception { "then\n" + "end\n"; PackageDescr pkg = parseAndGetPackageDescr( - drl ); + drl); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(out.getObjectType()).isEqualTo("Number"); AccumulateDescr accum = (AccumulateDescr) out.getSource(); assertThat(accum.isExternalFunction()).isTrue(); List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(1); + assertThat(functions).hasSize(1); assertThat(functions.get(0).getFunction()).isEqualTo("average"); assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); @@ -2789,7 +2758,7 @@ public void parse_AccumulateMnemonic2() throws Exception { } @Test - public void parse_ImportAccumulate() throws Exception { + void importAccumulate() { String drl = "package org.drools.mvel.compiler\n" + "import acc foo.Bar baz\n" + "import accumulate foo.Bar2 baz2\n" + @@ -2801,9 +2770,9 @@ public void parse_ImportAccumulate() throws Exception { "then\n" + "end\n"; PackageDescr pkg = parseAndGetPackageDescr( - drl ); + drl); - assertThat(pkg.getAccumulateImports().size()).isEqualTo(2); + assertThat(pkg.getAccumulateImports()).hasSize(2); AccumulateImportDescr imp = (AccumulateImportDescr) pkg.getAccumulateImports().get(0); assertThat(imp.getTarget()).isEqualTo("foo.Bar"); assertThat(imp.getFunctionName()).isEqualTo("baz"); @@ -2812,18 +2781,18 @@ public void parse_ImportAccumulate() throws Exception { assertThat(imp.getTarget()).isEqualTo("foo.Bar2"); assertThat(imp.getFunctionName()).isEqualTo("baz2"); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(out.getObjectType()).isEqualTo("Object"); AccumulateDescr accum = (AccumulateDescr) out.getSource(); assertThat(accum.isExternalFunction()).isTrue(); List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(2); + assertThat(functions).hasSize(2); assertThat(functions.get(0).getFunction()).isEqualTo("baz"); assertThat(functions.get(0).getBind()).isEqualTo("$v1"); assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); @@ -2837,25 +2806,25 @@ public void parse_ImportAccumulate() throws Exception { } @Test - public void parse_AccumulateMultipleFunctionsConstraint() throws Exception { + void accumulateMultipleFunctionsConstraint() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulateMultipleFunctionsConstraint.drl" ); + "accumulateMultipleFunctionsConstraint.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(out.getObjectType()).isEqualTo("Object"); - assertThat(out.getConstraint().getDescrs().size()).isEqualTo(2); + assertThat(out.getConstraint().getDescrs()).hasSize(2); assertThat(out.getConstraint().getDescrs().get(0).toString()).isEqualTo("$a1 > 10 && $M1 <= 100"); assertThat(out.getConstraint().getDescrs().get(1).toString()).isEqualTo("$m1 == 5"); AccumulateDescr accum = (AccumulateDescr) out.getSource(); assertThat(accum.isExternalFunction()).isTrue(); List functions = accum.getFunctions(); - assertThat(functions.size()).isEqualTo(3); + assertThat(functions).hasSize(3); assertThat(functions.get(0).getFunction()).isEqualTo("average"); assertThat(functions.get(0).getBind()).isEqualTo("$a1"); assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); @@ -2873,212 +2842,204 @@ public void parse_AccumulateMultipleFunctionsConstraint() throws Exception { } @Test - public void parse_OrCE() throws Exception { + void orCE() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "or_ce.drl" ); + "or_ce.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(2); - final PatternDescr person = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr person = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(person.getObjectType()).isEqualTo("Person"); assertThat(person.getIdentifier()).isEqualTo("$p"); - final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get( 1 ); - assertThat(or.getDescrs().size()).isEqualTo(2); + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(1); + assertThat(or.getDescrs()).hasSize(2); - final PatternDescr cheese1 = (PatternDescr) or.getDescrs().get( 0 ); + final PatternDescr cheese1 = (PatternDescr) or.getDescrs().get(0); assertThat(cheese1.getObjectType()).isEqualTo("Cheese"); assertThat(cheese1.getIdentifier()).isEqualTo("$c"); - final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get( 1 ); + final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get(1); assertThat(cheese2.getObjectType()).isEqualTo("Cheese"); assertThat(cheese2.getIdentifier()).isNull(); } @Test - public void parse_RuleSingleLine() throws Exception { + void ruleSingleLine() { final String text = "rule \"another test\" salience 10 when eval( true ) then System.out.println(1); end"; RuleDescr rule = parseAndGetFirstRuleDescr( - text ); + text); assertThat(rule.getName()).isEqualTo("another test"); - assertThat((String)rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1); "); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1); "); } @Test - public void parse_RuleTwoLines() throws Exception { + void ruleTwoLines() { final String text = "rule \"another test\" salience 10 when eval( true ) then System.out.println(1);\n end"; RuleDescr rule = parseAndGetFirstRuleDescr( - text ); + text); assertThat(rule.getName()).isEqualTo("another test"); - assertThat((String)rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1);\n "); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1);\n "); } @Test - public void parse_RuleParseLhs3() throws Exception { + void ruleParseLhs3() { final String text = "rule X when (or\nnot Person()\n(and Cheese()\nMeat()\nWine())) then end"; AndDescr pattern = parseAndGetFirstRuleDescr( - text ).getLhs(); - - assertThat(pattern.getDescrs().size()).isEqualTo(1); - OrDescr or = (OrDescr) pattern.getDescrs().get( 0 ); - assertThat(or.getDescrs().size()).isEqualTo(2); - NotDescr not = (NotDescr) or.getDescrs().get( 0 ); - AndDescr and = (AndDescr) or.getDescrs().get( 1 ); - assertThat(not.getDescrs().size()).isEqualTo(1); - PatternDescr person = (PatternDescr) not.getDescrs().get( 0 ); + text).getLhs(); + + assertThat(pattern.getDescrs()).hasSize(1); + OrDescr or = (OrDescr) pattern.getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); + NotDescr not = (NotDescr) or.getDescrs().get(0); + AndDescr and = (AndDescr) or.getDescrs().get(1); + assertThat(not.getDescrs()).hasSize(1); + PatternDescr person = (PatternDescr) not.getDescrs().get(0); assertThat(person.getObjectType()).isEqualTo("Person"); - assertThat(and.getDescrs().size()).isEqualTo(3); - PatternDescr cheese = (PatternDescr) and.getDescrs().get( 0 ); + assertThat(and.getDescrs()).hasSize(3); + PatternDescr cheese = (PatternDescr) and.getDescrs().get(0); assertThat(cheese.getObjectType()).isEqualTo("Cheese"); - PatternDescr meat = (PatternDescr) and.getDescrs().get( 1 ); + PatternDescr meat = (PatternDescr) and.getDescrs().get(1); assertThat(meat.getObjectType()).isEqualTo("Meat"); - PatternDescr wine = (PatternDescr) and.getDescrs().get( 2 ); + PatternDescr wine = (PatternDescr) and.getDescrs().get(2); assertThat(wine.getObjectType()).isEqualTo("Wine"); - } @Test - public void parse_AccumulateMultiPattern() throws Exception { + void accumulateMultiPattern() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "accumulate_multi_pattern.drl" ); + "accumulate_multi_pattern.drl"); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace( "$counter" - ); - assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace( "int x = 0 ;" - ); - assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace( "x++;" - ); - assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace( "new Integer(x)" - ); + assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace("$counter" + ); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace("int x = 0 ;" + ); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace("x++;" + ); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace("new Integer(x)" + ); final AndDescr and = (AndDescr) accum.getInput(); - assertThat(and.getDescrs().size()).isEqualTo(2); - final PatternDescr person = (PatternDescr) and.getDescrs().get( 0 ); - final PatternDescr cheese = (PatternDescr) and.getDescrs().get( 1 ); + assertThat(and.getDescrs()).hasSize(2); + final PatternDescr person = (PatternDescr) and.getDescrs().get(0); + final PatternDescr cheese = (PatternDescr) and.getDescrs().get(1); assertThat(person.getObjectType()).isEqualTo("Person"); assertThat(cheese.getObjectType()).isEqualTo("Cheese"); } @Test - public void parse_PluggableOperators() throws Exception { + void pluggableOperators() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "pluggable_operators.drl" ); - + "pluggable_operators.drl"); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(5); - assertThat(pkg.getRules().size()).isEqualTo(1); - final RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(5); - - final PatternDescr eventA = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr eventA = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(eventA.getIdentifier()).isEqualTo("$a"); assertThat(eventA.getObjectType()).isEqualTo("EventA"); - final PatternDescr eventB = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + final PatternDescr eventB = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(eventB.getIdentifier()).isEqualTo("$b"); assertThat(eventB.getObjectType()).isEqualTo("EventB"); - assertThat(eventB.getConstraint().getDescrs().size()).isEqualTo(1); - assertThat(eventB.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(eventB.getConstraint().getDescrs()).hasSize(1); + assertThat(eventB.getConstraint().getDescrs()).hasSize(1); - final ExprConstraintDescr fcdB = (ExprConstraintDescr) eventB.getConstraint().getDescrs().get( 0 ); + final ExprConstraintDescr fcdB = (ExprConstraintDescr) eventB.getConstraint().getDescrs().get(0); assertThat(fcdB.getExpression()).isEqualTo("this after[1,10] $a || this not after[15,20] $a"); - final PatternDescr eventC = (PatternDescr) rule.getLhs().getDescrs().get( 2 ); + final PatternDescr eventC = (PatternDescr) rule.getLhs().getDescrs().get(2); assertThat(eventC.getIdentifier()).isEqualTo("$c"); assertThat(eventC.getObjectType()).isEqualTo("EventC"); - assertThat(eventC.getConstraint().getDescrs().size()).isEqualTo(1); - final ExprConstraintDescr fcdC = (ExprConstraintDescr) eventC.getConstraint().getDescrs().get( 0 ); + assertThat(eventC.getConstraint().getDescrs()).hasSize(1); + final ExprConstraintDescr fcdC = (ExprConstraintDescr) eventC.getConstraint().getDescrs().get(0); assertThat(fcdC.getExpression()).isEqualTo("this finishes $b"); - final PatternDescr eventD = (PatternDescr) rule.getLhs().getDescrs().get( 3 ); + final PatternDescr eventD = (PatternDescr) rule.getLhs().getDescrs().get(3); assertThat(eventD.getIdentifier()).isEqualTo("$d"); assertThat(eventD.getObjectType()).isEqualTo("EventD"); - assertThat(eventD.getConstraint().getDescrs().size()).isEqualTo(1); - final ExprConstraintDescr fcdD = (ExprConstraintDescr) eventD.getConstraint().getDescrs().get( 0 ); + assertThat(eventD.getConstraint().getDescrs()).hasSize(1); + final ExprConstraintDescr fcdD = (ExprConstraintDescr) eventD.getConstraint().getDescrs().get(0); assertThat(fcdD.getExpression()).isEqualTo("this not starts $a"); - final PatternDescr eventE = (PatternDescr) rule.getLhs().getDescrs().get( 4 ); + final PatternDescr eventE = (PatternDescr) rule.getLhs().getDescrs().get(4); assertThat(eventE.getIdentifier()).isEqualTo("$e"); assertThat(eventE.getObjectType()).isEqualTo("EventE"); - assertThat(eventE.getConstraint().getDescrs().size()).isEqualTo(1); + assertThat(eventE.getConstraint().getDescrs()).hasSize(1); - ExprConstraintDescr fcdE = (ExprConstraintDescr) eventE.getConstraint().getDescrs().get( 0 ); + 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"); } @Test - public void parse_RuleMetadata() throws Exception { + void ruleMetadata() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "Rule_with_Metadata.drl" ); - + "Rule_with_Metadata.drl"); // @fooAttribute(barValue) // @fooAtt2(barVal2) - RuleDescr rule = pkg.getRules().get( 0 ); - assertThat(rule.getAnnotationNames().contains("fooMeta1")).isTrue(); + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getAnnotationNames()).contains("fooMeta1"); assertThat(rule.getAnnotation("fooMeta1").getValue()).isEqualTo("barVal1"); - assertThat(rule.getAnnotationNames().contains("fooMeta2")).isTrue(); + assertThat(rule.getAnnotationNames()).contains("fooMeta2"); assertThat(rule.getAnnotation("fooMeta2").getValue()).isEqualTo("barVal2"); - assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace( "System.out.println(\"Consequence\");" - ); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(\"Consequence\");" + ); } @Test - public void parse_RuleExtends() throws Exception { + void ruleExtends() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "Rule_with_Extends.drl" ); + "Rule_with_Extends.drl"); - - - RuleDescr rule = pkg.getRules().get( 0 ); + RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getParentName() != null).isTrue(); assertThat(rule.getParentName()).isEqualTo("rule1"); AndDescr lhs = rule.getLhs(); assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(1); + assertThat(lhs.getDescrs()).hasSize(1); - PatternDescr pattern = (PatternDescr) lhs.getDescrs().get( 0 ); + PatternDescr pattern = (PatternDescr) lhs.getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("foo"); assertThat(pattern.getIdentifier()).isEqualTo("$foo"); - } @Test - public void parse_TypeDeclarationWithFields() throws Exception { + void typeDeclarationWithFields() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "declare_type_with_fields.drl" ); - + "declare_type_with_fields.drl"); List td = pkg.getTypeDeclarations(); - assertThat(td.size()).isEqualTo(3); + assertThat(td).hasSize(3); - TypeDeclarationDescr d = td.get( 0 ); + TypeDeclarationDescr d = td.get(0); assertThat(d.getTypeName()).isEqualTo("SomeFact"); - assertThat(d.getFields().size()).isEqualTo(2); - assertThat(d.getFields().containsKey("name")).isTrue(); - assertThat(d.getFields().containsKey("age")).isTrue(); + assertThat(d.getFields()).hasSize(2); + assertThat(d.getFields()).containsKey("name"); + assertThat(d.getFields()).containsKey("age"); - TypeFieldDescr f = d.getFields().get("name" ); + TypeFieldDescr f = d.getFields().get("name"); assertThat(f.getPattern().getObjectType()).isEqualTo("String"); - f = d.getFields().get( "age" ); + f = d.getFields().get("age"); assertThat(f.getPattern().getObjectType()).isEqualTo("Integer"); - d = td.get( 1 ); + d = td.get(1); assertThat(d.getTypeName()).isEqualTo("AnotherFact"); - TypeDeclarationDescr type = td.get( 2 ); + TypeDeclarationDescr type = td.get(2); assertThat(type.getTypeName()).isEqualTo("Person"); assertThat(type.getAnnotation("role").getValue()).isEqualTo("fact"); @@ -3086,92 +3047,88 @@ public void parse_TypeDeclarationWithFields() throws Exception { assertThat(type.getAnnotation("doc").getValue("author")).isEqualTo("\"Bob\""); assertThat(type.getAnnotation("doc").getValue("date")).isEqualTo("Calendar.getInstance().getDate()"); - assertThat(type.getFields().size()).isEqualTo(2); - TypeFieldDescr field = type.getFields().get( "name" ); + assertThat(type.getFields()).hasSize(2); + TypeFieldDescr field = type.getFields().get("name"); assertThat(field.getFieldName()).isEqualTo("name"); assertThat(field.getPattern().getObjectType()).isEqualTo("String"); assertThat(field.getInitExpr()).isEqualTo("\"John Doe\""); assertThat(field.getAnnotation("length").getValue("max")).isEqualTo("50"); - assertThat( field.getAnnotation( "key" ) ).isNotNull(); + assertThat(field.getAnnotation("key")).isNotNull(); - field = type.getFields().get( "age" ); + field = type.getFields().get("age"); assertThat(field.getFieldName()).isEqualTo("age"); assertThat(field.getPattern().getObjectType()).isEqualTo("int"); assertThat(field.getInitExpr()).isEqualTo("-1"); assertThat(field.getAnnotation("ranged").getValue("min")).isEqualTo("0"); assertThat(field.getAnnotation("ranged").getValue("max")).isEqualTo("150"); assertThat(field.getAnnotation("ranged").getValue("unknown")).isEqualTo("-1"); - } @Test - public void parse_QualifiedTypeDeclaration() throws Exception { + void qualifiedTypeDeclaration() { final PackageDescr pkg = parseAndGetPackageDescrFromFile( - "qualified_type_declaration.drl" ); + "qualified_type_declaration.drl"); - TypeDeclarationDescr someFact = pkg.getTypeDeclarations().get( 0 ); + TypeDeclarationDescr someFact = pkg.getTypeDeclarations().get(0); assertThat(someFact.getTypeName()).isEqualTo("SomeFact"); assertThat(someFact.getNamespace()).isEqualTo("com.sample1"); - EnumDeclarationDescr color = pkg.getEnumDeclarations().get( 0 ); + EnumDeclarationDescr color = pkg.getEnumDeclarations().get(0); assertThat(color.getTypeName()).isEqualTo("Color"); assertThat(color.getNamespace()).isEqualTo("com.sample2"); } @Test - public void parenthesesOneLevelNestWithThreeSiblings() throws Exception { - final PackageDescr pkg = parseAndGetPackageDescrFromFile( "Rule_with_nested_LHS.drl" ); - + void parenthesesOneLevelNestWithThreeSiblings() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile("Rule_with_nested_LHS.drl"); - - RuleDescr rule = pkg.getRules().get( 0 ); + RuleDescr rule = pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("test"); AndDescr lhs = rule.getLhs(); assertThat(lhs).isNotNull(); - assertThat(lhs.getDescrs().size()).isEqualTo(2); + assertThat(lhs.getDescrs()).hasSize(2); - PatternDescr a = (PatternDescr) lhs.getDescrs().get( 0 ); + PatternDescr a = (PatternDescr) lhs.getDescrs().get(0); assertThat(a.getObjectType()).isEqualTo("A"); - OrDescr or = (OrDescr) lhs.getDescrs().get( 1 ); - assertThat(or.getDescrs().size()).isEqualTo(3); + OrDescr or = (OrDescr) lhs.getDescrs().get(1); + assertThat(or.getDescrs()).hasSize(3); - AndDescr and1 = (AndDescr) or.getDescrs().get( 0 ); - assertThat(and1.getDescrs().size()).isEqualTo(2); - PatternDescr b = (PatternDescr) and1.getDescrs().get( 0 ); - PatternDescr c = (PatternDescr) and1.getDescrs().get( 1 ); + AndDescr and1 = (AndDescr) or.getDescrs().get(0); + assertThat(and1.getDescrs()).hasSize(2); + PatternDescr b = (PatternDescr) and1.getDescrs().get(0); + PatternDescr c = (PatternDescr) and1.getDescrs().get(1); assertThat(b.getObjectType()).isEqualTo("B"); assertThat(c.getObjectType()).isEqualTo("C"); - AndDescr and2 = (AndDescr) or.getDescrs().get( 1 ); - assertThat(and2.getDescrs().size()).isEqualTo(2); - PatternDescr d = (PatternDescr) and2.getDescrs().get( 0 ); - PatternDescr e = (PatternDescr) and2.getDescrs().get( 1 ); + AndDescr and2 = (AndDescr) or.getDescrs().get(1); + assertThat(and2.getDescrs()).hasSize(2); + PatternDescr d = (PatternDescr) and2.getDescrs().get(0); + PatternDescr e = (PatternDescr) and2.getDescrs().get(1); assertThat(d.getObjectType()).isEqualTo("D"); assertThat(e.getObjectType()).isEqualTo("E"); - AndDescr and3 = (AndDescr) or.getDescrs().get( 2 ); - assertThat(and3.getDescrs().size()).isEqualTo(2); - PatternDescr f = (PatternDescr) and3.getDescrs().get( 0 ); - PatternDescr g = (PatternDescr) and3.getDescrs().get( 1 ); + AndDescr and3 = (AndDescr) or.getDescrs().get(2); + assertThat(and3.getDescrs()).hasSize(2); + PatternDescr f = (PatternDescr) and3.getDescrs().get(0); + PatternDescr g = (PatternDescr) and3.getDescrs().get(1); assertThat(f.getObjectType()).isEqualTo("F"); assertThat(g.getObjectType()).isEqualTo("G"); } @Test - public void parse_EntryPoint() throws Exception { + void entryPoint() { final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point StreamA then end"; PackageDescr pkg = parseAndGetPackageDescr( - text ); - + text); - RuleDescr rule = pkg.getRules().get( 0 ); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); assertThat(pattern.getSource()).isNotNull(); @@ -3180,18 +3137,17 @@ public void parse_EntryPoint() throws Exception { } @Test - public void parse_EntryPoint2() throws Exception { + void entryPoint2() { final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point \"StreamA\" then end"; PackageDescr pkg = parseAndGetPackageDescr( - text ); + text); + RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); - RuleDescr rule = pkg.getRules().get( 0 ); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); - - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); assertThat(pattern.getSource()).isNotNull(); @@ -3200,283 +3156,272 @@ public void parse_EntryPoint2() throws Exception { } @Test - public void parse_SlidingWindow() throws Exception { + void slidingWindow() { final String text = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end"; - PackageDescr pkg = parseAndGetPackageDescr( text ); - + PackageDescr pkg = parseAndGetPackageDescr(text); - RuleDescr rule = pkg.getRules().get( 0 ); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); List behaviors = pattern.getBehaviors(); assertThat(behaviors).isNotNull(); - assertThat(behaviors.size()).isEqualTo(1); - BehaviorDescr descr = behaviors.get( 0 ); + assertThat(behaviors).hasSize(1); + BehaviorDescr descr = behaviors.get(0); assertThat(descr.getType()).isEqualTo("window"); assertThat(descr.getSubType()).isEqualTo("length"); assertThat(descr.getParameters().get(0)).isEqualTo("10"); } @Test - public void parse_RuleOldSyntax1() throws Exception { + void ruleOldSyntax1() { final String source = "rule \"Test\" when ( not $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; PackageDescr pkg = parseAndGetPackageDescr( - source ); + source); - - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("Test"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - assertThat(((NotDescr) rule.getLhs().getDescrs().get(0)).getDescrs().size()).isEqualTo(1); - NotDescr notDescr = (NotDescr) rule.getLhs().getDescrs().get( 0 ); - PatternDescr patternDescr = (PatternDescr) notDescr.getDescrs().get( 0 ); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + assertThat(((NotDescr) rule.getLhs().getDescrs().get(0)).getDescrs()).hasSize(1); + NotDescr notDescr = (NotDescr) rule.getLhs().getDescrs().get(0); + PatternDescr patternDescr = (PatternDescr) notDescr.getDescrs().get(0); assertThat(patternDescr.getIdentifier()).isEqualTo("$r"); - assertThat(patternDescr.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get( 0 ); + assertThat(patternDescr.getDescrs()).hasSize(1); + ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get(0); assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); } @Test - public void parse_RuleOldSyntax2() throws Exception { + void ruleOldSyntax2() { final String source = "rule \"Test\" when ( $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; PackageDescr pkg = parseAndGetPackageDescr( - source ); + source); - - RuleDescr rule = (RuleDescr) pkg.getRules().get( 0 ); + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("Test"); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(1); - PatternDescr patternDescr = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + PatternDescr patternDescr = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(patternDescr.getIdentifier()).isEqualTo("$r"); - assertThat(patternDescr.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get( 0 ); + assertThat(patternDescr.getDescrs()).hasSize(1); + ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get(0); assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); } @Test - public void parse_TypeWithMetaData() throws Exception { + void typeWithMetaData() { PackageDescr pkg = parseAndGetPackageDescrFromFile( - "type_with_meta.drl" ); - - + "type_with_meta.drl"); final List declarations = pkg.getTypeDeclarations(); - assertThat(declarations.size()).isEqualTo(3); + assertThat(declarations).hasSize(3); } @Test - public void parse_NullConstraints() throws Exception { + void nullConstraints() { final String text = "rule X when Person( name == null ) then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); - assertThat(pattern.getDescrs().size()).isEqualTo(1); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(fcd.getExpression()).isEqualTo("name == null"); assertThat(fcd.getPosition()).isEqualTo(0); assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); } @Test - public void parse_PositionalConstraintsOnly() throws Exception { + void positionalConstraintsOnly() { final String text = "rule X when Person( \"Mark\", 42; ) then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); - assertThat(pattern.getDescrs().size()).isEqualTo(2); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(2); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); assertThat(fcd.getPosition()).isEqualTo(0); assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); - fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + fcd = (ExprConstraintDescr) pattern.getDescrs().get(1); assertThat(fcd.getExpression()).isEqualTo("42"); assertThat(fcd.getPosition()).isEqualTo(1); assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); } @Test - public void parse_IsQuery() throws Exception { + void isQuery() { final String text = "rule X when ?person( \"Mark\", 42; ) then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); assertThat(pattern.isQuery()).isTrue(); - assertThat(pattern.getDescrs().size()).isEqualTo(2); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(2); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); assertThat(fcd.getPosition()).isEqualTo(0); assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); - fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + fcd = (ExprConstraintDescr) pattern.getDescrs().get(1); assertThat(fcd.getExpression()).isEqualTo("42"); assertThat(fcd.getPosition()).isEqualTo(1); assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); } @Test - public void parse_FromFollowedByQuery() throws Exception { + void fromFollowedByQuery() { // the 'from' expression requires a ";" to disambiguate the "?" // prefix for queries from the ternary operator "? :" final String text = "rule X when Cheese() from $cheesery ?person( \"Mark\", 42; ) then end"; RuleDescr rule = parseAndGetFirstRuleDescr( - text ); - + text); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Cheese"); assertThat(pattern.getSource().getText()).isEqualTo("from $cheesery"); assertThat(pattern.isQuery()).isFalse(); - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(pattern.getObjectType()).isEqualTo("person"); assertThat(pattern.isQuery()).isTrue(); - } @Test - public void parse_FromWithTernaryFollowedByQuery() throws Exception { + void fromWithTernaryFollowedByQuery() { // the 'from' expression requires a ";" to disambiguate the "?" // prefix for queries from the ternary operator "? :" final String text = "rule X when Cheese() from (isFull ? $cheesery : $market) ?person( \"Mark\", 42; ) then end"; RuleDescr rule = parseAndGetFirstRuleDescr( - text ); - + text); - PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Cheese"); assertThat(pattern.getSource().getText()).isEqualToIgnoringWhitespace("from (isFull ? $cheesery : $market)"); assertThat(pattern.isQuery()).isFalse(); - pattern = (PatternDescr) rule.getLhs().getDescrs().get( 1 ); + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); assertThat(pattern.getObjectType()).isEqualTo("person"); assertThat(pattern.isQuery()).isTrue(); - } @Test - public void parse_MultiValueAnnotationsBackwardCompatibility() throws Exception { + void multiValueAnnotationsBackwardCompatibility() { // multiple values with no keys are parsed as a single value final String text = "rule X @ann1( val1, val2 ) @ann2( \"val1\", \"val2\" ) when then end"; RuleDescr rule = parseAndGetFirstRuleDescr( - text ); + text); - AnnotationDescr ann = rule.getAnnotation("ann1" ); + AnnotationDescr ann = rule.getAnnotation("ann1"); assertThat(ann).isNotNull(); assertThat(ann.getValue()).isEqualTo("val1, val2"); - ann = rule.getAnnotation( "ann2" ); + ann = rule.getAnnotation("ann2"); assertThat(ann).isNotNull(); assertThat(ann.getValue()).isEqualTo("\"val1\", \"val2\""); assertThat(ann.getSingleValueAsString()).isEqualTo("\"val1\", \"val2\""); } @Test - public void parse_PositionalsAndNamedConstraints() throws Exception { + void positionalsAndNamedConstraints() { final String text = "rule X when Person( \"Mark\", 42; location == \"atlanta\" ) then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); - assertThat(pattern.getDescrs().size()).isEqualTo(3); - ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(3); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); assertThat(fcd.getPosition()).isEqualTo(0); assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); - fcd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + fcd = (ExprConstraintDescr) pattern.getDescrs().get(1); assertThat(fcd.getExpression()).isEqualTo("42"); assertThat(fcd.getPosition()).isEqualTo(1); assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); - fcd = (ExprConstraintDescr) pattern.getDescrs().get( 2 ); + fcd = (ExprConstraintDescr) pattern.getDescrs().get(2); assertThat(fcd.getExpression()).isEqualTo("location == \"atlanta\""); assertThat(fcd.getPosition()).isEqualTo(2); assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); - } @Test - public void parse_UnificationBinding() throws Exception { + void unificationBinding() { final String text = "rule X when $p := Person( $name := name, $loc : location ) then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); assertThat(pattern.getIdentifier()).isEqualTo("$p"); assertThat(pattern.isUnification()).isTrue(); - assertThat(pattern.getDescrs().size()).isEqualTo(2); - ExprConstraintDescr bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(2); + ExprConstraintDescr bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(bindingDescr.getExpression()).isEqualTo("$name := name"); - bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get(1); assertThat(bindingDescr.getExpression()).isEqualTo("$loc : location"); - } @Test - public void parse_BigLiterals() { + void bigLiterals() { final String text = "rule X when Primitives( bigInteger == (10I), " + " bigDecimal == (10B), " + " bigInteger < 50I, " + " bigDecimal < 50.2B ) then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); - assertThat(pattern.getDescrs().size()).isEqualTo(4); - ExprConstraintDescr ecd = (ExprConstraintDescr) pattern.getDescrs().get( 0 ); + assertThat(pattern.getDescrs()).hasSize(4); + ExprConstraintDescr ecd = (ExprConstraintDescr) pattern.getDescrs().get(0); assertThat(ecd.getExpression()).isEqualTo("bigInteger == (10I)"); - ecd = (ExprConstraintDescr) pattern.getDescrs().get( 1 ); + ecd = (ExprConstraintDescr) pattern.getDescrs().get(1); assertThat(ecd.getExpression()).isEqualTo("bigDecimal == (10B)"); - ecd = (ExprConstraintDescr) pattern.getDescrs().get( 2 ); + ecd = (ExprConstraintDescr) pattern.getDescrs().get(2); assertThat(ecd.getExpression()).isEqualTo("bigInteger < 50I"); - ecd = (ExprConstraintDescr) pattern.getDescrs().get( 3 ); + ecd = (ExprConstraintDescr) pattern.getDescrs().get(3); assertThat(ecd.getExpression()).isEqualTo("bigDecimal < 50.2B"); } @Test - public void parse_BindingComposite() throws Exception { + void bindingComposite() { final String text = "rule X when Person( $name : name == \"Bob\" || $loc : location == \"Montreal\" ) then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Person"); assertThat(pattern.isUnification()).isFalse(); // embedded bindings are extracted at compile time - List< ? > constraints = pattern.getDescrs(); - assertThat(constraints.size()).isEqualTo(1); + List constraints = pattern.getDescrs(); + assertThat(constraints).hasSize(1); assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name == \"Bob\" || $loc : location == \"Montreal\""); } @Test - public void parse_BindingCompositeWithMethods() throws Exception { + void bindingCompositeWithMethods() { final String text = "rule X when Person( $name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\" ) then end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Person"); assertThat(pattern.isUnification()).isFalse(); // embedded bindings are extracted at compile time - List< ? > constraints = pattern.getDescrs(); - assertThat(constraints.size()).isEqualTo(1); + List constraints = pattern.getDescrs(); + assertThat(constraints).hasSize(1); assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\""); } @Test - public void parse_PluggableOperators2() throws Exception { + void pluggableOperators2() { final String text = "rule \"tt\"\n" + " dialect \"mvel\"\n" + "when\n" + @@ -3484,47 +3429,44 @@ public void parse_PluggableOperators2() throws Exception { "then\n" + "end"; PatternDescr pattern = (PatternDescr) ((ExistsDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 )).getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0)).getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("TelephoneCall"); - ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); assertThat(constr.getText()).isEqualTo("this finishes [1m] \"25-May-2011\""); - } @Test - public void parse_InlineEval() throws Exception { + void inlineEval() { final String text = "rule \"inline eval\"\n" + "when\n" + " Person( eval( name.startsWith(\"b\") && name.finishesWith(\"b\")) )\n" + "then\n" + "end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("Person"); - ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); assertThat(constr.getText()).isEqualToIgnoringWhitespace("eval( name.startsWith(\"b\") && name.finishesWith(\"b\"))"); - } @Test - public void parse_InfinityLiteral() throws Exception { + void infinityLiteral() { final String text = "rule \"infinity\"\n" + "when\n" + " StockTick( this after[-*,*] $another )\n" + "then\n" + "end"; PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( - text ).getLhs().getDescrs().get( 0 ); + text).getLhs().getDescrs().get(0); assertThat(pattern.getObjectType()).isEqualTo("StockTick"); - ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get( 0 ); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); assertThat(constr.getText()).isEqualTo("this after[-*,*] $another"); - } - public static Stream entryPointIds() { + static Stream entryPointIds() { return Stream.of( Arguments.of("eventStream", "eventStream"), Arguments.of("\"My entry-point 'ID'\"", "My entry-point 'ID'") @@ -3533,28 +3475,28 @@ public static Stream entryPointIds() { @ParameterizedTest @MethodSource("entryPointIds") - public void parse_EntryPointDeclaration(String sourceId, String expectedId) throws Exception { + void parse_EntryPointDeclaration(String sourceId, String expectedId) { final String text = "package org.drools\n" + "declare entry-point " + sourceId + "\n" + " @source(\"jndi://queues/events\")\n" + " @foo( true )\n" + "end"; PackageDescr pkg = parseAndGetPackageDescr( - text ); + text); assertThat(pkg.getName()).isEqualTo("org.drools"); - assertThat(pkg.getEntryPointDeclarations().size()).isEqualTo(1); + assertThat(pkg.getEntryPointDeclarations()).hasSize(1); EntryPointDeclarationDescr epd = pkg.getEntryPointDeclarations().iterator().next(); assertThat(epd.getEntryPointId()).isEqualTo(expectedId); - assertThat(epd.getAnnotations().size()).isEqualTo(2); + assertThat(epd.getAnnotations()).hasSize(2); assertThat(epd.getAnnotation("source").getValue()).isEqualTo("\"jndi://queues/events\""); assertThat(epd.getAnnotation("foo").getValue()).isEqualTo("true"); } @Test - public void parse_WindowDeclaration() throws Exception { + void windowDeclaration() { final String text = "package org.drools\n" + "declare window Ticks\n" + " @doc(\"last 10 stock ticks\")\n" + @@ -3563,15 +3505,15 @@ public void parse_WindowDeclaration() throws Exception { " from entry-point stStream\n" + "end"; PackageDescr pkg = parseAndGetPackageDescr( - text ); + text); assertThat(pkg.getName()).isEqualTo("org.drools"); - assertThat(pkg.getWindowDeclarations().size()).isEqualTo(1); + assertThat(pkg.getWindowDeclarations()).hasSize(1); WindowDeclarationDescr wdd = pkg.getWindowDeclarations().iterator().next(); assertThat(wdd.getName()).isEqualTo("Ticks"); - assertThat(wdd.getAnnotations().size()).isEqualTo(1); + assertThat(wdd.getAnnotations()).hasSize(1); assertThat(wdd.getAnnotation("doc").getValue()).isEqualTo("\"last 10 stock ticks\""); PatternDescr pd = wdd.getPattern(); @@ -3580,17 +3522,17 @@ public void parse_WindowDeclaration() throws Exception { assertThat(pd.getObjectType()).isEqualTo("StockTick"); assertThat(pd.getSource().getText()).isEqualTo("stStream"); - assertThat(pd.getBehaviors().size()).isEqualTo(1); - BehaviorDescr bd = pd.getBehaviors().get( 0 ); + assertThat(pd.getBehaviors()).hasSize(1); + BehaviorDescr bd = pd.getBehaviors().get(0); assertThat(bd.getType()).isEqualTo("window"); assertThat(bd.getSubType()).isEqualTo("length"); - assertThat(bd.getParameters().size()).isEqualTo(2); + assertThat(bd.getParameters()).hasSize(2); assertThat(bd.getParameters().get(0)).isEqualTo("10"); assertThat(bd.getParameters().get(1)).isEqualTo("$s.symbol"); } @Test - public void parse_WindowUsage() throws Exception { + void windowUsage() { final String text = "package org.drools\n" + "rule X\n" + "when\n" + @@ -3598,15 +3540,15 @@ public void parse_WindowUsage() throws Exception { "then\n" + "end\n"; PackageDescr pkg = parseAndGetPackageDescr( - text ); + text); assertThat(pkg.getName()).isEqualTo("org.drools"); - assertThat(pkg.getRules().size()).isEqualTo(1); + assertThat(pkg.getRules()).hasSize(1); RuleDescr rd = pkg.getRules().get(0); assertThat(rd.getName()).isEqualTo("X"); - assertThat(rd.getLhs().getDescrs().size()).isEqualTo(1); + assertThat(rd.getLhs().getDescrs()).hasSize(1); PatternDescr pd = (PatternDescr) rd.getLhs().getDescrs().get(0); assertThat(pd).isNotNull(); @@ -3615,7 +3557,7 @@ public void parse_WindowUsage() throws Exception { } @Test - public void endInRhs() throws Exception { + void endInRhs() { final String text = "package org.drools\n" + "rule X\n" + "when\n" + @@ -3623,14 +3565,14 @@ public void endInRhs() throws Exception { "then\n" + " System.out.println($s.endsWith(\"xyz\"));\n" + "end\n"; - PackageDescr packageDescr = parseAndGetPackageDescr(text ); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("System.out.println($s.endsWith(\"xyz\"));"); } @Test - public void endTokenInRhs() throws Exception { + void endTokenInRhs() { final String text = "package org.drools\n" + "rule X\n" + "when\n" + @@ -3638,14 +3580,14 @@ public void endTokenInRhs() throws Exception { "then\n" + " int end = 10;\n" + "end\n"; - PackageDescr packageDescr = parseAndGetPackageDescr(text ); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int end = 10;"); } @Test - public void ruleTokenInRhs() throws Exception { + void ruleTokenInRhs() { final String text = "package org.drools\n" + "rule X\n" + "when\n" + @@ -3653,7 +3595,7 @@ public void ruleTokenInRhs() throws Exception { "then\n" + " int rule = 10;\n" + "end\n"; - PackageDescr packageDescr = parseAndGetPackageDescr(text ); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int rule = 10;"); @@ -3667,7 +3609,7 @@ void semicolonEnd() { " $s : String()\n" + "then\n" + " delete($s);end\n"; // no space after semicolon - PackageDescr packageDescr = parseAndGetPackageDescr(text ); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("delete($s);"); @@ -3681,7 +3623,7 @@ void braceEnd() { " $p : Person()\n" + "then\n" + " modify($p) { setAge(2) }end\n"; // no space after right brace - PackageDescr packageDescr = parseAndGetPackageDescr(text ); + PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("modify($p) { setAge(2) }"); @@ -4048,51 +3990,48 @@ void groupedConstraintsWithNullSafeDereferencing() { } @Test - public void functionWithStringLiteral() { + void functionWithStringLiteral() { final String text = "function String star(String s) { return \"*\"; }"; PackageDescr packageDescr = parseAndGetPackageDescr(text); - - FunctionDescr function = packageDescr.getFunctions().get( 0 ); + FunctionDescr function = packageDescr.getFunctions().get(0); assertThat(function.getName()).isEqualTo("star"); assertThat(function.getReturnType()).isEqualTo("String"); assertThat(function.getParameterTypes().get(0)).isEqualTo("String"); assertThat(function.getParameterNames().get(0)).isEqualTo("s"); - assertThat(function.getBody()).isEqualToIgnoringWhitespace( "return \"*\";"); + assertThat(function.getBody()).isEqualToIgnoringWhitespace("return \"*\";"); } @Test - public void functionWithStringLiteralAddition() { + void functionWithStringLiteralAddition() { final String text = "function String addStar(String s) { return s + \"*\"; }"; PackageDescr packageDescr = parseAndGetPackageDescr(text); - - FunctionDescr function = packageDescr.getFunctions().get( 0 ); + FunctionDescr function = packageDescr.getFunctions().get(0); assertThat(function.getName()).isEqualTo("addStar"); assertThat(function.getReturnType()).isEqualTo("String"); assertThat(function.getParameterTypes().get(0)).isEqualTo("String"); assertThat(function.getParameterNames().get(0)).isEqualTo("s"); - assertThat(function.getBody()).isEqualToIgnoringWhitespace( "return s + \"*\";"); + assertThat(function.getBody()).isEqualToIgnoringWhitespace("return s + \"*\";"); } @Test - public void functionWithMultipleBlockStatements() { + void functionWithMultipleBlockStatements() { final String text = "function String star(String s) {\n" + " String result = s + \"*\";\n" + " return result;\n" + "}"; PackageDescr packageDescr = parseAndGetPackageDescr(text); - - FunctionDescr function = packageDescr.getFunctions().get( 0 ); + FunctionDescr function = packageDescr.getFunctions().get(0); assertThat(function.getName()).isEqualTo("star"); assertThat(function.getReturnType()).isEqualTo("String"); assertThat(function.getParameterTypes().get(0)).isEqualTo("String"); assertThat(function.getParameterNames().get(0)).isEqualTo("s"); - assertThat(function.getBody()).isEqualToIgnoringWhitespace( "String result = s + \"*\"; return result;"); + assertThat(function.getBody()).isEqualToIgnoringWhitespace("String result = s + \"*\"; return result;"); } @Test @@ -4105,7 +4044,6 @@ void lhsPatternAnnotation() { "end\n"; PackageDescr packageDescr = parseAndGetPackageDescr(text); - RuleDescr ruleDescr = packageDescr.getRules().get(0); PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); AnnotationDescr annotationDescr = patternDescr.getAnnotations().iterator().next(); @@ -4233,7 +4171,7 @@ void fromNew() { } @Test - public void expiresWithTimeLiteralValue() { + void expiresWithTimeLiteralValue() { String text = "package org.drools\n" + "declare StockFact\n" + " @role( value = event )\n" + @@ -4337,12 +4275,12 @@ void ooPathLhsPattern() { assertThat(ruleDescr.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { assertThat(notDescr.getDescrs()).hasSize(1); assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { - assertThat(patternDescr.getConstraint().getDescrs()).hasSize(1); - assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { - assertThat(exprConstraintDescr.getExpression()).isEqualTo("/strings [ this == \"It Does Work\" ]"); - assertThat(exprConstraintDescr.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); - assertThat(exprConstraintDescr.getPosition()).isEqualTo(0); - }); + assertThat(patternDescr.getConstraint().getDescrs()).hasSize(1); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("/strings [ this == \"It Does Work\" ]"); + assertThat(exprConstraintDescr.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); + assertThat(exprConstraintDescr.getPosition()).isEqualTo(0); + }); }); }); } @@ -4387,7 +4325,7 @@ void inlineCastThis() { } @Test - public void queryArgumentWithoutType() throws Exception { + void queryArgumentWithoutType() { final String text = "package org.drools\n" + "query olderThan( $age )\n" + " $p : Person(age > (Integer)$age)\n" + @@ -4401,7 +4339,7 @@ public void queryArgumentWithoutType() throws Exception { } @Test - public void queryMultipleArguments() throws Exception { + void queryMultipleArguments() { final String text = "package org.drools\n" + "query olderThan( String $name, int $age )\n" + " $p : Person(age > $age)\n" + @@ -4415,7 +4353,7 @@ public void queryMultipleArguments() throws Exception { } @Test - public void queryArrayArgument() throws Exception { + void queryArrayArgument() { final String text = "package org.drools\n" + "query olderThan( int[] $ages )\n" + " $p : Person(age > $ages[0])\n" + @@ -4429,7 +4367,7 @@ public void queryArrayArgument() throws Exception { } @Test - public void queryZeroArgument() throws Exception { + void queryZeroArgument() { final String text = "package org.drools\n" + "query olderThan()\n" + " $p : Person()\n" + @@ -4443,7 +4381,7 @@ public void queryZeroArgument() throws Exception { } @Test - public void queryNoArgument() throws Exception { + void queryNoArgument() { final String text = "package org.drools\n" + "query olderThan\n" + " $p : Person()\n" + @@ -4457,7 +4395,7 @@ public void queryNoArgument() throws Exception { } @Test - public void traitExtendsMultiple() throws Exception { + void traitExtendsMultiple() { final String source = "declare trait FatherTrait extends com.sample.ParentTrait, UncleTrait, org.test.GrandParentTrait end"; PackageDescr pkg = parseAndGetPackageDescr(source); @@ -4474,7 +4412,7 @@ public void traitExtendsMultiple() throws Exception { } @Test - public void pluggableEvaluator() throws Exception { + void pluggableEvaluator() { final String source = "package org.drools\n" + "rule R\n" + "when\n" + @@ -4497,15 +4435,15 @@ public void pluggableEvaluator() throws Exception { void namedConsequenceDo() { final String text = "rule R when\n" + - " $r : Result()\n" + - " $p1 : Person(name == \"Mark\")\n" + - " do[FoundMark]\n" + - " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + - "then\n" + - " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + - "then[FoundMark]\n" + - " $r.addValue(\"Found \" + $p1.getName());\n" + - "end"; + " $r : Result()\n" + + " $p1 : Person(name == \"Mark\")\n" + + " do[FoundMark]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"Found \" + $p1.getName());\n" + + "end"; PackageDescr packageDescr = parseAndGetPackageDescr(text); RuleDescr ruleDescr = packageDescr.getRules().get(0); NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); @@ -4681,17 +4619,17 @@ void namedConsequenceOrWithBindVariables() { OrDescr orDescr = (OrDescr) ruleDescr.getLhs().getDescrs().get(1); PatternDescr patternDescr1 = (PatternDescr) orDescr.getDescrs().get(0); assertThat(patternDescr1.getIdentifier()).isEqualTo("$p1"); - assertThat(((ExprConstraintDescr)patternDescr1.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("name == \"Mark\""); + assertThat(((ExprConstraintDescr) patternDescr1.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("name == \"Mark\""); PatternDescr patternDescr2 = (PatternDescr) orDescr.getDescrs().get(1); assertThat(patternDescr2.getIdentifier()).isEqualTo("$p1"); - assertThat(((ExprConstraintDescr)patternDescr2.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("name == \"Mario\""); + assertThat(((ExprConstraintDescr) patternDescr2.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("name == \"Mario\""); NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMarkOrMario"); } @Test - void testNamedConsequencesInsideOR1() { + void namedConsequencesInsideOR1() { final String text = "import org.drools.mvel.compiler.Cheese;\n " + "global java.util.List results;\n" + @@ -4737,7 +4675,7 @@ void testNamedConsequencesInsideOR1() { } @Test - void testNamedConsequencesInsideOR2() { + void namedConsequencesInsideOR2() { final String text = "import org.drools.mvel.compiler.Cheese;\n " + "global java.util.List results;\n" + @@ -4783,7 +4721,7 @@ void testNamedConsequencesInsideOR2() { } @Test - public void queryComplexLhs() { + void queryComplexLhs() { final String text = "query isContainedIn(String x, String y)\n" + " Location (x, y;)\n" + " or\n" + @@ -4923,7 +4861,7 @@ void existsWithPrefixAnd() { } @Test - public void enumDeclaration() { + void enumDeclaration() { final String text = "declare enum PersonAge\n" + " @doc(author=\"Bob\")\n" + @@ -4994,7 +4932,7 @@ static void assertNamespace(Collection children, String nam } @Test - public void noWhitespaceBetweenRuleKeywordAndName() { + void noWhitespaceBetweenRuleKeywordAndName() { final String text = "rule X when then end rule\"Y\" when then end rule'Z'when then end"; PackageDescr pkg = parseAndGetPackageDescr(text); @@ -5063,7 +5001,7 @@ void unificationInAccumulateRule() { "then\n" + "end"; RuleDescr rule = parseAndGetFirstRuleDescr(text); - assertThat(rule.getLhs().getDescrs().size()).isEqualTo(2); + assertThat(rule.getLhs().getDescrs()).hasSize(2); final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(1); AccumulateDescr accumulateDescr = (AccumulateDescr) outPattern.getSource(); @@ -5278,12 +5216,12 @@ void accumulateWithEmptyActionAndReverse() { "then end"; RuleDescr rule = parseAndGetFirstRuleDescr(drl); - final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get( 0 ); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); - assertThat(accum.getInitCode()).isEqualTo( "double total = 0;"); + assertThat(accum.getInitCode()).isEqualTo("double total = 0;"); assertThat(accum.getActionCode()).isEmpty(); assertThat(accum.getReverseCode()).isEmpty(); - assertThat(accum.getResultCode()).isEqualTo( "new Double( total )"); + assertThat(accum.getResultCode()).isEqualTo("new Double( total )"); assertThat(accum.isExternalFunction()).isFalse(); From d7a8d5a9bde8f1852c085a2ebb11efdaba88c54d Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 11 Jun 2024 14:36:10 +0900 Subject: [PATCH 128/141] [incubator-kie-drools-5988] [new-parser] Merge dev-new-parser to main - new parser is disabled by default --- .github/workflows/pr-downstream.yml | 1 - .../src/test/resources/logback-test.xml | 1 + .../main/java/org/drools/drl/parser/DrlParser.java | 11 ++++++----- .../src/test/resources/logback-test.xml | 1 + .../src/test/resources/logback-test.xml | 1 + pom.xml | 7 ++++--- 6 files changed, 13 insertions(+), 9 deletions(-) diff --git a/.github/workflows/pr-downstream.yml b/.github/workflows/pr-downstream.yml index 5cca505b8f5..b82393a748f 100644 --- a/.github/workflows/pr-downstream.yml +++ b/.github/workflows/pr-downstream.yml @@ -14,7 +14,6 @@ on: jobs: kogito-downstream-build: - if false: # Temporally disabled because downstream build doesn't work with the feature branch dev-new-parser concurrency: group: pr-${{ matrix.job_name }}_${{ matrix.os }}_${{ matrix.java-version }}_${{ matrix.maven-version }}_${{ github.head_ref }} cancel-in-progress: true diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml b/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml index 7740901e7d3..7f61472dec1 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml @@ -9,6 +9,7 @@ + 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 398e5f49923..714fd8a21c6 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 @@ -53,6 +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 final List results = new ArrayList<>(); private List editorSentences = null; private Location location = new Location( Location.LOCATION_UNKNOWN ); @@ -61,8 +62,8 @@ public class DrlParser { public static final String ANTLR4_PARSER_ENABLED_PROPERTY = "drools.drl.antlr4.parser.enabled"; - // TODO: temporarily removed 'final' for testing purposes. This should be final - public static boolean ANTLR4_PARSER_ENABLED = Boolean.parseBoolean(System.getProperty(ANTLR4_PARSER_ENABLED_PROPERTY, "true")); // default is true + // 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; private final LanguageLevelOption languageLevel; @@ -83,7 +84,7 @@ public PackageDescr parse(final Resource resource, final String text) throws Dro public PackageDescr parse(final boolean isEditor, final String text) throws DroolsParserException { - System.out.println("### parse : ANTLR4_PARSER_ENABLED = " + ANTLR4_PARSER_ENABLED); + LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED); if (ANTLR4_PARSER_ENABLED) { // new parser based on antlr4 return compileWithAntlr4Parser(parser -> parser.parse(new StringReader(text))); @@ -96,7 +97,7 @@ public PackageDescr parse(final boolean isEditor, public PackageDescr parse(final boolean isEditor, final Reader reader) throws DroolsParserException { - System.out.println("### parse : ANTLR4_PARSER_ENABLED = " + ANTLR4_PARSER_ENABLED); + LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED); if (ANTLR4_PARSER_ENABLED) { // new parser based on antlr4 return compileWithAntlr4Parser(parser -> parser.parse(reader)); @@ -185,7 +186,7 @@ public PackageDescr parse(final boolean isEditor, final InputStream is) throws DroolsParserException, IOException { this.resource = resource; String encoding = resource instanceof InternalResource ? ((InternalResource) resource).getEncoding() : null; - System.out.println("### parse : ANTLR4_PARSER_ENABLED = " + ANTLR4_PARSER_ENABLED); + LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED); if (ANTLR4_PARSER_ENABLED) { // new parser based on antlr4 return compileWithAntlr4Parser(parser -> parser.parse(is, encoding)); 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 dbee14ec590..25b6a1f4918 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,6 +36,7 @@ + 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 ce4cf145c90..715224c2777 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,6 +34,7 @@ + diff --git a/pom.xml b/pom.xml index c0fd1291775..adb61070d4e 100644 --- a/pom.xml +++ b/pom.xml @@ -312,10 +312,10 @@ - disableNewParser + enableNewParser - disableNewParser + enableNewParser @@ -325,7 +325,8 @@ maven-surefire-plugin - false + + true From caa8f3a8bdf8bc345444472257e50a4b62e75b09 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 12 Sep 2024 14:57:52 +0900 Subject: [PATCH 129/141] License header for .g4 --- .../drl/parser/antlr4/DRL6Expressions.g4 | 18 +++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLLexer.g4 | 18 +++++++++++++++++ .../org/drools/drl/parser/antlr4/DRLParser.g4 | 20 ++++++++++++++++++- 3 files changed, 55 insertions(+), 1 deletion(-) 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/DRL6Expressions.g4 index 2efe8b1ec8e..063e4ed48cf 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/DRL6Expressions.g4 @@ -1,3 +1,21 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ parser grammar DRL6Expressions; options { 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/DRLLexer.g4 index 2a433de8b06..2c05b4dc38b 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/DRLLexer.g4 @@ -1,3 +1,21 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ lexer grammar DRLLexer; 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/DRLParser.g4 index c1e399fd01c..8ccaf9b4cd8 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/DRLParser.g4 @@ -1,4 +1,22 @@ -parser grammar DRLParser; +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + parser grammar DRLParser; options { tokenVocab=DRLLexer; } From 076a4d261de3e5a8d31571ba84edee136fd8f69d Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 2 Oct 2024 16:47:53 +0900 Subject: [PATCH 130/141] License headers --- NOTICE | 4 ++++ .../src/test/resources/logback-test.xml | 20 +++++++++++++++++++ .../org/drools/drl/parser/antlr4/complex.dsl | 19 ++++++++++++++++++ .../parser/antlr4/multiple_constraints.dsl | 19 ++++++++++++++++++ .../drools-drl-parser/Developer_Notes.md | 19 ++++++++++++++++++ .../drl/parser/DrlExprParserFactory.java | 18 +++++++++++++++++ pom.xml | 2 ++ 7 files changed, 101 insertions(+) diff --git a/NOTICE b/NOTICE index 43c4b92efb0..646a3d4ae06 100644 --- a/NOTICE +++ b/NOTICE @@ -21,3 +21,7 @@ This product also includes the following third-party components: * search-ui Downloaded from: https://gitlab.com/antora/antora-lunr-extension License: Mozilla Public License 2.0 + +* JavaParser, JavaLexer + Downloaded from: https://github.com/antlr/grammars-v4/tree/master/java/java + License: BSD License \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml b/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml index 7f61472dec1..f44c3a48c76 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml @@ -1,4 +1,24 @@ + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/complex.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/complex.dsl index b2cf4cb9c84..0e7ffc0fd07 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/complex.dsl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/complex.dsl @@ -1,3 +1,22 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + #place your comments here - this is just a description for your own purposes. [when]There is a Person with name of {name}=Person(name=="{name}") [when]Person is at least {age} years old and lives in {location}=Person(age > {age}, location == "{location}") diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_constraints.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_constraints.dsl index 92a142ec007..b56fd4bd644 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_constraints.dsl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_constraints.dsl @@ -1,3 +1,22 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + #place your comments here - this is just a description for your own purposes. [when]There is a Person with=Person() [when]- age less than {age}=age < {age} diff --git a/drools-drl/drools-drl-parser/Developer_Notes.md b/drools-drl/drools-drl-parser/Developer_Notes.md index d3d2d77e1be..4e09d2afd6a 100644 --- a/drools-drl/drools-drl-parser/Developer_Notes.md +++ b/drools-drl/drools-drl-parser/Developer_Notes.md @@ -1,3 +1,22 @@ + + # drools-drl-parser In this `dev-new-parser` branch, `drools-drl-parser` has 2 implementations of the DRL parser. The new parser is under development, and the old parser is used in the current drools code base. 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 58659218037..4ddbf289705 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 @@ -1,3 +1,21 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.drools.drl.parser; import org.drools.drl.parser.antlr4.Drl6ExprParserAntlr4; diff --git a/pom.xml b/pom.xml index adb61070d4e..82960af5a91 100644 --- a/pom.xml +++ b/pom.xml @@ -142,6 +142,8 @@ **/branch.yaml **/main.yaml **/mvel.jj + **/JavaLexer.g4 + **/JavaParser.g4 **/*.csv **/*.sdo **/*.sdt From 16c8d299d98aaef4e29ffbd75aaf69c431b48597 Mon Sep 17 00:00:00 2001 From: Jozef Marko Date: Mon, 14 Oct 2024 08:49:10 +0200 Subject: [PATCH 131/141] Add license header (#6121) --- .../kie-pmml-compiler-core/PMMLCompiler.uml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-core/PMMLCompiler.uml b/kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-core/PMMLCompiler.uml index 9a2bea63492..40b89299c9b 100644 --- a/kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-core/PMMLCompiler.uml +++ b/kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-core/PMMLCompiler.uml @@ -1,4 +1,22 @@ + JAVA org.kie.pmml.compiler.executor.PMMLCompilerExecutorImpl From 9a52c69238868b8e0cf6caec027bc7bcd9b1b943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tibor=20Zim=C3=A1nyi?= Date: Mon, 14 Oct 2024 14:34:03 +0200 Subject: [PATCH 132/141] Support generic range type in DMN engine (#6123) --- .../org/kie/dmn/core/DMNCompilerTest.java | 2 +- .../kie/dmn/feel/parser/feel11/FEEL_1_1.g4 | 1 + .../codegen/feel11/ASTCompilerHelper.java | 8 +++ .../codegen/feel11/ASTCompilerVisitor.java | 7 ++ .../codegen/feel11/DMNCodegenConstants.java | 3 + .../kie/dmn/feel/lang/ast/RangeTypeNode.java | 48 ++++++++++++++ .../org/kie/dmn/feel/lang/ast/Visitor.java | 1 + .../lang/ast/visitor/DefaultedVisitor.java | 6 ++ .../kie/dmn/feel/lang/types/GenRangeType.java | 64 +++++++++++++++++++ .../feel/parser/feel11/ASTBuilderVisitor.java | 7 ++ .../dmn/feel/parser/feel11/ParserHelper.java | 5 ++ .../feel11/CodegenFEELUnaryTestsTest.java | 3 +- .../codegen/feel11/DirectCompilerTest.java | 13 ++-- .../feel/lang/ast/ForExpressionNodeTest.java | 6 +- .../dmn/feel/lang/ast/RangeTypeNodeTest.java | 52 +++++++++++++++ .../ForIterationUtilsTest.java | 2 +- .../dmn/feel/runtime/FEELCompilerTest.java | 14 ++-- .../dmn/feel/runtime/FEELOperatorsTest.java | 2 + .../functions/BaseFEELFunctionHelperTest.java | 4 +- .../functions/BaseFEELFunctionTest.java | 4 +- .../runtime/functions/ScorerHelperTest.java | 18 +++--- .../org/kie/dmn/feel/util/CompilerUtils.java | 3 +- .../EvaluationContextTestUtil.java} | 7 +- kie-dmn/kie-dmn-tck/pom.xml | 1 - 24 files changed, 242 insertions(+), 39 deletions(-) create mode 100644 kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeTypeNode.java create mode 100644 kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/types/GenRangeType.java create mode 100644 kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/RangeTypeNodeTest.java rename kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/{codegen/feel11/CodegenTestUtil.java => util/EvaluationContextTestUtil.java} (91%) diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNCompilerTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNCompilerTest.java index 7e9874ef7da..18d96e5ef71 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNCompilerTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNCompilerTest.java @@ -56,7 +56,7 @@ import static org.kie.dmn.core.util.DynamicTypeUtils.entry; import static org.kie.dmn.core.util.DynamicTypeUtils.mapOf; import static org.kie.dmn.core.util.DynamicTypeUtils.prototype; -import static org.kie.dmn.feel.codegen.feel11.CodegenTestUtil.newEmptyEvaluationContext; +import static org.kie.dmn.feel.util.EvaluationContextTestUtil.newEmptyEvaluationContext; public class DMNCompilerTest extends BaseVariantTest { diff --git a/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 b/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 index 4760125e128..9f04edc4532 100644 --- a/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 +++ b/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 @@ -135,6 +135,7 @@ type helper.popScope(); } : {_input.LT(1).getText().equals("list")}? sk=Identifier LT type GT #listType + | {_input.LT(1).getText().equals("range")}? sk=Identifier LT type GT #rangeType | {_input.LT(1).getText().equals("context")}? sk=Identifier LT Identifier COLON type ( COMMA Identifier COLON type )* GT #contextType | FUNCTION #qnType | FUNCTION LT (type ( COMMA type )*)? GT RARROW type #functionType diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java index 30930577189..dc87cd9e5d7 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java @@ -72,6 +72,7 @@ import org.kie.dmn.feel.lang.ast.QualifiedNameNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.RangeNode; +import org.kie.dmn.feel.lang.ast.RangeTypeNode; import org.kie.dmn.feel.lang.ast.SignedUnaryNode; import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.TemporalConstantNode; @@ -136,6 +137,7 @@ import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.QUALIFIEDNAMENODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.QUANTIFIEDEXPRESSIONNODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.RANGENODE_CT; +import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.RANGETYPENODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.SIGNEDUNARYNODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.STRINGNODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.TEMPORALCONSTANTNODE_CT; @@ -431,6 +433,12 @@ public BlockStmt add(RangeNode n) { endExpression), n.getText()); } + public BlockStmt add(RangeTypeNode n) { + Expression genTypeNodeExpression = getNodeExpression(n.getGenericTypeNode()); + return addVariableDeclaratorWithObjectCreation(RANGETYPENODE_CT, NodeList.nodeList(genTypeNodeExpression), + n.getText()); + } + public BlockStmt add(SignedUnaryNode n) { Expression signExpression = getEnumExpression(n.getSign()); Expression expressionExpression = getNodeExpression(n.getExpression()); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java index 0a509bca667..a4bef5554d3 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java @@ -50,6 +50,7 @@ import org.kie.dmn.feel.lang.ast.QualifiedNameNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.RangeNode; +import org.kie.dmn.feel.lang.ast.RangeTypeNode; import org.kie.dmn.feel.lang.ast.SignedUnaryNode; import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.TemporalConstantNode; @@ -253,6 +254,12 @@ public BlockStmt visit(RangeNode n) { return compilerHelper.add(n); } + @Override + public BlockStmt visit(RangeTypeNode n) { + LOGGER.trace("visit {}", n); + return compilerHelper.add(n); + } + @Override public BlockStmt visit(SignedUnaryNode n) { LOGGER.trace("visit {}", n); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java index 96520d8689c..f5db4e41509 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java @@ -51,6 +51,7 @@ import org.kie.dmn.feel.lang.ast.QualifiedNameNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.RangeNode; +import org.kie.dmn.feel.lang.ast.RangeTypeNode; import org.kie.dmn.feel.lang.ast.SignedUnaryNode; import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.TemporalConstantNode; @@ -142,6 +143,8 @@ public class DMNCodegenConstants { public static final ClassOrInterfaceType LISTNODE_CT = parseClassOrInterfaceType(ListNode.class.getCanonicalName()); public static final ClassOrInterfaceType LISTTYPENODE_CT = parseClassOrInterfaceType(ListTypeNode.class.getCanonicalName()); + public static final ClassOrInterfaceType RANGETYPENODE_CT = + parseClassOrInterfaceType(RangeTypeNode.class.getCanonicalName()); public static final ClassOrInterfaceType NAMEDEFNODE_CT = parseClassOrInterfaceType(NameDefNode.class.getCanonicalName()); public static final ClassOrInterfaceType NAMEDPARAMETERNODE_CT = diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeTypeNode.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeTypeNode.java new file mode 100644 index 00000000000..87771e9ac0c --- /dev/null +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeTypeNode.java @@ -0,0 +1,48 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the + * License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and limitations under the License. + */ + +package org.kie.dmn.feel.lang.ast; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.kie.dmn.feel.lang.EvaluationContext; +import org.kie.dmn.feel.lang.Type; +import org.kie.dmn.feel.lang.types.GenRangeType; + +public class RangeTypeNode extends TypeNode { + + private final TypeNode genericTypeNode; + + public RangeTypeNode(ParserRuleContext ctx, TypeNode gen) { + super(ctx); + this.genericTypeNode = gen; + } + + public RangeTypeNode(TypeNode genericTypeNode, String text) { + this.genericTypeNode = genericTypeNode; + this.setText(text); + } + + @Override + public Type evaluate(EvaluationContext ctx) { + Type gen = genericTypeNode.evaluate(ctx); + return new GenRangeType(gen); + } + + @Override + public T accept(Visitor v) { + return v.visit(this); + } + + public TypeNode getGenericTypeNode() { + return genericTypeNode; + } + +} diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java index 6904d03b2d5..82775356454 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java @@ -50,6 +50,7 @@ public interface Visitor { T visit(QualifiedNameNode n); T visit(QuantifiedExpressionNode n); T visit(RangeNode n); + T visit(RangeTypeNode n); T visit(SignedUnaryNode n); T visit(StringNode n); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java index 68d5baaa16a..6eb2d6b79d5 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java @@ -49,6 +49,7 @@ import org.kie.dmn.feel.lang.ast.QualifiedNameNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.RangeNode; +import org.kie.dmn.feel.lang.ast.RangeTypeNode; import org.kie.dmn.feel.lang.ast.SignedUnaryNode; import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; @@ -194,6 +195,11 @@ public T visit(RangeNode n) { return defaultVisit(n); } + @Override + public T visit(RangeTypeNode n) { + return defaultVisit(n); + } + @Override public T visit(SignedUnaryNode n) { return defaultVisit(n); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/types/GenRangeType.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/types/GenRangeType.java new file mode 100644 index 00000000000..4386040ba0d --- /dev/null +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/types/GenRangeType.java @@ -0,0 +1,64 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the + * License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and limitations under the License. + */ + +package org.kie.dmn.feel.lang.types; + +import org.kie.dmn.feel.lang.SimpleType; +import org.kie.dmn.feel.lang.Type; +import org.kie.dmn.feel.runtime.impl.RangeImpl; + +public class GenRangeType implements SimpleType { + + /** + * Represents the "generic" type of the current list + */ + private final Type gen; + + + public GenRangeType(Type gen) { + this.gen = gen; + } + + @Override + public boolean isInstanceOf(Object o) { + if (o instanceof RangeImpl rangeImpl) { + return gen.isInstanceOf(rangeImpl.getLowEndPoint()) && gen.isInstanceOf(rangeImpl.getHighEndPoint()); + } else { + return false; + } + } + + @Override + public boolean isAssignableValue(Object value) { + if ( value == null ) { + return true; // a null-value can be assigned to any type. + } + if (!(value instanceof RangeImpl)) { + return gen.isAssignableValue(value); + } + return isInstanceOf(value); + } + + @Override + public String getName() { + return "[anonymous]"; + } + + public Type getGen() { + return gen; + } + + @Override + public boolean conformsTo(Type t) { + return (t instanceof GenRangeType && this.gen.conformsTo(((GenRangeType) t).gen)) || t == BuiltInType.RANGE; + } + +} diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java index 62ce7781a5a..295b9fe539f 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java @@ -49,6 +49,7 @@ import org.kie.dmn.feel.lang.ast.QualifiedNameNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.RangeNode; +import org.kie.dmn.feel.lang.ast.RangeTypeNode; import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.TypeNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; @@ -586,6 +587,12 @@ public BaseNode visitListType(FEEL_1_1Parser.ListTypeContext ctx) { return new ListTypeNode(ctx, type); } + @Override + public BaseNode visitRangeType(FEEL_1_1Parser.RangeTypeContext ctx) { + TypeNode type = (TypeNode) visit(ctx.type()); + return new RangeTypeNode(ctx, type); + } + @Override public BaseNode visitContextType(FEEL_1_1Parser.ContextTypeContext ctx) { List pNames = new ArrayList<>(); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ParserHelper.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ParserHelper.java index 3ac1ca33150..4308519335a 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ParserHelper.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ParserHelper.java @@ -42,6 +42,7 @@ import org.kie.dmn.feel.lang.types.DefaultBuiltinFEELTypeRegistry; import org.kie.dmn.feel.lang.types.FEELTypeRegistry; import org.kie.dmn.feel.lang.types.GenListType; +import org.kie.dmn.feel.lang.types.GenRangeType; import org.kie.dmn.feel.lang.types.ScopeImpl; import org.kie.dmn.feel.lang.types.SymbolTable; import org.kie.dmn.feel.lang.types.VariableSymbol; @@ -144,6 +145,10 @@ public void recoverScope( String name ) { scopeType = ((GenListType) scopeType).getGen(); } + if (scopeType instanceof GenRangeType) { + scopeType = ((GenRangeType) scopeType).getGen(); + } + if (resolved != null && scopeType instanceof CompositeType) { pushScope(scopeType); CompositeType type = (CompositeType) scopeType; diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/CodegenFEELUnaryTestsTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/CodegenFEELUnaryTestsTest.java index ff42ea47a6d..c598d4f9df5 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/CodegenFEELUnaryTestsTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/CodegenFEELUnaryTestsTest.java @@ -34,6 +34,7 @@ import org.kie.dmn.feel.parser.feel11.ASTBuilderVisitor; import org.kie.dmn.feel.parser.feel11.FEELParser; import org.kie.dmn.feel.parser.feel11.FEEL_1_1Parser; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.util.NumberEvalHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -98,7 +99,7 @@ private List parseCompileEvaluate(String feelLiteralExpression, Object FEELEventListenersManager mgr = new FEELEventListenersManager(); SyntaxErrorListener listener = new SyntaxErrorListener(); mgr.addListener(listener); - EvaluationContext emptyContext = CodegenTestUtil.newEmptyEvaluationContext(mgr); + EvaluationContext emptyContext = EvaluationContextTestUtil.newEmptyEvaluationContext(mgr); CompiledFEELUnaryTests compiledUnaryTests = parse(feelLiteralExpression, mgr, listener); LOG.debug("{}", compiledUnaryTests); List result = compiledUnaryTests.getUnaryTests() diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/DirectCompilerTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/DirectCompilerTest.java index 9231a8b1d5d..5a8f00660d7 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/DirectCompilerTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/DirectCompilerTest.java @@ -36,6 +36,7 @@ import org.kie.dmn.feel.runtime.FEELTernaryLogicTest; import org.kie.dmn.feel.runtime.functions.CustomFEELFunction; import org.kie.dmn.feel.util.CompilerUtils; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -226,7 +227,7 @@ void filter_path_tricky1() { CompiledFEELExpression nameRef = CompilerUtils.parseCodegen("[ {x:1, y:2}, {x:2, y:3} ][x]"); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("x", 2); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -239,7 +240,7 @@ void filter_path_tricky2() { CompiledFEELExpression nameRef = CompilerUtils.parseCodegen("[ {x:1, y:2}, {x:2, y:3} ][x]"); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("x", false); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -410,7 +411,7 @@ void nameReference() { CompiledFEELExpression nameRef = parseCodegen(inputExpression, mapOf(entry("someSimpleName", BuiltInType.STRING) ) ); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("someSimpleName", 123L); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -425,7 +426,7 @@ void qualifiedName() { CompiledFEELExpression qualRef = parseCodegen(inputExpression, mapOf(entry("My Person", personType) ) ); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("My Person", mapOf( entry("Full Name", "John Doe"), entry("Age", 47) )); Object result = qualRef.apply(context); LOG.debug("{}", result); @@ -456,7 +457,7 @@ void qualifiedName2() { CompiledFEELExpression qualRef = parseCodegen(inputExpression, mapOf(entry("My Person", personType) ) ); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("My Person", new MyPerson()); Object result = qualRef.apply(context); LOG.debug("{}", result); @@ -471,7 +472,7 @@ void qualifiedName3() { CompiledFEELExpression qualRef = parseCodegen(inputExpression, mapOf(entry("a date", dateType))); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("a date", LocalDate.of(2016, 8, 2)); Object result = qualRef.apply(context); LOG.debug("{}", result); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/ForExpressionNodeTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/ForExpressionNodeTest.java index 290abe5132f..f09f03caa66 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/ForExpressionNodeTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/ForExpressionNodeTest.java @@ -26,7 +26,7 @@ import java.util.Map; import org.junit.jupiter.api.Test; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.lang.Type; import org.kie.dmn.feel.lang.types.BuiltInType; @@ -39,7 +39,7 @@ void evaluateSimpleArray() { IterationContextNode x = getIterationContextNode("x", getListNode("[ 1, 2, 3, 4 ]", Arrays.asList("1", "2", "3", "4")), "x in [ 1, 2, 3, 4 ]"); IterationContextNode y = getIterationContextNode("y", getNameRefNode(BuiltInType.UNKNOWN, "x"), "y in x"); ForExpressionNode forExpressionNode = new ForExpressionNode(Arrays.asList(x, y), getNameRefNode(BuiltInType.UNKNOWN, "y"), "for x in [ 1, 2, 3, 4 ], y in x return y"); - Object retrieved = forExpressionNode.evaluate(CodegenTestUtil.newEmptyEvaluationContext()); + Object retrieved = forExpressionNode.evaluate(EvaluationContextTestUtil.newEmptyEvaluationContext()); assertThat(retrieved).isInstanceOf(List.class).asList(). containsExactly(BigDecimal.ONE, BigDecimal.valueOf(2), BigDecimal.valueOf(3), BigDecimal.valueOf(4)); } @@ -52,7 +52,7 @@ void evaluateNestedArray() { IterationContextNode x = getIterationContextNode("x", getNestedListNode("[ [1, 2], [3, 4] ]", firstIterationContext), "x in [ [1, 2], [3, 4] ]"); IterationContextNode y = getIterationContextNode("y", getNameRefNode(BuiltInType.UNKNOWN, "x"), "y in x"); ForExpressionNode forExpressionNode = new ForExpressionNode(Arrays.asList(x, y), getNameRefNode(BuiltInType.UNKNOWN, "y"), "for x in [ [1, 2], [3, 4] ], y in x return y"); - Object retrieved = forExpressionNode.evaluate(CodegenTestUtil.newEmptyEvaluationContext()); + Object retrieved = forExpressionNode.evaluate(EvaluationContextTestUtil.newEmptyEvaluationContext()); assertThat(retrieved).isInstanceOf(List.class).asList(). containsExactly(BigDecimal.ONE, BigDecimal.valueOf(2), BigDecimal.valueOf(3), BigDecimal.valueOf(4)); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/RangeTypeNodeTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/RangeTypeNodeTest.java new file mode 100644 index 00000000000..aaa5a3caa02 --- /dev/null +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/RangeTypeNodeTest.java @@ -0,0 +1,52 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.kie.dmn.feel.lang.ast; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.kie.dmn.feel.lang.types.GenRangeType; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; +import org.kie.dmn.feel.lang.types.BuiltInType; +import org.mockito.Mockito; + +class RangeTypeNodeTest { + + @Test + void evaluate() { + final CTypeNode typeNode = new CTypeNode(BuiltInType.BOOLEAN); + final RangeTypeNode rangeTypeNode = new RangeTypeNode(typeNode, "sometext"); + Assertions.assertThat(rangeTypeNode.evaluate(EvaluationContextTestUtil.newEmptyEvaluationContext())).isInstanceOf(GenRangeType.class); + } + + @Test + void accept() { + final Visitor visitor = Mockito.spy(Visitor.class); + final RangeTypeNode rangeTypeNode = new RangeTypeNode(null, "sometext"); + rangeTypeNode.accept(visitor); + Mockito.verify(visitor).visit(rangeTypeNode); + } + + @Test + void getGenTypeNode() { + final CTypeNode typeNode = new CTypeNode(BuiltInType.BOOLEAN); + final RangeTypeNode rangeTypeNode = new RangeTypeNode(typeNode, "sometext"); + Assertions.assertThat(rangeTypeNode.getGenericTypeNode()).isSameAs(typeNode); + } +} \ No newline at end of file diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java index 226d2e1797d..43547f15081 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java @@ -32,7 +32,7 @@ import org.mockito.ArgumentCaptor; import static org.assertj.core.api.Assertions.assertThat; -import static org.kie.dmn.feel.codegen.feel11.CodegenTestUtil.newEmptyEvaluationContext; +import static org.kie.dmn.feel.util.EvaluationContextTestUtil.newEmptyEvaluationContext; import static org.kie.dmn.feel.lang.ast.forexpressioniterators.ForIterationUtils.getForIteration; import static org.kie.dmn.feel.lang.ast.forexpressioniterators.ForIterationUtils.validateValues; import static org.kie.dmn.feel.lang.ast.forexpressioniterators.ForIterationUtils.valueMustBeValid; diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELCompilerTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELCompilerTest.java index 80502839d79..f3b34fef4f9 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELCompilerTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELCompilerTest.java @@ -25,7 +25,7 @@ import java.util.List; import org.junit.jupiter.api.Test; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.codegen.feel11.CompiledFEELExpression; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.feel.lang.FEELProperty; @@ -226,7 +226,7 @@ void filter_path_tricky1() { CompiledFEELExpression nameRef = CompilerUtils.parseInterpreted("[ {x:1, y:2}, {x:2, y:3} ][x]"); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("x", 2); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -239,7 +239,7 @@ void filter_path_tricky2() { CompiledFEELExpression nameRef = CompilerUtils.parseInterpreted("[ {x:1, y:2}, {x:2, y:3} ][x]"); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("x", false); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -410,7 +410,7 @@ void nameReference() { CompiledFEELExpression nameRef = parseInterpreted(inputExpression, mapOf(entry("someSimpleName", BuiltInType.STRING) ) ); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("someSimpleName", 123L); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -425,7 +425,7 @@ void qualifiedName() { CompiledFEELExpression qualRef = parseInterpreted(inputExpression, mapOf(entry("My Person", personType) ) ); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("My Person", mapOf( entry("Full Name", "John Doe"), entry("Age", 47) )); Object result = qualRef.apply(context); LOG.debug("{}", result); @@ -456,7 +456,7 @@ void qualifiedName2() { CompiledFEELExpression qualRef = parseInterpreted(inputExpression, mapOf(entry("My Person", personType) ) ); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("My Person", new MyPerson()); Object result = qualRef.apply(context); LOG.debug("{}", result); @@ -471,7 +471,7 @@ void qualifiedName3() { CompiledFEELExpression qualRef = parseInterpreted(inputExpression, mapOf(entry("a date", dateType))); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("a date", LocalDate.of(2016, 8, 2)); Object result = qualRef.apply(context); LOG.debug("{}", result); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELOperatorsTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELOperatorsTest.java index 92258af10bf..5d167665c70 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELOperatorsTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELOperatorsTest.java @@ -127,6 +127,8 @@ private static Collection data() { {"(function(a: context) {b: \"b\", c: \"c\"}) instance of function>->context", Boolean.TRUE , null}, {"(function(a: context) \"foo\") instance of function>->string", Boolean.FALSE , null}, {"(function(a: context, b: context) \"foo\") instance of function,context>->string", Boolean.TRUE , null}, + {"range(\"[1..3]\") instance of range", Boolean.TRUE , null}, + {"range(\"[1..3]\") instance of range", Boolean.FALSE , null} }; return addAdditionalParameters(cases, false); } diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionHelperTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionHelperTest.java index 9143712030a..b8d51268fa7 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionHelperTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionHelperTest.java @@ -30,7 +30,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.feel.lang.impl.NamedParameter; import org.kie.dmn.feel.runtime.FEELFunction; @@ -44,7 +44,7 @@ class BaseFEELFunctionHelperTest { @BeforeEach public void setUp() { - ctx = CodegenTestUtil.newEmptyEvaluationContext(); + ctx = EvaluationContextTestUtil.newEmptyEvaluationContext(); } @Test diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionTest.java index f5deff2214d..af32bcc9c6a 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.feel.lang.ast.BaseNode; import org.kie.dmn.feel.lang.ast.InfixOpNode; @@ -51,7 +51,7 @@ class BaseFEELFunctionTest { @BeforeEach public void setUp() { - ctx = CodegenTestUtil.newEmptyEvaluationContext(); + ctx = EvaluationContextTestUtil.newEmptyEvaluationContext(); } @Test diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/ScorerHelperTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/ScorerHelperTest.java index 71f4bf6934f..9cc4098d8cb 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/ScorerHelperTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/ScorerHelperTest.java @@ -24,7 +24,7 @@ import java.util.Random; import org.junit.jupiter.api.Test; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.feel.lang.impl.NamedParameter; @@ -443,7 +443,7 @@ void typeIdentityOfParameters() { retrieved = ScoreHelper.typeIdentityOfParameters.applyAsInt(compares); assertThat(retrieved).isEqualTo(500); - originalInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String" }; + originalInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String" }; adaptedInput = originalInput; parameterTypes = new Class[] { EvaluationContext.class, String.class }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, parameterTypes); @@ -451,7 +451,7 @@ void typeIdentityOfParameters() { assertThat(retrieved).isEqualTo(1000); originalInput = new Object[] { "String" }; - adaptedInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String" }; + adaptedInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String" }; parameterTypes = new Class[] { EvaluationContext.class, String.class }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, parameterTypes); retrieved = ScoreHelper.typeIdentityOfParameters.applyAsInt(compares); @@ -465,7 +465,7 @@ void typeIdentityOfParameters() { assertThat(retrieved).isEqualTo(0); originalInput = new Object[] { "String", 34 }; - adaptedInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String", 34 }; + adaptedInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String", 34 }; parameterTypes = new Class[] { EvaluationContext.class, String.class, Integer.class }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, parameterTypes); retrieved = ScoreHelper.typeIdentityOfParameters.applyAsInt(compares); @@ -491,7 +491,7 @@ void typeIdentityOfParameters() { retrieved = ScoreHelper.typeIdentityOfParameters.applyAsInt(compares); assertThat(retrieved).isEqualTo(0); - originalInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String" }; + originalInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String" }; parameterTypes = new Class[] { EvaluationContext.class, Integer.class }; compares = new ScoreHelper.Compares(originalInput, null, parameterTypes); retrieved = ScoreHelper.typeIdentityOfParameters.applyAsInt(compares); @@ -531,20 +531,20 @@ void coercedToVarargs() { retrieved = ScoreHelper.coercedToVarargs.applyAsInt(compares); assertThat(retrieved).isEqualTo(coercedToVarargsScore); - originalInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String", 34 }; + originalInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String", 34 }; adaptedInput = new Object[] { new Object[] {"String", 34} }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, null); retrieved = ScoreHelper.coercedToVarargs.applyAsInt(compares); assertThat(retrieved).isEqualTo(coercedToVarargsScore); originalInput = new Object[] { "String", 34 }; - adaptedInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), new Object[] {"String", 34} }; + adaptedInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), new Object[] {"String", 34} }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, null); retrieved = ScoreHelper.coercedToVarargs.applyAsInt(compares); assertThat(retrieved).isEqualTo(coercedToVarargsScore); - originalInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String", 34 }; - adaptedInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), new Object[] {"String", 34} }; + originalInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String", 34 }; + adaptedInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), new Object[] {"String", 34} }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, null); retrieved = ScoreHelper.coercedToVarargs.applyAsInt(compares); assertThat(retrieved).isEqualTo(coercedToVarargsScore); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/util/CompilerUtils.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/util/CompilerUtils.java index c201ec39ca3..3c645548ed0 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/util/CompilerUtils.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/util/CompilerUtils.java @@ -25,7 +25,6 @@ import com.github.javaparser.ast.stmt.BlockStmt; import org.antlr.v4.runtime.tree.ParseTree; import org.kie.dmn.feel.codegen.feel11.ASTCompilerVisitor; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; import org.kie.dmn.feel.codegen.feel11.CompiledFEELExpression; import org.kie.dmn.feel.codegen.feel11.CompilerBytecodeLoader; import org.kie.dmn.feel.lang.EvaluationContext; @@ -100,7 +99,7 @@ public static CompiledFEELExpression parseInterpreted(String input, Map org.apache.maven.plugins maven-scm-plugin - 1.11.1 run-tck-suite From fab792f0c280fcbb7360a1160832fbbac35a1f4d Mon Sep 17 00:00:00 2001 From: Jason Porter Date: Tue, 15 Oct 2024 13:42:25 -0600 Subject: [PATCH 133/141] Renaming DISCLAIMER file Signed-off-by: Jason Porter --- DISCLAIMER => DISCLAIMER-WIP | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename DISCLAIMER => DISCLAIMER-WIP (100%) diff --git a/DISCLAIMER b/DISCLAIMER-WIP similarity index 100% rename from DISCLAIMER rename to DISCLAIMER-WIP From da37e6656f432c15d4f725c6b93f8b288733d196 Mon Sep 17 00:00:00 2001 From: Gabriele Cardosi Date: Wed, 16 Oct 2024 10:14:59 +0200 Subject: [PATCH 134/141] [incubator-kie-issues#1528] Implement DMNEvent reporting inside DMNConditionalEvaluator. (#6124) * [incubator-kie-issues#1528] Implement DMNEvent reporting inside DMNConditionalEvaluator. * [incubator-kie-issues#1528] Implement DMNEvent reporting inside DMNConditionalEvaluator. * [incubator-kie-issues#1528] Fix RiskScore_Simple.dmn * [incubator-kie-issues#1528] Fix id used to track conditional evaluation --------- Co-authored-by: Gabriele-Cardosi --- .../kie/dmn/api/core}/EvaluatorResult.java | 2 +- .../AfterConditionalEvaluationEvent.java | 33 +++ .../event/AfterEvaluateConditionalEvent.java | 33 +++ .../core/event/DMNRuntimeEventListener.java | 12 + .../jsr223/JSR223DTExpressionEvaluator.java | 4 +- .../JSR223LiteralExpressionEvaluator.java | 4 +- .../dmn/core/api/DMNExpressionEvaluator.java | 1 + .../dmn/core/ast/DMNConditionalEvaluator.java | 39 ++- .../kie/dmn/core/ast/DMNContextEvaluator.java | 4 +- .../core/ast/DMNDTExpressionEvaluator.java | 5 +- .../core/ast/DMNDecisionServiceEvaluator.java | 4 +- ...ionServiceFunctionDefinitionEvaluator.java | 4 +- .../kie/dmn/core/ast/DMNFilterEvaluator.java | 4 +- .../ast/DMNFunctionDefinitionEvaluator.java | 4 +- .../dmn/core/ast/DMNInvocationEvaluator.java | 4 +- .../dmn/core/ast/DMNIteratorEvaluator.java | 4 +- .../kie/dmn/core/ast/DMNListEvaluator.java | 4 +- .../ast/DMNLiteralExpressionEvaluator.java | 5 +- .../dmn/core/ast/DMNRelationEvaluator.java | 4 +- .../kie/dmn/core/ast/EvaluatorResultImpl.java | 2 +- .../core/compiler/DMNEvaluatorCompiler.java | 2 +- .../DMNAlphaNetworkEvaluatorImpl.java | 2 +- .../AfterConditionalEvaluationEventImpl.java | 43 ++++ .../AfterEvaluateConditionalEventImpl.java | 43 ++++ .../impl/DMNRuntimeEventManagerUtils.java | 18 ++ .../org/kie/dmn/core/impl/DMNRuntimeImpl.java | 2 +- ...AbstractDMNKiePMMLInvocationEvaluator.java | 4 +- .../pmml/AbstractPMMLInvocationEvaluator.java | 4 +- .../org/kie/dmn/core/DMNInputRuntimeTest.java | 58 +++++ .../java/org/kie/dmn/core/DMNRuntimeTest.java | 2 +- .../core/ast/DMNConditionalEvaluatorTest.java | 175 ++++++++++++++ .../dmn/core/ast/DMNContextEvaluatorTest.java | 2 +- .../impl/DMNRuntimeEventManagerUtilsTest.java | 78 ++++++ .../tests/core/v1_1/DMNRuntimeTest.java | 2 +- .../signavio/MultiInstanceDecisionLogic.java | 4 +- .../valid_models/DMNv1_5/RiskScore_Simple.dmn | 228 ++++++++++++++++++ .../core/ast/DMNConditionalEvaluator.java | 4 +- .../core/ast/DMNFilterEvaluator.java | 5 +- .../core/ast/DMNIteratorEvaluator.java | 4 +- 39 files changed, 797 insertions(+), 59 deletions(-) rename kie-dmn/{kie-dmn-core/src/main/java/org/kie/dmn/core/api => kie-dmn-api/src/main/java/org/kie/dmn/api/core}/EvaluatorResult.java (96%) create mode 100644 kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterConditionalEvaluationEvent.java create mode 100644 kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateConditionalEvent.java create mode 100644 kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterConditionalEvaluationEventImpl.java create mode 100644 kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateConditionalEventImpl.java create mode 100644 kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNConditionalEvaluatorTest.java create mode 100644 kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtilsTest.java create mode 100644 kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Simple.dmn diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/EvaluatorResult.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/EvaluatorResult.java similarity index 96% rename from kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/EvaluatorResult.java rename to kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/EvaluatorResult.java index 7ef00e8ac0b..078bac9ce08 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/EvaluatorResult.java +++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/EvaluatorResult.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.kie.dmn.core.api; +package org.kie.dmn.api.core; public interface EvaluatorResult { diff --git a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterConditionalEvaluationEvent.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterConditionalEvaluationEvent.java new file mode 100644 index 00000000000..06b4050772f --- /dev/null +++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterConditionalEvaluationEvent.java @@ -0,0 +1,33 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.api.core.event; + +import org.kie.dmn.api.core.EvaluatorResult; + +/** + * Event fired after the then/else branches of an if condition are evaluated + * @see AfterEvaluateConditionalEvent + */ +public interface AfterConditionalEvaluationEvent { + + EvaluatorResult getEvaluatorResultResult(); + + String getExecutedId(); + +} diff --git a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateConditionalEvent.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateConditionalEvent.java new file mode 100644 index 00000000000..b0fb5f2c623 --- /dev/null +++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateConditionalEvent.java @@ -0,0 +1,33 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.api.core.event; + +import org.kie.dmn.api.core.EvaluatorResult; + +/** + * Event fired after the if if conditional is evaluated + * + */ +public interface AfterEvaluateConditionalEvent { + + EvaluatorResult getEvaluatorResultResult(); + + String getExecutedId(); + +} diff --git a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/DMNRuntimeEventListener.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/DMNRuntimeEventListener.java index ddb6e890938..258d3f8b6b8 100644 --- a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/DMNRuntimeEventListener.java +++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/DMNRuntimeEventListener.java @@ -47,4 +47,16 @@ default void afterInvokeBKM(AfterInvokeBKMEvent event) {} default void beforeEvaluateAll(BeforeEvaluateAllEvent event) {} default void afterEvaluateAll(AfterEvaluateAllEvent event) {} + + /** + * Fired after the if if conditional is evaluated + * + */ + default void afterEvaluateConditional(AfterEvaluateConditionalEvent event) {} + + /** + * Fired after the then/else branches of an if condition are evaluated + * + */ + default void afterConditionalEvaluation(AfterConditionalEvaluationEvent event) {} } diff --git a/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java b/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java index ff114e2eb44..afa8009e4d7 100644 --- a/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java @@ -35,8 +35,8 @@ import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.api.feel.runtime.events.FEELEventListener; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.DMNDTExpressionEvaluator; import org.kie.dmn.core.ast.DMNDTExpressionEvaluator.EventResults; import org.kie.dmn.core.ast.EvaluatorResultImpl; diff --git a/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223LiteralExpressionEvaluator.java b/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223LiteralExpressionEvaluator.java index 5b3a5302298..48630c6459e 100644 --- a/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223LiteralExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223LiteralExpressionEvaluator.java @@ -21,8 +21,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.slf4j.Logger; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/DMNExpressionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/DMNExpressionEvaluator.java index c40ebcb323d..c6237641674 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/DMNExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/DMNExpressionEvaluator.java @@ -19,6 +19,7 @@ package org.kie.dmn.core.api; import org.kie.dmn.api.core.DMNResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; /** diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNConditionalEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNConditionalEvaluator.java index 7da9445a81a..8f89bb1fcbb 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNConditionalEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNConditionalEvaluator.java @@ -18,15 +18,20 @@ */ package org.kie.dmn.core.ast; +import java.util.HashMap; +import java.util.Map; + import org.kie.dmn.api.core.DMNMessage; import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; +import org.kie.dmn.core.impl.DMNRuntimeEventManagerUtils; import org.kie.dmn.core.util.Msg; import org.kie.dmn.core.util.MsgUtil; +import org.kie.dmn.model.api.Conditional; import org.kie.dmn.model.api.DMNElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,6 +45,7 @@ public class DMNConditionalEvaluator implements DMNExpressionEvaluator { private DMNExpressionEvaluator elseEvaluator; private DMNElement node; private String name; + private final Map evaluatorIdMap = new HashMap<>(); public DMNConditionalEvaluator(String name, DMNElement node, DMNExpressionEvaluator ifEvaluator, DMNExpressionEvaluator thenEvaluator, DMNExpressionEvaluator elseEvaluator) { this.name = name; @@ -47,6 +53,14 @@ public DMNConditionalEvaluator(String name, DMNElement node, DMNExpressionEvalua this.ifEvaluator = ifEvaluator; this.thenEvaluator = thenEvaluator; this.elseEvaluator = elseEvaluator; + Conditional conditional = node.getChildren().stream() + .filter(c -> c instanceof Conditional) + .map(c -> (Conditional) c) + .findFirst() + .orElseThrow(() -> new RuntimeException("Missing Conditional element inside " + node)); + evaluatorIdMap.put(ifEvaluator, conditional.getIf().getId()); + evaluatorIdMap.put(thenEvaluator, conditional.getThen().getId()); + evaluatorIdMap.put(elseEvaluator, conditional.getElse().getId()); } @Override @@ -54,16 +68,12 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager eventManager, DMNResult d DMNResultImpl result = (DMNResultImpl) dmnr; EvaluatorResult ifEvaluation = ifEvaluator.evaluate(eventManager, result); + String executedId = evaluatorIdMap.get(ifEvaluator); + DMNRuntimeEventManagerUtils.fireAfterEvaluateConditional(eventManager, ifEvaluation, executedId); if (ifEvaluation.getResultType().equals(ResultType.SUCCESS)) { Object ifResult = ifEvaluation.getResult(); - if (ifResult instanceof Boolean) { - if (((Boolean) ifResult).booleanValue()) { - return thenEvaluator.evaluate(eventManager, result); - } else { - return elseEvaluator.evaluate(eventManager, result); - } - } else if (ifResult == null) { - return elseEvaluator.evaluate(eventManager, result); + if (ifResult == null || ifResult instanceof Boolean) { + return manageBooleanOrNullIfResult((Boolean) ifResult, eventManager, result); } else { MsgUtil.reportMessage(logger, DMNMessage.Severity.ERROR, @@ -80,4 +90,13 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager eventManager, DMNResult d return new EvaluatorResultImpl(null, ResultType.FAILURE); } + protected EvaluatorResult manageBooleanOrNullIfResult(Boolean booleanResult, DMNRuntimeEventManager eventManager, DMNResultImpl result) { + DMNExpressionEvaluator evaluatorToUse = booleanResult != null && booleanResult ? thenEvaluator : elseEvaluator; + + EvaluatorResult toReturn = evaluatorToUse.evaluate(eventManager, result); + String executedId = evaluatorIdMap.get(evaluatorToUse); + DMNRuntimeEventManagerUtils.fireAfterConditionalEvaluation(eventManager, toReturn, executedId); + return toReturn; + } + } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java index 4fbb5c0c649..cedf3e309a3 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java @@ -31,8 +31,8 @@ import org.kie.dmn.api.core.DMNType; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.impl.DMNRuntimeEventManagerUtils; import org.kie.dmn.core.impl.DMNRuntimeImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java index 7432b3114c6..8293f82e672 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java @@ -19,7 +19,6 @@ package org.kie.dmn.core.ast; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -32,8 +31,8 @@ import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.impl.DMNRuntimeEventManagerUtils; import org.kie.dmn.core.impl.DMNRuntimeImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceEvaluator.java index 63a6faf1a74..328ee461b02 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceEvaluator.java @@ -33,8 +33,8 @@ import org.kie.dmn.api.core.ast.DecisionServiceNode; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.compiler.DMNCompilerImpl; import org.kie.dmn.core.impl.DMNDecisionResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java index 21ee7e0af6a..00c2c0f50f0 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java @@ -31,8 +31,8 @@ import org.kie.dmn.api.core.ast.DecisionServiceNode; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.DMNFunctionDefinitionEvaluator.FormalParameter; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.impl.DMNRuntimeImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFilterEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFilterEvaluator.java index ccaddaac570..b0120fd57e5 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFilterEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFilterEvaluator.java @@ -28,8 +28,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.IterableRange; import org.kie.dmn.core.util.Msg; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java index c7d6469aaca..902ff74556c 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java @@ -32,8 +32,8 @@ import org.kie.dmn.api.core.ast.DMNNode; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.BaseDMNTypeImpl; import org.kie.dmn.core.impl.DMNContextFEELCtxWrapper; import org.kie.dmn.core.impl.DMNResultImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNInvocationEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNInvocationEvaluator.java index ec42aa0f1ec..44e166bb221 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNInvocationEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNInvocationEvaluator.java @@ -32,8 +32,8 @@ import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNModelImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.Msg; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNIteratorEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNIteratorEvaluator.java index 1abbe18e518..1d73315edee 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNIteratorEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNIteratorEvaluator.java @@ -27,8 +27,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.IterableRange; import org.kie.dmn.core.util.Msg; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNListEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNListEvaluator.java index f0156ddfa9c..0a85a479073 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNListEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNListEvaluator.java @@ -26,8 +26,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.Msg; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNLiteralExpressionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNLiteralExpressionEvaluator.java index 5e42fbc420d..07d1f69390b 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNLiteralExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNLiteralExpressionEvaluator.java @@ -19,7 +19,6 @@ package org.kie.dmn.core.ast; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.kie.dmn.api.core.DMNMessage; @@ -29,8 +28,8 @@ import org.kie.dmn.api.feel.runtime.events.FEELEvent.Severity; import org.kie.dmn.api.feel.runtime.events.FEELEventListener; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.Msg; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNRelationEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNRelationEvaluator.java index 1bb21d824b7..6a971ffba15 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNRelationEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNRelationEvaluator.java @@ -28,8 +28,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.Msg; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/EvaluatorResultImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/EvaluatorResultImpl.java index 73b25ca012b..ed8eb063996 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/EvaluatorResultImpl.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/EvaluatorResultImpl.java @@ -18,7 +18,7 @@ */ package org.kie.dmn.core.ast; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; public class EvaluatorResultImpl implements EvaluatorResult { private final Object result; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java index 9e4ad9d59e9..57b4bc8f12c 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java @@ -38,7 +38,7 @@ import org.kie.dmn.api.core.ast.DMNNode; import org.kie.dmn.api.core.ast.DecisionNode; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.ast.DMNBaseNode; import org.kie.dmn.core.ast.DMNConditionalEvaluator; import org.kie.dmn.core.ast.DMNContextEvaluator; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java index 522eb377438..cbffc8b5c8e 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java @@ -27,7 +27,7 @@ import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.ast.DMNBaseNode; import org.kie.dmn.core.ast.DMNDTExpressionEvaluator; import org.kie.dmn.core.ast.EvaluatorResultImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterConditionalEvaluationEventImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterConditionalEvaluationEventImpl.java new file mode 100644 index 00000000000..5d3c8eb2464 --- /dev/null +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterConditionalEvaluationEventImpl.java @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.core.impl; + +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; + +public class AfterConditionalEvaluationEventImpl implements AfterConditionalEvaluationEvent { + + private final EvaluatorResult evaluatorResult; + private final String executedId; + + public AfterConditionalEvaluationEventImpl(EvaluatorResult evaluatorResult, String executedId) { + this.evaluatorResult = evaluatorResult; + this.executedId = executedId; + } + + @Override + public EvaluatorResult getEvaluatorResultResult() { + return evaluatorResult; + } + + @Override + public String getExecutedId() { + return executedId; + } +} diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateConditionalEventImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateConditionalEventImpl.java new file mode 100644 index 00000000000..4aa97cec111 --- /dev/null +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateConditionalEventImpl.java @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.core.impl; + +import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; +import org.kie.dmn.api.core.EvaluatorResult; + +public class AfterEvaluateConditionalEventImpl implements AfterEvaluateConditionalEvent { + + private final EvaluatorResult evaluatorResult; + private final String executedId; + + public AfterEvaluateConditionalEventImpl(EvaluatorResult evaluatorResult, String executedId) { + this.evaluatorResult = evaluatorResult; + this.executedId = executedId; + } + + @Override + public EvaluatorResult getEvaluatorResultResult() { + return evaluatorResult; + } + + @Override + public String getExecutedId() { + return executedId; + } +} diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java index 23879b1c7af..d4a65088c76 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java @@ -26,8 +26,10 @@ import org.kie.dmn.api.core.ast.BusinessKnowledgeModelNode; import org.kie.dmn.api.core.ast.DecisionNode; import org.kie.dmn.api.core.ast.DecisionServiceNode; +import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; import org.kie.dmn.api.core.event.AfterEvaluateAllEvent; import org.kie.dmn.api.core.event.AfterEvaluateBKMEvent; +import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; import org.kie.dmn.api.core.event.AfterEvaluateContextEntryEvent; import org.kie.dmn.api.core.event.AfterEvaluateDecisionEvent; import org.kie.dmn.api.core.event.AfterEvaluateDecisionServiceEvent; @@ -42,6 +44,7 @@ import org.kie.dmn.api.core.event.BeforeInvokeBKMEvent; import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; +import org.kie.dmn.api.core.EvaluatorResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -149,6 +152,20 @@ public static void fireAfterEvaluateAll(DMNRuntimeEventManagerImpl eventManager, } } + public static void fireAfterEvaluateConditional(DMNRuntimeEventManager eventManager, EvaluatorResult evaluatorResult, String executedId) { + if( eventManager.hasListeners() ) { + AfterEvaluateConditionalEvent event = new AfterEvaluateConditionalEventImpl(evaluatorResult, executedId); + notifyListeners(eventManager, l -> l.afterEvaluateConditional(event)); + } + } + + public static void fireAfterConditionalEvaluation(DMNRuntimeEventManager eventManager, EvaluatorResult evaluatorResult, String idExecuted) { + if( eventManager.hasListeners() ) { + AfterConditionalEvaluationEvent event = new AfterConditionalEvaluationEventImpl(evaluatorResult, idExecuted); + notifyListeners(eventManager, l -> l.afterConditionalEvaluation(event)); + } + } + private static void notifyListeners(DMNRuntimeEventManager eventManager, Consumer consumer) { for( DMNRuntimeEventListener listener : eventManager.getListeners() ) { try { @@ -159,6 +176,7 @@ private static void notifyListeners(DMNRuntimeEventManager eventManager, Consume } } + private DMNRuntimeEventManagerUtils() { // Constructing instances is not allowed for this class } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeImpl.java index 12a3eebea54..203c44f32af 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeImpl.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeImpl.java @@ -45,7 +45,7 @@ import org.kie.dmn.api.core.event.BeforeEvaluateDecisionEvent; import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.core.api.DMNFactory; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.ast.BusinessKnowledgeModelNodeImpl; import org.kie.dmn.core.ast.DMNBaseNode; import org.kie.dmn.core.ast.DMNDecisionServiceEvaluator; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractDMNKiePMMLInvocationEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractDMNKiePMMLInvocationEvaluator.java index 584005239ce..414d1efbc4b 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractDMNKiePMMLInvocationEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractDMNKiePMMLInvocationEvaluator.java @@ -28,8 +28,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.DMNType; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.CompositeTypeImpl; import org.kie.dmn.core.impl.DMNResultImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractPMMLInvocationEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractPMMLInvocationEvaluator.java index 25f6b18a963..fb07f4708ad 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractPMMLInvocationEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractPMMLInvocationEvaluator.java @@ -30,8 +30,8 @@ import org.kie.dmn.api.core.DMNType; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.DMNFunctionDefinitionEvaluator.FormalParameter; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.DMNModelImpl; diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java index 4feaac9d57a..d89ff7ef4ca 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java @@ -19,6 +19,7 @@ package org.kie.dmn.core; import java.math.BigDecimal; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -39,7 +40,11 @@ import org.kie.dmn.api.core.ast.DecisionServiceNode; import org.kie.dmn.api.core.ast.InputDataNode; import org.kie.dmn.api.core.ast.ItemDefNode; +import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; +import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; +import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.core.api.DMNFactory; +import org.kie.dmn.core.api.event.DefaultDMNRuntimeEventListener; import org.kie.dmn.core.util.DMNRuntimeUtil; import static org.assertj.core.api.Assertions.assertThat; @@ -377,6 +382,59 @@ void typeConstraintsChecks(boolean useExecModelCompiler) { assertThat(dmnResult3.getMessages().stream().anyMatch(m -> m.getMessageType().equals(DMNMessageType.ERROR_EVAL_NODE))).isTrue(); } + @ParameterizedTest + @MethodSource("params") + void conditionalIfCheck(boolean useExecModelCompiler) { + init(useExecModelCompiler); + final String ifElementId = "_3C702CE4-E5A0-4B6F-905D-C2621FFFA387"; + final String thenElementId = "_6481FF12-61B5-451C-B775-4143D9B6CD6B"; + final String elseElementId = "_2CD02CB2-6B56-45C4-B461-405E89D45633"; + final DMNRuntime runtime = DMNRuntimeUtil.createRuntime("valid_models/DMNv1_5/RiskScore_Simple.dmn", this.getClass() ); + + + final List afterEvaluateConditionalEvents = new ArrayList<>(); + final List afterConditionalEvaluationEvents = new ArrayList<>(); + runtime.addListener(new DefaultDMNRuntimeEventListener() { + + @Override + public void afterEvaluateConditional(AfterEvaluateConditionalEvent event) { + afterEvaluateConditionalEvents.add(event); + } + + @Override + public void afterConditionalEvaluation(AfterConditionalEvaluationEvent event) { + afterConditionalEvaluationEvents.add(event); + } + + }); + final DMNModel dmnModel = runtime.getModel( + "https://kie.org/dmn/_A3317FB1-7BF8-4904-A5F4-2CD63AF3AEC9", + "DMN_A77074C1-21FE-4F7E-9753-F84661569AFC" ); + assertThat(dmnModel).isNotNull(); + assertThat(dmnModel.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnModel.getMessages())).isFalse(); + + final DMNContext ctx1 = runtime.newContext(); + ctx1.set("Credit Score", "Poor"); + ctx1.set("DTI", 33); + final DMNResult dmnResult1 = runtime.evaluateAll( dmnModel, ctx1 ); + assertThat(dmnResult1.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnResult1.getMessages())).isFalse(); + assertThat( dmnResult1.getContext().get( "Risk Score" )).isEqualTo(BigDecimal.valueOf(50)); + assertThat(afterEvaluateConditionalEvents).hasSize(1).allMatch(event -> event.getExecutedId().equals(ifElementId)); + assertThat(afterConditionalEvaluationEvents).hasSize(1).allMatch(event -> event.getExecutedId().equals(elseElementId)); + + // + afterEvaluateConditionalEvents.clear(); + afterConditionalEvaluationEvents.clear(); + final DMNContext ctx2 = runtime.newContext(); + ctx2.set("Credit Score", "Excellent"); + ctx2.set("DTI", 10); + final DMNResult dmnResult2 = runtime.evaluateAll( dmnModel, ctx2 ); + assertThat(dmnResult2.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnResult1.getMessages())).isFalse(); + assertThat( dmnResult2.getContext().get( "Risk Score" )).isEqualTo(BigDecimal.valueOf(20)); + assertThat(afterEvaluateConditionalEvents).hasSize(1).allMatch(event -> event.getExecutedId().equals(ifElementId)); + assertThat(afterConditionalEvaluationEvents).hasSize(1).allMatch(event -> event.getExecutedId().equals(thenElementId)); + } + @ParameterizedTest @MethodSource("params") void dmnInputDataNodeTypeTest(boolean useExecModelCompiler) { diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNRuntimeTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNRuntimeTest.java index 89e261436f7..13a044a6576 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNRuntimeTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNRuntimeTest.java @@ -63,7 +63,7 @@ import org.kie.dmn.api.core.event.BeforeEvaluateDecisionTableEvent; import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.core.api.DMNFactory; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.ast.DMNContextEvaluator; import org.kie.dmn.core.ast.DecisionNodeImpl; import org.kie.dmn.core.ast.EvaluatorResultImpl; diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNConditionalEvaluatorTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNConditionalEvaluatorTest.java new file mode 100644 index 00000000000..4514ce77ce6 --- /dev/null +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNConditionalEvaluatorTest.java @@ -0,0 +1,175 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.core.ast; + +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; +import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; +import org.kie.dmn.api.core.event.DMNRuntimeEventListener; +import org.kie.dmn.api.core.event.DMNRuntimeEventManager; +import org.kie.dmn.core.api.DMNExpressionEvaluator; +import org.kie.dmn.core.impl.DMNResultImpl; +import org.kie.dmn.model.api.ChildExpression; +import org.kie.dmn.model.api.Conditional; +import org.kie.dmn.model.api.DMNElement; +import org.kie.dmn.model.api.DMNModelInstrumentedBase; +import org.kie.dmn.model.api.Expression; +import org.mockito.ArgumentCaptor; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class DMNConditionalEvaluatorTest { + + private static final String ID_ELEMENT_ID = "ID_ELEMENT_ID"; + private static final String THEN_ELEMENT_ID = "THEN_ELEMENT_ID"; + private static final String ELSE_ELEMENT_ID = "ELSE_ELEMENT_ID"; + private static DMNRuntimeEventManager eventManagerMock; + private static DMNRuntimeEventListener spiedListener; + private static EvaluatorResult ifEvaluationMock; + private static EvaluatorResult thenEvaluationMock; + private static EvaluatorResult elseEvaluationMock; + private static DMNResultImpl dmnResultMock; + private static DMNConditionalEvaluator dmnConditionalEvaluator; + + @BeforeAll + static void setUp() { + spiedListener = spy(DMNRuntimeEventListener.class); + Set listeners = Collections.singleton(spiedListener); + eventManagerMock = mock(DMNRuntimeEventManager.class); + when(eventManagerMock.hasListeners()).thenReturn(true); + when(eventManagerMock.getListeners()).thenReturn(listeners); + ifEvaluationMock = mock(EvaluatorResult.class); + thenEvaluationMock = mock(EvaluatorResult.class); + elseEvaluationMock = mock(EvaluatorResult.class); + + dmnResultMock = mock(DMNResultImpl.class); + DMNExpressionEvaluator ifEvaluatorMock = mock(DMNExpressionEvaluator.class); + DMNExpressionEvaluator thenEvaluatorMock = mock(DMNExpressionEvaluator.class); + DMNExpressionEvaluator elseEvaluatorMock = mock(DMNExpressionEvaluator.class); + + when(ifEvaluatorMock.evaluate(eventManagerMock, dmnResultMock)).thenReturn(ifEvaluationMock); + when(thenEvaluatorMock.evaluate(eventManagerMock, dmnResultMock)).thenReturn(thenEvaluationMock); + when(elseEvaluatorMock.evaluate(eventManagerMock, dmnResultMock)).thenReturn(elseEvaluationMock); + + ChildExpression ifMock = mock(ChildExpression.class); + when(ifMock.getId()).thenReturn(ID_ELEMENT_ID); + + ChildExpression thenMock = mock(ChildExpression.class); + when(thenMock.getId()).thenReturn(THEN_ELEMENT_ID); + + ChildExpression elseMock = mock(ChildExpression.class); + when(elseMock.getId()).thenReturn(ELSE_ELEMENT_ID); + + Conditional conditionalMock = mock(Conditional.class); + when(conditionalMock.getIf()).thenReturn(ifMock); + when(conditionalMock.getThen()).thenReturn(thenMock); + when(conditionalMock.getElse()).thenReturn(elseMock); + + List nodeChildren = Collections.singletonList(conditionalMock); + DMNElement nodeMock = mock(DMNElement.class); + when(nodeMock.getChildren()).thenReturn(nodeChildren); + + dmnConditionalEvaluator = new DMNConditionalEvaluator("name", + nodeMock, + ifEvaluatorMock, + thenEvaluatorMock, + elseEvaluatorMock); + } + + @BeforeEach + void setup() { + reset(spiedListener); + } + + @Test + void evaluateListenerInvocation() { + when(ifEvaluationMock.getResultType()).thenReturn(EvaluatorResult.ResultType.FAILURE); // not interested in + // nested execution + + dmnConditionalEvaluator.evaluate(eventManagerMock, dmnResultMock); + ArgumentCaptor evaluateConditionalEventArgumentCaptor = + ArgumentCaptor.forClass(AfterEvaluateConditionalEvent.class); + verify(spiedListener).afterEvaluateConditional(evaluateConditionalEventArgumentCaptor.capture()); + AfterEvaluateConditionalEvent evaluateConditionalEvent = evaluateConditionalEventArgumentCaptor.getValue(); + assertThat(evaluateConditionalEvent).isNotNull(); + assertThat(evaluateConditionalEvent.getEvaluatorResultResult()).isEqualTo(ifEvaluationMock); + assertThat(evaluateConditionalEvent.getExecutedId()).isEqualTo(ID_ELEMENT_ID); + } + + @Test + void evaluateManageBooleanOrNullIfResultInvocation() { + when(ifEvaluationMock.getResultType()).thenReturn(EvaluatorResult.ResultType.SUCCESS); + when(ifEvaluationMock.getResult()).thenReturn(true); + + DMNConditionalEvaluator spiedDmnConditionalEvaluator = spy(dmnConditionalEvaluator); + spiedDmnConditionalEvaluator.evaluate(eventManagerMock, dmnResultMock); + verify(spiedDmnConditionalEvaluator).manageBooleanOrNullIfResult(true, eventManagerMock, dmnResultMock); + } + + @Test + void manageBooleanOrNullIfResultWithTrue() { + dmnConditionalEvaluator.manageBooleanOrNullIfResult(true, eventManagerMock, dmnResultMock); + ArgumentCaptor afterConditionalEvaluationEventArgumentCaptor = + ArgumentCaptor.forClass(AfterConditionalEvaluationEvent.class); + verify(spiedListener).afterConditionalEvaluation(afterConditionalEvaluationEventArgumentCaptor.capture()); + AfterConditionalEvaluationEvent conditionalEvaluationEvent = + afterConditionalEvaluationEventArgumentCaptor.getValue(); + assertThat(conditionalEvaluationEvent).isNotNull(); + assertThat(conditionalEvaluationEvent.getEvaluatorResultResult()).isEqualTo(thenEvaluationMock); + assertThat(conditionalEvaluationEvent.getExecutedId()).isEqualTo(THEN_ELEMENT_ID); + } + + @Test + void manageBooleanOrNullIfResultWithFalse() { + dmnConditionalEvaluator.manageBooleanOrNullIfResult(false, eventManagerMock, dmnResultMock); + ArgumentCaptor afterConditionalEvaluationEventArgumentCaptor = + ArgumentCaptor.forClass(AfterConditionalEvaluationEvent.class); + verify(spiedListener).afterConditionalEvaluation(afterConditionalEvaluationEventArgumentCaptor.capture()); + AfterConditionalEvaluationEvent conditionalEvaluationEvent = + afterConditionalEvaluationEventArgumentCaptor.getValue(); + assertThat(conditionalEvaluationEvent).isNotNull(); + assertThat(conditionalEvaluationEvent.getEvaluatorResultResult()).isEqualTo(elseEvaluationMock); + assertThat(conditionalEvaluationEvent.getExecutedId()).isEqualTo(ELSE_ELEMENT_ID); + } + + @Test + void manageBooleanOrNullIfResultWithNull() { + dmnConditionalEvaluator.manageBooleanOrNullIfResult(null, eventManagerMock, dmnResultMock); + ArgumentCaptor afterConditionalEvaluationEventArgumentCaptor = + ArgumentCaptor.forClass(AfterConditionalEvaluationEvent.class); + verify(spiedListener).afterConditionalEvaluation(afterConditionalEvaluationEventArgumentCaptor.capture()); + AfterConditionalEvaluationEvent conditionalEvaluationEvent = + afterConditionalEvaluationEventArgumentCaptor.getValue(); + assertThat(conditionalEvaluationEvent).isNotNull(); + assertThat(conditionalEvaluationEvent.getEvaluatorResultResult()).isEqualTo(elseEvaluationMock); + assertThat(conditionalEvaluationEvent.getExecutedId()).isEqualTo(ELSE_ELEMENT_ID); + } +} \ No newline at end of file diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNContextEvaluatorTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNContextEvaluatorTest.java index 066c5439439..ab1f01394f0 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNContextEvaluatorTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNContextEvaluatorTest.java @@ -31,7 +31,7 @@ import org.kie.dmn.api.core.ast.DecisionNode; import org.kie.dmn.core.api.DMNExpressionEvaluator; import org.kie.dmn.core.api.DMNFactory; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.impl.DMNDecisionResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.impl.DMNResultImplFactory; diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtilsTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtilsTest.java new file mode 100644 index 00000000000..1a78b34fe8c --- /dev/null +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtilsTest.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.core.impl; + +import java.util.Collections; +import java.util.Set; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; +import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; +import org.kie.dmn.api.core.event.DMNRuntimeEventListener; +import org.kie.dmn.api.core.event.DMNRuntimeEventManager; +import org.mockito.ArgumentCaptor; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class DMNRuntimeEventManagerUtilsTest { + + private static DMNRuntimeEventManager eventManagerMock; + private static DMNRuntimeEventListener spiedListener; + + @BeforeAll + static void setUp() { + spiedListener = spy(DMNRuntimeEventListener.class); + Set listeners = Collections.singleton(spiedListener); + eventManagerMock = mock(DMNRuntimeEventManager.class); + when(eventManagerMock.hasListeners()).thenReturn(true); + when(eventManagerMock.getListeners()).thenReturn(listeners); + } + + @Test + void fireAfterEvaluateConditional() { + EvaluatorResult evaluatorResult = mock(EvaluatorResult.class); + String executedId = "EXECUTED_ID"; + DMNRuntimeEventManagerUtils.fireAfterEvaluateConditional(eventManagerMock, evaluatorResult, executedId); + ArgumentCaptor evaluateConditionalEventArgumentCaptor = ArgumentCaptor.forClass(AfterEvaluateConditionalEvent.class); + verify(spiedListener).afterEvaluateConditional (evaluateConditionalEventArgumentCaptor.capture()); + AfterEvaluateConditionalEvent evaluateConditionalEvent = evaluateConditionalEventArgumentCaptor.getValue(); + assertThat(evaluateConditionalEvent).isNotNull(); + assertThat(evaluateConditionalEvent.getEvaluatorResultResult()).isEqualTo(evaluatorResult); + assertThat(evaluateConditionalEvent.getExecutedId()).isEqualTo(executedId); + } + + @Test + void fireAfterConditionalEvaluation() { + EvaluatorResult evaluatorResult = mock(EvaluatorResult.class); + String executedId = "EXECUTED_ID"; + DMNRuntimeEventManagerUtils.fireAfterConditionalEvaluation(eventManagerMock, evaluatorResult, executedId); + ArgumentCaptor conditionalEvaluationEventArgumentCaptor = ArgumentCaptor.forClass(AfterConditionalEvaluationEvent.class); + verify(spiedListener).afterConditionalEvaluation (conditionalEvaluationEventArgumentCaptor.capture()); + AfterConditionalEvaluationEvent evaluateConditionalEvent = conditionalEvaluationEventArgumentCaptor.getValue(); + assertThat(evaluateConditionalEvent).isNotNull(); + assertThat(evaluateConditionalEvent.getEvaluatorResultResult()).isEqualTo(evaluatorResult); + assertThat(evaluateConditionalEvent.getExecutedId()).isEqualTo(executedId); + } +} \ No newline at end of file diff --git a/kie-dmn/kie-dmn-legacy-tests/src/test/java/org/kie/dmn/legacy/tests/core/v1_1/DMNRuntimeTest.java b/kie-dmn/kie-dmn-legacy-tests/src/test/java/org/kie/dmn/legacy/tests/core/v1_1/DMNRuntimeTest.java index b5443e3e861..e562d67e1aa 100644 --- a/kie-dmn/kie-dmn-legacy-tests/src/test/java/org/kie/dmn/legacy/tests/core/v1_1/DMNRuntimeTest.java +++ b/kie-dmn/kie-dmn-legacy-tests/src/test/java/org/kie/dmn/legacy/tests/core/v1_1/DMNRuntimeTest.java @@ -58,7 +58,7 @@ import org.kie.dmn.api.core.event.BeforeEvaluateDecisionTableEvent; import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.core.api.DMNFactory; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.ast.DMNContextEvaluator; import org.kie.dmn.core.ast.DecisionNodeImpl; import org.kie.dmn.core.ast.EvaluatorResultImpl; diff --git a/kie-dmn/kie-dmn-signavio/src/main/java/org/kie/dmn/signavio/MultiInstanceDecisionLogic.java b/kie-dmn/kie-dmn-signavio/src/main/java/org/kie/dmn/signavio/MultiInstanceDecisionLogic.java index 542b7c3ff91..aab6c9897d5 100644 --- a/kie-dmn/kie-dmn-signavio/src/main/java/org/kie/dmn/signavio/MultiInstanceDecisionLogic.java +++ b/kie-dmn/kie-dmn-signavio/src/main/java/org/kie/dmn/signavio/MultiInstanceDecisionLogic.java @@ -33,8 +33,8 @@ import org.kie.dmn.api.core.ast.DMNNode; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.DMNBaseNode; import org.kie.dmn.core.ast.DecisionNodeImpl; import org.kie.dmn.core.ast.EvaluatorResultImpl; diff --git a/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Simple.dmn b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Simple.dmn new file mode 100644 index 00000000000..ea0d40e36a1 --- /dev/null +++ b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Simple.dmn @@ -0,0 +1,228 @@ + + + + string + + "Poor", "Fair", "Excellent" + + + + string + + "High", "Medium", "Low" + + + + string + + "Qualified", "Not Qualified" + + + + + + + + + + + + + + + + + + + + Credit Score + + + + + DTI + + + + + + + "Poor" + + + - + + + 30 + + + // Your annotations here + + + + + "Fair" + + + - + + + 20 + + + + + + + + "Excellent" + + + - + + + 10 + + + + + + + + - + + + > 40 + + + 30 + + + + + + + + - + + + [20..40] + + + 20 + + + + + + + + - + + + < 20 + + + 10 + + + + + + + + + + + + + + + + Risk Score <= 30 + + + + + "Qualified" + + + + + "Not Qualified" + + + + + + + + + + 60 + 145 + 118 + 118 + 240 + + + 120 + + + 60 + 145 + 118 + 118 + 240 + + + 190 + + + 190 + + + 60 + 145 + 118 + 118 + 240 + + + 232 + + + 232 + + + 190 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNConditionalEvaluator.java b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNConditionalEvaluator.java index 4a2a1e15586..7821ce36724 100644 --- a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNConditionalEvaluator.java +++ b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNConditionalEvaluator.java @@ -22,8 +22,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNFilterEvaluator.java b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNFilterEvaluator.java index 167a6bd01ad..f5482b7b7c0 100644 --- a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNFilterEvaluator.java +++ b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNFilterEvaluator.java @@ -18,7 +18,6 @@ */ package org.kie.dmn.trisotech.core.ast; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -29,8 +28,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNIteratorEvaluator.java b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNIteratorEvaluator.java index 0c5a30c0eb7..6536b46adbf 100644 --- a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNIteratorEvaluator.java +++ b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNIteratorEvaluator.java @@ -26,8 +26,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.MsgUtil; From cb15b1a324ef29adc503ccf806f0bbe68c4312ff Mon Sep 17 00:00:00 2001 From: Paolo Bizzarri Date: Thu, 17 Oct 2024 08:16:43 +0200 Subject: [PATCH 135/141] [NO ISSUE] Migrate to JUnit5 drools model (#6128) * Migrated first parameter tests * More tests migrated to JUnit5 * More tests migrated to JUnit5 * Infrastructure to migrate parameterized tests * Migrated more tests * More tests migrated * Keep migrating * Migrated more tests * Migrated more tests * Migrated more tests * Migrated more tests * Migrated even more tests * Migrated more tests to JUnit5 * Migrated more tests. removed unused imports * More tests migrated. * More tests migrated to JUnit5 * Migrated more tests * Migrated all the tests in model codegen * All tests migrated to JUnit5 * Missed fix --- drools-model/drools-canonical-model/pom.xml | 7 +- .../model/operators/MatchesOperatorTest.java | 6 +- .../drools/model/util/OperatorUtilsTest.java | 2 +- drools-model/drools-model-codegen/pom.xml | 32 +- .../codegen/execmodel/AccumulateTest.java | 803 +++++++++-------- .../codegen/execmodel/BaseModelTest.java | 78 +- .../codegen/execmodel/BetaConditionTest.java | 66 +- .../BigPojoExecModelGenerationTest.java | 2 +- .../model/codegen/execmodel/BindingTest.java | 126 +-- .../codegen/execmodel/BuildFromDescrTest.java | 2 +- .../codegen/execmodel/BuildFromKJarTest.java | 3 +- .../model/codegen/execmodel/CepTest.java | 279 +++--- .../model/codegen/execmodel/ChannelTest.java | 25 +- .../execmodel/CompilationFailuresTest.java | 121 +-- .../model/codegen/execmodel/CompilerTest.java | 821 ++++++++++-------- .../codegen/execmodel/ComplexRulesTest.java | 208 +++-- .../execmodel/ConditionalExprTest.java | 63 +- .../ConstraintNormalizationTest.java | 142 +-- .../codegen/execmodel/ConstraintTest.java | 65 +- .../CustomConstraintOperatorTest.java | 2 +- ...DeclaredTypeDifferentKJarIncludesTest.java | 31 +- .../codegen/execmodel/DeclaredTypesTest.java | 112 +-- .../model/codegen/execmodel/DowncastTest.java | 14 +- .../codegen/execmodel/DroolsContextTest.java | 35 +- .../model/codegen/execmodel/EnumTest.java | 22 +- .../model/codegen/execmodel/EvalTest.java | 160 ++-- .../codegen/execmodel/ExisistentialTest.java | 98 ++- .../execmodel/ExternalisedLambdaTest.java | 78 +- .../model/codegen/execmodel/FromTest.java | 282 +++--- .../codegen/execmodel/FunctionsTest.java | 77 +- .../execmodel/GeneratedClassNamesTest.java | 46 +- .../model/codegen/execmodel/GenericsTest.java | 39 +- .../execmodel/GetterOverloadingTest.java | 63 +- .../model/codegen/execmodel/GlobalTest.java | 112 +-- .../model/codegen/execmodel/GroupByTest.java | 232 ++--- .../codegen/execmodel/HalfBinaryTest.java | 91 +- .../codegen/execmodel/HierarchyRulesTest.java | 15 +- .../model/codegen/execmodel/InTest.java | 37 +- .../execmodel/IncrementalCompilationTest.java | 127 +-- .../model/codegen/execmodel/IndexTest.java | 139 +-- .../execmodel/InternalMatchGroupTest.java | 13 +- .../codegen/execmodel/KieBaseBuilderTest.java | 21 +- .../codegen/execmodel/KieBuilderTest.java | 2 +- .../codegen/execmodel/KjarBuildTest.java | 2 +- .../codegen/execmodel/ListenersTest.java | 14 +- .../MapInitializationDrools3800Test.java | 21 +- .../execmodel/MaterializedLambdaTest.java | 21 +- .../execmodel/ModelBuilderImplTest.java | 6 +- .../execmodel/ModelSourceClassTest.java | 6 +- .../codegen/execmodel/MultiKieBaseTest.java | 38 +- .../codegen/execmodel/MvelDialectMapTest.java | 22 +- .../codegen/execmodel/MvelDialectTest.java | 431 +++++---- .../codegen/execmodel/MvelOperatorsTest.java | 191 ++-- .../execmodel/NamedConsequencesTest.java | 120 +-- .../codegen/execmodel/NativeCompilerTest.java | 16 +- .../codegen/execmodel/NodeSharingTest.java | 116 +-- .../execmodel/NullSafeDereferencingTest.java | 98 ++- ...StringArithmeticOperationCoercionTest.java | 122 +-- .../model/codegen/execmodel/OOPathTest.java | 105 ++- .../codegen/execmodel/OnlyExecModelTest.java | 18 +- .../codegen/execmodel/OnlyPatternTest.java | 20 +- .../model/codegen/execmodel/OrTest.java | 74 +- .../execmodel/PackagesIsolationTest.java | 32 +- .../PrimitiveConversionErrorsTest.java | 118 ++- .../PropertyReactivityMatrixTest.java | 201 +++-- .../execmodel/PropertyReactivityTest.java | 535 +++++++----- .../codegen/execmodel/PrototypeTest.java | 2 +- .../execmodel/PrototypesAllowedTest.java | 2 +- .../model/codegen/execmodel/QueryTest.java | 235 ++--- .../codegen/execmodel/RuleAttributesTest.java | 86 +- .../SegmentPrototypeExpressionTest.java | 2 +- .../codegen/execmodel/TextBlockTest.java | 14 +- .../model/codegen/execmodel/ToStringTest.java | 2 +- .../codegen/execmodel/TypeCoercionTest.java | 195 +++-- .../execmodel/TypeDeclarationTest.java | 57 +- .../execmodel/TypeObjectCoercionTest.java | 177 ++-- .../execmodel/UseClassFieldsInRulesTest.java | 103 ++- .../ObjectTypeNodeCompilerTest.java | 77 +- .../execmodel/assembler/AssemblerTest.java | 2 +- .../bigdecimaltest/BigDecimalTest.java | 295 ++++--- .../bigintegertest/BigIntegerTest.java | 21 +- .../ConstraintEvaluationExceptionTest.java | 89 +- .../execmodel/drlx/DrlxCompilerTest.java | 8 +- .../execmodel/exchange/SendReceiveTest.java | 2 +- .../execmodel/fireandalarm/CompilerTest.java | 18 +- .../fireandalarm/FireAndAlarmTest.java | 2 +- .../FireAndAlarmUsingDroolsTest.java | 2 +- .../execmodel/generator/ConsequenceTest.java | 2 +- .../generator/ConstraintTestUtil.java | 2 +- .../generator/DrlxParseUtilTest.java | 2 +- .../generator/ExpressionTyperTest.java | 15 +- .../execmodel/generator/FlattenScopeTest.java | 2 +- .../GeneratedClassDeclarationTest.java | 2 +- .../execmodel/generator/StringUtilTest.java | 2 +- .../drlxparse/CoercedExpressionTest.java | 8 +- .../drlxparse/ConstraintParserTest.java | 6 +- .../execmodel/inlinecast/InlineCastTest.java | 97 ++- .../operators/BaseOperatorsTest.java | 19 +- .../execmodel/operators/DateOperatorTest.java | 23 +- .../operators/EqualityComparisonTest.java | 56 +- ...EqualityComparisonWith2PropertiesTest.java | 58 +- .../execmodel/util/LambdaUtilTest.java | 3 +- .../ExecModelLambdaPostProcessorTest.java | 7 +- .../MaterializedLambdaConsequenceTest.java | 2 +- .../MaterializedLambdaExtractorTest.java | 2 +- .../MaterializedLambdaPredicateTest.java | 2 +- .../execmodel/variables/VariablesTest.java | 37 +- drools-model/drools-model-compiler/pom.xml | 6 +- .../drools/modelcompiler/PatternDSLTest.java | 3 +- drools-model/drools-model-prototype/pom.xml | 6 +- .../PrototypeFieldExtractorTest.java | 2 +- drools-model/drools-mvel-compiler/pom.xml | 10 +- .../java/org/drools/mvel/ArithmeticTest.java | 122 +-- .../mvelcompiler/ConstraintCompilerTest.java | 2 +- .../drools/mvelcompiler/MvelCompilerTest.java | 2 +- .../mvelcompiler/PreprocessCompilerTest.java | 2 +- .../util/MethodResolutionUtilsTest.java | 2 +- drools-model/drools-mvel-parser/pom.xml | 6 +- .../drools/mvel/parser/DrlxParserTest.java | 3 +- .../mvel/parser/DroolsMvelParserTest.java | 15 +- 120 files changed, 4864 insertions(+), 4081 deletions(-) diff --git a/drools-model/drools-canonical-model/pom.xml b/drools-model/drools-canonical-model/pom.xml index 58d14809398..0b11dd11640 100644 --- a/drools-model/drools-canonical-model/pom.xml +++ b/drools-model/drools-canonical-model/pom.xml @@ -43,11 +43,10 @@ logback-classic test - - junit - junit - test + org.junit.jupiter + junit-jupiter + test org.assertj diff --git a/drools-model/drools-canonical-model/src/test/java/org/drools/model/operators/MatchesOperatorTest.java b/drools-model/drools-canonical-model/src/test/java/org/drools/model/operators/MatchesOperatorTest.java index 4520828c4ea..85904614f4d 100644 --- a/drools-model/drools-canonical-model/src/test/java/org/drools/model/operators/MatchesOperatorTest.java +++ b/drools-model/drools-canonical-model/src/test/java/org/drools/model/operators/MatchesOperatorTest.java @@ -18,11 +18,11 @@ */ package org.drools.model.operators; -import org.junit.After; -import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class MatchesOperatorTest { @@ -60,7 +60,7 @@ public void testMatchesOperatorNoCache() { assertThat(instance.mapSize()).isEqualTo(0); } - @After + @AfterEach public void resetCache() { MatchesOperator instance = MatchesOperator.INSTANCE; instance.reInitialize(); diff --git a/drools-model/drools-canonical-model/src/test/java/org/drools/model/util/OperatorUtilsTest.java b/drools-model/drools-canonical-model/src/test/java/org/drools/model/util/OperatorUtilsTest.java index 9a42b767312..0b2b2797720 100644 --- a/drools-model/drools-canonical-model/src/test/java/org/drools/model/util/OperatorUtilsTest.java +++ b/drools-model/drools-canonical-model/src/test/java/org/drools/model/util/OperatorUtilsTest.java @@ -20,7 +20,7 @@ import java.math.BigDecimal; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-model-codegen/pom.xml b/drools-model/drools-model-codegen/pom.xml index b8df4eda918..174224e2c04 100644 --- a/drools-model/drools-model-codegen/pom.xml +++ b/drools-model/drools-model-codegen/pom.xml @@ -127,36 +127,16 @@ test - - junit - junit - test - - + + org.junit.jupiter + junit-jupiter + test + + org.assertj assertj-core test - - org.junit.vintage - junit-vintage-engine - test - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.jupiter - junit-jupiter-params - test - org.drools drools-decisiontables diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/AccumulateTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/AccumulateTest.java index f46c7f77084..95d368192c9 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/AccumulateTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/AccumulateTest.java @@ -50,6 +50,8 @@ import org.drools.core.base.accumulators.IntegerMaxAccumulateFunction; import org.drools.core.rule.consequence.InternalMatch; import org.drools.model.functions.accumulate.GroupKey; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.drools.model.codegen.execmodel.domain.Adult; import org.drools.model.codegen.execmodel.domain.Child; import org.drools.model.codegen.execmodel.domain.Customer; @@ -59,7 +61,6 @@ import org.drools.model.codegen.execmodel.domain.StockTick; import org.drools.model.codegen.execmodel.domain.TargetPolicy; import org.drools.model.codegen.execmodel.oopathdtables.InternationalAddress; -import org.junit.Test; import org.kie.api.builder.Message; import org.kie.api.builder.Results; import org.kie.api.definition.type.FactType; @@ -68,16 +69,14 @@ import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.fail; public class AccumulateTest extends BaseModelTest { - public AccumulateTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testAccumulate1() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulate1(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -89,7 +88,7 @@ public void testAccumulate1() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -102,8 +101,9 @@ public void testAccumulate1() { assertThat(results.iterator().next().getValue()).isEqualTo(77); } - @Test - public void testFromOnAccumulatedValue() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromOnAccumulatedValue(RUN_TYPE runType) { // DROOLS-5635 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -117,7 +117,7 @@ public void testFromOnAccumulatedValue() { " insert(new Result($s));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert("test"); ksession.insert(new Person("Mark", 37)); @@ -131,8 +131,9 @@ public void testFromOnAccumulatedValue() { assertThat(results.iterator().next().getValue()).isEqualTo("77"); } - @Test - public void testFromOnAccumulatedValueUsingExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromOnAccumulatedValueUsingExists(RUN_TYPE runType) { // DROOLS-5635 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -146,7 +147,7 @@ public void testFromOnAccumulatedValueUsingExists() { " insert(new Result($s));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert("test"); ksession.insert(new Person("Mark", 37)); @@ -160,8 +161,9 @@ public void testFromOnAccumulatedValueUsingExists() { assertThat(results.iterator().next().getValue()).isEqualTo("77"); } - @Test - public void testAccumulateWithoutParameters() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithoutParameters(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -173,7 +175,7 @@ public void testAccumulateWithoutParameters() { " insert(new Result($count));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -186,8 +188,9 @@ public void testAccumulateWithoutParameters() { assertThat(results.iterator().next().getValue()).isEqualTo(2l); } - @Test - public void testAccumulateWithLessParameter() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithLessParameter(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -199,7 +202,7 @@ public void testAccumulateWithLessParameter() { " insert(new Result(\"fired\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -214,8 +217,9 @@ public void testAccumulateWithLessParameter() { assertThat(results.iterator().next().getValue()).isEqualTo("fired"); } - @Test - public void testAccumulateOverConstant() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateOverConstant(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -227,7 +231,7 @@ public void testAccumulateOverConstant() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -240,8 +244,9 @@ public void testAccumulateOverConstant() { assertThat(results.iterator().next().getValue()).isEqualTo(2); } - @Test - public void testAccumulateConstrainingValue() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateConstrainingValue(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -253,7 +258,7 @@ public void testAccumulateConstrainingValue() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -266,8 +271,9 @@ public void testAccumulateConstrainingValue() { assertThat(results.iterator().next().getValue()).isEqualTo(77); } - @Test - public void testAccumulateConstrainingValue2() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateConstrainingValue2(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -279,7 +285,7 @@ public void testAccumulateConstrainingValue2() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -291,8 +297,9 @@ public void testAccumulateConstrainingValue2() { assertThat(results.size()).isEqualTo(0); } - @Test - public void testAccumulateConstrainingValueInPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateConstrainingValueInPattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -304,7 +311,7 @@ public void testAccumulateConstrainingValueInPattern() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -317,8 +324,9 @@ public void testAccumulateConstrainingValueInPattern() { assertThat(results.iterator().next().getValue()).isEqualTo(77); } - @Test - public void testAccumulateWithProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithProperty(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -330,7 +338,7 @@ public void testAccumulateWithProperty() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -343,8 +351,9 @@ public void testAccumulateWithProperty() { assertThat(results.iterator().next().getValue()).isEqualTo(77); } - @Test - public void testAccumulate2() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulate2(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -358,7 +367,7 @@ public void testAccumulate2() { " insert(new Result($average));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -371,8 +380,9 @@ public void testAccumulate2() { assertThat(results).contains(new Result(77)); } - @Test - public void testAccumulateMultipleFunctions() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateMultipleFunctions(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -386,7 +396,7 @@ public void testAccumulateMultipleFunctions() { " insert(new Result($average));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -399,8 +409,9 @@ public void testAccumulateMultipleFunctions() { assertThat(results).contains(new Result(77)); } - @Test - public void testAccumulateMultipleFunctionsConstrainingValues() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateMultipleFunctionsConstrainingValues(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -415,7 +426,7 @@ public void testAccumulateMultipleFunctionsConstrainingValues() { " insert(new Result($min));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -428,8 +439,9 @@ public void testAccumulateMultipleFunctionsConstrainingValues() { assertThat(results).contains(new Result(77)); } - @Test - public void testAccumulateWithAnd() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithAnd(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -440,7 +452,7 @@ public void testAccumulateWithAnd() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -453,8 +465,9 @@ public void testAccumulateWithAnd() { assertThat(results).contains(new Result(43)); } - @Test - public void testAccumulateWithAnd2() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithAnd2(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -465,7 +478,7 @@ public void testAccumulateWithAnd2() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -479,8 +492,9 @@ public void testAccumulateWithAnd2() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(49); } - @Test - public void testAccumulateWithAnd3() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithAnd3(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -491,7 +505,7 @@ public void testAccumulateWithAnd3() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -505,8 +519,9 @@ public void testAccumulateWithAnd3() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(49); } - @Test - public void testAccumulateWithAnd3Binds() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithAnd3Binds(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -518,7 +533,7 @@ public void testAccumulateWithAnd3Binds() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -533,8 +548,9 @@ public void testAccumulateWithAnd3Binds() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(54); } - @Test - public void testAccumulateWithAnd4Binds() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithAnd4Binds(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -546,7 +562,7 @@ public void testAccumulateWithAnd4Binds() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -562,8 +578,9 @@ public void testAccumulateWithAnd4Binds() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(59); } - @Test - public void testAccumulateWithCustomImport() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithCustomImport(RUN_TYPE runType) { String str = "import accumulate " + TestFunction.class.getCanonicalName() + " f;\n" + "import " + Adult.class.getCanonicalName() + ";\n" + @@ -575,7 +592,7 @@ public void testAccumulateWithCustomImport() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -630,8 +647,9 @@ public Class getResultType() { } } - @Test - public void testFromAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -643,7 +661,7 @@ public void testFromAccumulate() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -656,8 +674,9 @@ public void testFromAccumulate() { assertThat(results.iterator().next().getValue()).isEqualTo(77); } - @Test - public void testFromCollect() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollect(RUN_TYPE runType) { String str = "import " + Customer.class.getCanonicalName() + ";\n" + "import " + TargetPolicy.class.getCanonicalName() + ";\n" + @@ -671,11 +690,12 @@ public void testFromCollect() { " update($target);\n" + "end"; - checkCollect( str ); + checkCollect(runType, str); } - @Test - public void testFromCollectWithAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithAccumulate(RUN_TYPE runType) { String str = "import " + Customer.class.getCanonicalName() + ";\n" + "import " + TargetPolicy.class.getCanonicalName() + ";\n" + @@ -689,11 +709,12 @@ public void testFromCollectWithAccumulate() { " update($target);\n" + "end"; - checkCollect( str ); + checkCollect(runType, str); } - @Test - public void testFromCollectWithExpandedAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithExpandedAccumulate(RUN_TYPE runType) { String str = "import " + Customer.class.getCanonicalName() + ";\n" + "import " + TargetPolicy.class.getCanonicalName() + ";\n" + @@ -712,11 +733,11 @@ public void testFromCollectWithExpandedAccumulate() { " update($target);\n" + "end"; - checkCollect( str ); + checkCollect(runType, str); } - private void checkCollect( String str ) { - KieSession ksession = getKieSession(str); + private void checkCollect(RUN_TYPE runType, String str ) { + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -744,17 +765,19 @@ private void checkCollect( String str ) { assertThat(filtered).isEqualTo(1); } - @Test - public void testFromCollectWithExpandedAccumulate2() { - testFromCollectWithExpandedAccumulate2(false); + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithExpandedAccumulate2(RUN_TYPE runType) { + testFromCollectWithExpandedAccumulate2(runType, false); } - @Test - public void testFromCollectWithExpandedAccumulate2WithReverse() { - testFromCollectWithExpandedAccumulate2(true); + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithExpandedAccumulate2WithReverse(RUN_TYPE runType) { + testFromCollectWithExpandedAccumulate2(runType, true); } - public void testFromCollectWithExpandedAccumulate2(boolean performReverse) { + public void testFromCollectWithExpandedAccumulate2(RUN_TYPE runType, boolean performReverse) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " $sum : Integer() from accumulate (\n" + @@ -764,7 +787,7 @@ public void testFromCollectWithExpandedAccumulate2(boolean performReverse) { " insert($sum);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); FactHandle fh_Edson = ksession.insert(new Person("Edson", 35)); @@ -785,8 +808,9 @@ public void testFromCollectWithExpandedAccumulate2(boolean performReverse) { } } - @Test - public void testExpandedAccumulateWith2Args() { + @ParameterizedTest + @MethodSource("parameters") + public void testExpandedAccumulateWith2Args(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " $avg : Integer() from accumulate (\n" + @@ -799,7 +823,7 @@ public void testExpandedAccumulateWith2Args() { " insert($avg);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); FactHandle fh_Edson = ksession.insert(new Person("Edson", 35)); @@ -818,8 +842,9 @@ public void testExpandedAccumulateWith2Args() { assertThat(results).contains(36); } - @Test - public void testExpandedAccumulateWith2Args2Bindings() { + @ParameterizedTest + @MethodSource("parameters") + public void testExpandedAccumulateWith2Args2Bindings(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " $avg : Integer() from accumulate (\n" + @@ -833,7 +858,7 @@ public void testExpandedAccumulateWith2Args2Bindings() { " insert($avg);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); FactHandle fh_Edson = ksession.insert(new Person("Edson", 35)); @@ -853,8 +878,9 @@ public void testExpandedAccumulateWith2Args2Bindings() { } - @Test - public void testExpandedAccumulateWith3Args() { + @ParameterizedTest + @MethodSource("parameters") + public void testExpandedAccumulateWith3Args(RUN_TYPE runType) { String str = "rule \"TestAccumulate2\" when\n" + " $dx : Number () from accumulate ( $d : Double (),\n" + @@ -866,7 +892,7 @@ public void testExpandedAccumulateWith3Args() { " insert($dx.intValue());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(1.0); ksession.insert(2.0); @@ -878,8 +904,9 @@ public void testExpandedAccumulateWith3Args() { assertThat(results).contains(8); } - @Test - public void testAccumulateFromWithConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateFromWithConstraint(RUN_TYPE runType) { String str = "import " + java.util.List.class.getCanonicalName() + ";" + "import " + org.drools.model.codegen.execmodel.oopathdtables.Person.class.getCanonicalName() + ";" + @@ -892,7 +919,7 @@ public void testAccumulateFromWithConstraint() { " insert($cities.get(0));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new InternationalAddress("", 1, "Milan", "Safecountry")); ksession.fireAllRules(); @@ -902,8 +929,9 @@ public void testAccumulateFromWithConstraint() { assertThat(results).contains("Milan"); } - @Test - public void testAccumulateWithThis() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithThis(RUN_TYPE runType) { final String drl1 = "import java.util.*;\n" + "rule B\n" + @@ -916,7 +944,7 @@ public void testAccumulateWithThis() { "then\n" + " insert($eventCodeDistinctMois);\n" + "end"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert("1"); ksession.insert("3"); @@ -930,8 +958,9 @@ public void testAccumulateWithThis() { assertThat(results).contains(4); } - @Test - public void testAccumulateWithExternalBind() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithExternalBind(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -944,7 +973,7 @@ public void testAccumulateWithExternalBind() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); ksession.insert(new Person("Mark", 37)); @@ -958,8 +987,9 @@ public void testAccumulateWithExternalBind() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(77); } - @Test - public void testFromCollectWithExpandedAccumulateExternalBindInInit() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithExpandedAccumulateExternalBindInInit(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " String( $l : length )\n" + @@ -970,7 +1000,7 @@ public void testFromCollectWithExpandedAccumulateExternalBindInInit() { " insert($sum);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); @@ -984,8 +1014,9 @@ public void testFromCollectWithExpandedAccumulateExternalBindInInit() { } - @Test - public void testFromCollectWithExpandedAccumulateExternalBindInAction() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithExpandedAccumulateExternalBindInAction(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " String( $l : length )" + @@ -996,7 +1027,7 @@ public void testFromCollectWithExpandedAccumulateExternalBindInAction() { " insert($sum);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); @@ -1010,8 +1041,9 @@ public void testFromCollectWithExpandedAccumulateExternalBindInAction() { } - @Test - public void testUseAccumulateFunctionWithOperationInBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccumulateFunctionWithOperationInBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -1022,7 +1054,7 @@ public void testUseAccumulateFunctionWithOperationInBinding() { " insert($result);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); @@ -1036,8 +1068,9 @@ public void testUseAccumulateFunctionWithOperationInBinding() { } - @Test - public void testUseAccumulateFunctionWithArrayAccessOperation() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccumulateFunctionWithArrayAccessOperation(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -1048,7 +1081,7 @@ public void testUseAccumulateFunctionWithArrayAccessOperation() { " insert($result);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); Adult luca = new Adult("Luca", 33); @@ -1065,8 +1098,9 @@ public void testUseAccumulateFunctionWithArrayAccessOperation() { assertThat(results.get(0).intValue()).isEqualTo(11); } - @Test - public void testUseAccumulateFunctionWithListMvelDialectWithoutBias() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccumulateFunctionWithListMvelDialectWithoutBias(RUN_TYPE runType) throws Exception { String str = "package org.test;" + "import java.util.*; " + "declare Data " + @@ -1081,7 +1115,7 @@ public void testUseAccumulateFunctionWithListMvelDialectWithoutBias() throws Exc " insert($tot);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactType dataType = ksession.getKieBase().getFactType("org.test", "Data"); Object data1 = dataType.newInstance(); @@ -1095,8 +1129,9 @@ public void testUseAccumulateFunctionWithListMvelDialectWithoutBias() throws Exc assertThat(results.get(0).intValue()).isEqualTo(2); } - @Test - public void testUseAccumulateFunctionWithListMvelDialect() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccumulateFunctionWithListMvelDialect(RUN_TYPE runType) throws Exception { String str = "package org.test;" + "import java.util.*; " + "declare Data " + @@ -1112,7 +1147,7 @@ public void testUseAccumulateFunctionWithListMvelDialect() throws Exception { " insert($tot);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactType dataType = ksession.getKieBase().getFactType("org.test", "Data"); Object data1 = dataType.newInstance(); @@ -1132,8 +1167,9 @@ public void testUseAccumulateFunctionWithListMvelDialect() throws Exception { assertThat(results.get(0).intValue()).isEqualTo(212); } - @Test - public void testTypedResultOnAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testTypedResultOnAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1145,7 +1181,7 @@ public void testTypedResultOnAccumulate() { " insert(new Person(\"test\", $max));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert("xyz"); @@ -1156,8 +1192,9 @@ public void testTypedResultOnAccumulate() { assertThat(results.iterator().next().getAge()).isEqualTo(3); } - @Test - public void testExtractorInPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testExtractorInPattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1169,7 +1206,7 @@ public void testExtractorInPattern() { " insert(new Result($max));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("a", 23)); @@ -1181,8 +1218,9 @@ public void testExtractorInPattern() { } - @Test - public void testThisInPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testThisInPattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1194,7 +1232,7 @@ public void testThisInPattern() { " insert(new Result($max));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(2); ksession.insert(10); @@ -1208,8 +1246,9 @@ public void testThisInPattern() { - @Test - public void testExtractorInFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testExtractorInFunction(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1221,7 +1260,7 @@ public void testExtractorInFunction() { " insert(new Result($max));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("a", 23)); @@ -1232,8 +1271,9 @@ public void testExtractorInFunction() { assertThat(results.iterator().next().getValue()).isEqualTo(23); } - @Test - public void testBigDecimalOperationsInAccumulateConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalOperationsInAccumulateConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List results;\n" + @@ -1246,7 +1286,7 @@ public void testBigDecimalOperationsInAccumulateConstraint() { " results.add($moneySummed);\n" + "end\n"; - KieSession ksession1 = getKieSession(str); + KieSession ksession1 = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession1.setGlobal("results", results); @@ -1266,8 +1306,9 @@ public void testBigDecimalOperationsInAccumulateConstraint() { // do also the test with two functions - @Test - public void testAccumulateWithMax() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithMax(RUN_TYPE runType) { String str = "import " + StockTick.class.getCanonicalName() + ";" + "import " + StockTick.class.getCanonicalName() + ";" + @@ -1279,7 +1320,7 @@ public void testAccumulateWithMax() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StockTick st = new StockTick("RHT"); st.setTimeField(new Date().getTime()); @@ -1287,8 +1328,9 @@ public void testAccumulateWithMax() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAccumulateWithMaxCalendar() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithMaxCalendar(RUN_TYPE runType) { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "rule AccumulateMaxDate\n" + @@ -1300,7 +1342,7 @@ public void testAccumulateWithMaxCalendar() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StockTick st = new StockTick("RHT"); st.setDueDate(Calendar.getInstance()); @@ -1308,8 +1350,9 @@ public void testAccumulateWithMaxCalendar() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAccumulateWithMaxCalendarAndConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithMaxCalendarAndConstraint(RUN_TYPE runType) { String str = "import " + Customer.class.getCanonicalName() + ";\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -1324,7 +1367,7 @@ public void testAccumulateWithMaxCalendarAndConstraint() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StockTick st = new StockTick("RHT"); st.setDueDate(Calendar.getInstance()); @@ -1335,8 +1378,9 @@ public void testAccumulateWithMaxCalendarAndConstraint() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNoBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoBinding(RUN_TYPE runType) { final String str = "rule foo\n" + "when\n" + @@ -1347,7 +1391,7 @@ public void testNoBinding() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("xyz"); ksession.fireAllRules(); } @@ -1358,8 +1402,9 @@ public Short getValue() { } } - @Test - public void testImplicitCastInAccumulateFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testImplicitCastInAccumulateFunction(RUN_TYPE runType) { String str = "import " + ShortValue.class.getCanonicalName() + ";" + "rule X when\n" + @@ -1367,15 +1412,16 @@ public void testImplicitCastInAccumulateFunction() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new ShortValue()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAccumulateWithFunctionWithExternalBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithFunctionWithExternalBinding(RUN_TYPE runType) { final String drl = "import " + Converter.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1387,7 +1433,7 @@ public void testAccumulateWithFunctionWithExternalBinding() { " list.add($result);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1408,8 +1454,9 @@ public static int convert(final int i) { } } - @Test - public void testAccumulateWithFunctionWithExternalBindingAndOR() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithFunctionWithExternalBindingAndOR(RUN_TYPE runType) { final String drl = "import " + Converter.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1424,7 +1471,7 @@ public void testAccumulateWithFunctionWithExternalBindingAndOR() { " list.add($result);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1438,8 +1485,9 @@ public void testAccumulateWithFunctionWithExternalBindingAndOR() { assertThat(list.get(0).intValue()).isEqualTo(5); } - @Test - public void testAccumulateWithOR() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithOR(RUN_TYPE runType) { final String drl = "import " + Converter.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1453,7 +1501,7 @@ public void testAccumulateWithOR() { " list.add($result);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1466,8 +1514,9 @@ public void testAccumulateWithOR() { assertThat(list.get(0).intValue()).isEqualTo(5); } - @Test - public void testPatternMatchingOverNumberWhileAccumulatingShort() { + @ParameterizedTest + @MethodSource("parameters") + public void testPatternMatchingOverNumberWhileAccumulatingShort(RUN_TYPE runType) { String drl= "import " + AccumulateResult.class.getCanonicalName() + "\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1486,7 +1535,7 @@ public void testPatternMatchingOverNumberWhileAccumulatingShort() { " update($accumulateResult);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); AccumulateResult result = new AccumulateResult(false); @@ -1538,8 +1587,9 @@ public void setBigDecimalValue(BigDecimal bigDecimalValue) { } - @Test - public void testAccumulateOverField() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateOverField(RUN_TYPE runType) { String str = "import java.lang.Number;\n" + "import java.math.BigDecimal;\n" + @@ -1558,7 +1608,7 @@ public void testAccumulateOverField() { " }\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", BigDecimal.valueOf(1000))); ksession.insert(new Person("Luca", BigDecimal.valueOf(2000))); @@ -1572,8 +1622,9 @@ public void testAccumulateOverField() { assertThat(result.getBigDecimalValue()).isEqualTo(BigDecimal.valueOf(3000)); } - @Test - public void testFromAccumulateBigDecimalMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromAccumulateBigDecimalMvel(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1590,7 +1641,7 @@ public void testFromAccumulateBigDecimalMvel() { " list.add($b);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1607,8 +1658,9 @@ public void testFromAccumulateBigDecimalMvel() { } - @Test - public void testSemicolonMissingInInit() { + @ParameterizedTest + @MethodSource("parameters") + public void testSemicolonMissingInInit(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1624,7 +1676,7 @@ public void testSemicolonMissingInInit() { " list.add($sum);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1643,8 +1695,9 @@ public void testSemicolonMissingInInit() { } - @Test(expected = AssertionError.class) - public void testSemicolonMissingInAction() { + @ParameterizedTest + @MethodSource("parameters") + public void testSemicolonMissingInAction(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1660,11 +1713,13 @@ public void testSemicolonMissingInAction() { " list.add($sum);\n" + "end"; - getKieSession(str); + + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> getKieSession(runType, str)); } - @Test(expected = AssertionError.class) - public void testSemicolonMissingInReverse() { + @ParameterizedTest + @MethodSource("parameters") + public void testSemicolonMissingInReverse(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1680,11 +1735,12 @@ public void testSemicolonMissingInReverse() { " list.add($sum);\n" + "end"; - getKieSession(str); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> getKieSession(runType, str)); } - @Test - public void testGroupBy() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy(RUN_TYPE runType) { // DROOLS-4737 String str = "import java.util.*;\n" + @@ -1704,7 +1760,7 @@ public void testGroupBy() { " System.out.println(\"Sum of ages of person with initial '\" + $initial + \"' is \" + $sumOfAges);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 42)); ksession.insert(new Person("Edson", 38)); @@ -1765,8 +1821,9 @@ public V getValue() { } } - @Test - public void testGroupBy2() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy2(RUN_TYPE runType) { // DROOLS-4737 String str = "import java.util.*;\n" + @@ -1787,7 +1844,7 @@ public void testGroupBy2() { " results.put($initial, $sumOfAges);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -1822,8 +1879,9 @@ public void testGroupBy2() { assertThat(results.get("M")).isEqualTo(119); } - @Test - public void testGroupBy3() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy3(RUN_TYPE runType) { // DROOLS-4737 String str = "import java.util.*;\n" + @@ -1854,7 +1912,7 @@ public void testGroupBy3() { " results.put($initial, $sumOfAges);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -1889,8 +1947,9 @@ public void testGroupBy3() { assertThat(results.get("M")).isEqualTo(119); } - @Test - public void testGroupBy3WithExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy3WithExists(RUN_TYPE runType) { String str = "import java.util.*;\n" + "import " + GroupKey.class.getCanonicalName() + ";\n" + @@ -1921,7 +1980,7 @@ public void testGroupBy3WithExists() { " results.put($initial, $sumOfAges);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -1961,8 +2020,9 @@ public void testGroupBy3WithExists() { assertThat(results.get("M")).isEqualTo(119); } - @Test - public void testGroupBy3WithExists2() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy3WithExists2(RUN_TYPE runType) { String str = "import java.util.*;\n" + "import " + GroupKey.class.getCanonicalName() + ";\n" + @@ -1994,7 +2054,7 @@ public void testGroupBy3WithExists2() { " results.add(java.util.Arrays.asList($k, $count));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList(); ksession.setGlobal( "results", results ); @@ -2022,8 +2082,9 @@ public void testGroupBy3WithExists2() { .containsOnly(Arrays.asList(child2, 1L)); } - @Test - public void testGroupBy3With2VarsKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy3With2VarsKey(RUN_TYPE runType) { String str = "import java.util.*;\n" + "import " + GroupKey.class.getCanonicalName() + ";\n" + @@ -2057,7 +2118,7 @@ public void testGroupBy3With2VarsKey() { " results.put($k, $sumOfAges);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -2100,8 +2161,9 @@ public void testGroupBy3With2VarsKey() { assertThat(results.get("M5")).isEqualTo(119); } - @Test - public void testFromAfterAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromAfterAccumulate(RUN_TYPE runType) { // DROOLS-4737 String str = "import " + List.class.getCanonicalName() + ";\n" + @@ -2113,7 +2175,7 @@ public void testFromAfterAccumulate() { " System.out.println($name + \"' is \" + $age);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 42)); ksession.insert(new Person("Edson", 38)); @@ -2121,8 +2183,9 @@ public void testFromAfterAccumulate() { ksession.fireAllRules(); } - @Test - public void testCoercionInAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testCoercionInAccumulate(RUN_TYPE runType) { String str = "global java.util.List result;\n" + "rule \"Row 1 moveToBiggerCities\"\n" + @@ -2136,7 +2199,7 @@ public void testCoercionInAccumulate() { List result = new ArrayList<>(); - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("result", result); IntStream.range(1, 7).forEach(ksession::insert); @@ -2147,8 +2210,9 @@ public void testCoercionInAccumulate() { } - @Test - public void testCoercionInAccumulate2() { + @ParameterizedTest +@MethodSource("parameters") + public void testCoercionInAccumulate2(RUN_TYPE runType) { final String drl = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List result; \n" + @@ -2165,7 +2229,7 @@ public void testCoercionInAccumulate2() { List result = new ArrayList<>(); - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); ksession.setGlobal("result", result); ksession.insert(new Person("Luca", 35)); @@ -2210,8 +2274,9 @@ public long between(LocalDateTime start, LocalDateTime end) { } } - @Test - public void testAccumulateOnStaticMethod() { + @ParameterizedTest +@MethodSource("parameters") + public void testAccumulateOnStaticMethod(RUN_TYPE runType) { // DROOLS-4979 final String drl = "import java.time.Duration\n" + @@ -2230,7 +2295,7 @@ public void testAccumulateOnStaticMethod() { List result = new ArrayList<>(); - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); ksession.setGlobal("result", result); ksession.insert(new Interval( @@ -2244,8 +2309,9 @@ public void testAccumulateOnStaticMethod() { } - @Test - public void testAccumulateOfDurationBetweenDateTime() { + @ParameterizedTest +@MethodSource("parameters") + public void testAccumulateOfDurationBetweenDateTime(RUN_TYPE runType) { // DROOLS-4979 final String drl = "import java.time.Duration\n" + @@ -2264,7 +2330,7 @@ public void testAccumulateOfDurationBetweenDateTime() { List result = new ArrayList<>(); - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); ksession.setGlobal("result", result); ksession.insert(new Interval( @@ -2278,8 +2344,9 @@ public void testAccumulateOfDurationBetweenDateTime() { } - @Test - public void testGroupByRegrouped() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupByRegrouped(RUN_TYPE runType) { // DROOLS-5283 String str = "import java.util.*;\n" + @@ -2305,7 +2372,7 @@ public void testGroupByRegrouped() { "then\n" + " System.out.println($p.toString());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 42)); ksession.insert(new Person("Edson", 38)); @@ -2327,8 +2394,9 @@ public void testGroupByRegrouped() { ksession.fireAllRules(); } - @Test - public void testAccumulateStaticMethodWithPatternBindVar() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateStaticMethodWithPatternBindVar(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + MyUtil.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -2339,7 +2407,7 @@ public void testAccumulateStaticMethodWithPatternBindVar() { " insert($result);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); ksession.insert(new Person("Mark", 37)); @@ -2358,8 +2426,9 @@ public static int add(int a, int b) { } } - @Test - public void testModifyAccumulatedFactWithNonIndexableConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyAccumulatedFactWithNonIndexableConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -2370,7 +2439,7 @@ public void testModifyAccumulatedFactWithNonIndexableConstraint() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "a" ); ksession.insert( "b" ); @@ -2411,8 +2480,9 @@ public void testModifyAccumulatedFactWithNonIndexableConstraint() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testAccumulateWithManyBindings() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithManyBindings(RUN_TYPE runType) { // DROOLS-5546 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -2424,7 +2494,7 @@ public void testAccumulateWithManyBindings() { " insert($max);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 40 ) ); @@ -2437,8 +2507,9 @@ public void testAccumulateWithManyBindings() { assertThat(results.get(0).intValue()).isEqualTo(5); } - @Test - public void testFalseNodeSharing() { + @ParameterizedTest + @MethodSource("parameters") + public void testFalseNodeSharing(RUN_TYPE runType) { // DROOLS-5686 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -2457,7 +2528,7 @@ public void testFalseNodeSharing() { " insert(\"\" + $sum);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 46 ) ); ksession.insert( new Person( "Mark", 44 ) ); @@ -2474,8 +2545,9 @@ public void testFalseNodeSharing() { assertThat(resultsString.get(0)).isEqualTo("13"); } - @Test - public void testAccumulateWithTwoFunctions1() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithTwoFunctions1(RUN_TYPE runType) { // DROOLS-5752 String str = "import java.time.Duration;\n" + "import " + Shift.class.getCanonicalName() + ";\n" + @@ -2492,15 +2564,16 @@ public void testAccumulateWithTwoFunctions1() { " System.out.println($shiftCount + \" \" + $totalMinutes);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Shift( OffsetDateTime.now()) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAccumulateWithTwoFunctions2() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithTwoFunctions2(RUN_TYPE runType) { // DROOLS-5752 String str = "import java.time.Duration;\n" + "import " + Shift.class.getCanonicalName() + ";\n" + @@ -2517,7 +2590,7 @@ public void testAccumulateWithTwoFunctions2() { " System.out.println($shiftCount + \" \" + $totalMinutes);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Shift( OffsetDateTime.now()) ); @@ -2577,8 +2650,9 @@ public static Duration between(OffsetDateTime start, OffsetDateTime end) { return Duration.between(start, end); } - @Test - public void testAccumulateNumberFromSum() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateNumberFromSum(RUN_TYPE runType) { String str = "import " + Shift.class.getCanonicalName() + ";" + "import " + AccumulateTest.class.getCanonicalName() + ";" @@ -2600,7 +2674,7 @@ public void testAccumulateNumberFromSum() { - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Shift shift = new Shift(OffsetDateTime.now()); @@ -2625,8 +2699,9 @@ private static int switchMachinesInAssignments(KieSession session, MrProcessAssi return session.fireAllRules(); } - @Test - public void testDoubleAccumulateNPE() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoubleAccumulateNPE(RUN_TYPE runType) { // Prepare reproducing data. MrMachine machine2 = new MrMachine(); MrMachine machine3 = new MrMachine(); @@ -2651,7 +2726,7 @@ public void testDoubleAccumulateNPE() { "then\n" + " result.add($count);\n" + "end;"; - KieSession kieSession = getKieSession(rule); + KieSession kieSession = getKieSession(runType, rule); List result = new ArrayList<>(); kieSession.setGlobal("result", result); @@ -2731,8 +2806,9 @@ public static class MrMachine { } - @Test - public void testInlineAccumulateWithAnd() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineAccumulateWithAnd(RUN_TYPE runType) { // RHDM-1549 String str = "import " + Car.class.getCanonicalName() + ";" + @@ -2749,7 +2825,7 @@ public void testInlineAccumulateWithAnd() { " result.add($total);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -2780,8 +2856,9 @@ public void testInlineAccumulateWithAnd() { ksession.dispose(); } - @Test - public void testInlineMvelAccumulateWithAnd() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineMvelAccumulateWithAnd(RUN_TYPE runType) { // RHDM-1549 String str = "import " + Car.class.getCanonicalName() + ";" + @@ -2799,7 +2876,7 @@ public void testInlineMvelAccumulateWithAnd() { " result.add($total);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -2912,8 +2989,9 @@ public void setPrice(BigDecimal price) { } } - @Test - public void testAccumulateOnPartiallyReversibleFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateOnPartiallyReversibleFunction(RUN_TYPE runType) { // DROOLS-5930 String str = "import accumulate " + CountingIntegerMaxAccumulateFunction.class.getCanonicalName() + " countingMax;\n" + @@ -2925,7 +3003,7 @@ public void testAccumulateOnPartiallyReversibleFunction() { " result.add($max);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); CountingIntegerMaxAccumulateFunction accFunction = CountingIntegerMaxAccumulateFunction.INSTANCE; @@ -2990,8 +3068,9 @@ public void resetAccumulateCount() { } } - @Test - public void testOneAccumulateOnPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testOneAccumulateOnPattern(RUN_TYPE runType) { // DROOLS-5938 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -3004,7 +3083,7 @@ public void testOneAccumulateOnPattern() { " result.add($acc1.iterator().next());" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -3019,8 +3098,9 @@ public void testOneAccumulateOnPattern() { assertThat(result.get(0)).isEqualTo(lukas); } - @Test - public void testOneAccumulateOnPatternWithVarBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testOneAccumulateOnPatternWithVarBinding(RUN_TYPE runType) { // DROOLS-5938 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -3033,7 +3113,7 @@ public void testOneAccumulateOnPatternWithVarBinding() { " result.add($acc1.iterator().next());" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -3047,8 +3127,9 @@ public void testOneAccumulateOnPatternWithVarBinding() { assertThat(result.get(0)).isEqualTo(lukas); } - @Test - public void testTwoAccumulatesOnPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoAccumulatesOnPattern(RUN_TYPE runType) { // DROOLS-5938 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -3064,7 +3145,7 @@ public void testTwoAccumulatesOnPattern() { " result.add($acc2.iterator().next());" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -3076,8 +3157,9 @@ public void testTwoAccumulatesOnPattern() { assertThat(result.get(0)).isEqualTo(Pair.create("Lukas", 35)); } - @Test - public void testTwoAccumulatesOnPatternWithVarBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoAccumulatesOnPatternWithVarBinding(RUN_TYPE runType) { // DROOLS-5938 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -3093,7 +3175,7 @@ public void testTwoAccumulatesOnPatternWithVarBinding() { " result.add($acc2.iterator().next());" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -3105,8 +3187,9 @@ public void testTwoAccumulatesOnPatternWithVarBinding() { assertThat(result.get(0)).isEqualTo(Pair.create("Lukas", 35)); } - @Test - public void testBindingOrderWithInlineAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOrderWithInlineAccumulate(RUN_TYPE runType) { // RHDM-1551 String str = "import " + Aclass.class.getCanonicalName() + ";\n" + @@ -3134,7 +3217,7 @@ public void testBindingOrderWithInlineAccumulate() { " result.add($eSet.iterator().next());" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); List result = new ArrayList<>(); kSession.setGlobal("result", result); @@ -3151,8 +3234,9 @@ public void testBindingOrderWithInlineAccumulate() { kSession.dispose(); } - @Test - public void testBindingOrderWithInlineAccumulateAndLists() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOrderWithInlineAccumulateAndLists(RUN_TYPE runType) { // RHDM-1551 String str = "import " + Aclass.class.getCanonicalName() + ";\n" + @@ -3180,7 +3264,7 @@ public void testBindingOrderWithInlineAccumulateAndLists() { " result.add($eSet.iterator().next());" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); List result = new ArrayList<>(); kSession.setGlobal("result", result); @@ -3197,8 +3281,9 @@ public void testBindingOrderWithInlineAccumulateAndLists() { kSession.dispose(); } - @Test - public void testBindingOrderWithInlineAccumulateAndListsAndFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOrderWithInlineAccumulateAndListsAndFrom(RUN_TYPE runType) { // RHDM-1551 String str = "import " + Aclass.class.getCanonicalName() + ";\n" + @@ -3227,7 +3312,7 @@ public void testBindingOrderWithInlineAccumulateAndListsAndFrom() { " result.add($eSet.iterator().next());" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); List result = new ArrayList<>(); kSession.setGlobal("result", result); @@ -3324,8 +3409,9 @@ public void setName(String name) { } } - @Test - public void testMultiAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiAccumulate(RUN_TYPE runType) { // RHDM-1572 String str = "global java.util.List result;\n" + @@ -3340,7 +3426,7 @@ public void testMultiAccumulate() { " result.addAll($list);\n" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); List result = new ArrayList<>(); kSession.setGlobal( "result", result ); @@ -3360,8 +3446,9 @@ public void testMultiAccumulate() { kSession.dispose(); } - @Test - public void testAccumulateWithExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithExists(RUN_TYPE runType) { // RHDM-1571 String str = "import " + Car.class.getCanonicalName() + ";" + @@ -3375,7 +3462,7 @@ public void testAccumulateWithExists() { " result.addAll($list);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal( "result", result ); @@ -3392,8 +3479,9 @@ public void testAccumulateWithExists() { ksession.dispose(); } - @Test - public void testAccumulateWithForAll() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithForAll(RUN_TYPE runType) { // DROOLS-6025 String str = "import " + GrandChild.class.getCanonicalName() + ";\n" + @@ -3408,7 +3496,7 @@ public void testAccumulateWithForAll() { " System.out.println(\"exec \" + $count);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); GrandParent grandParent = new GrandParent(); GrandChild grandChild = new GrandChild(); @@ -3444,8 +3532,9 @@ public void setGrandChild(List grandChild) { } } - @Test - public void testAccumulateSubnetworkEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateSubnetworkEval(RUN_TYPE runType) { // DROOLS-6228 String str = "import java.time.Duration;\n" + @@ -3462,7 +3551,7 @@ public void testAccumulateSubnetworkEval() { " holder.set((int)holder.get() + $sum);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); AtomicReference holder = new AtomicReference<>(0); ksession.setGlobal("holder", holder); @@ -3475,8 +3564,9 @@ public void testAccumulateSubnetworkEval() { assertThat((int) holder.get()).isEqualTo(0); } - @Test - public void testInnerClassInAccumulatingFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerClassInAccumulatingFunction(RUN_TYPE runType) { // DROOLS-6238 String str = "import java.util.*;\n" + @@ -3501,7 +3591,7 @@ public void testInnerClassInAccumulatingFunction() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 42)); ksession.insert(new Person("Edson", 38)); @@ -3553,8 +3643,9 @@ public List result() { } } - @Test - public void testAccumulateWithSameBindingVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithSameBindingVariable(RUN_TYPE runType) { // DROOLS-6102 String str = "import java.util.*;\n" + @@ -3568,7 +3659,7 @@ public void testAccumulateWithSameBindingVariable() { " list.add( $tot2.intValue() ); \n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -3583,8 +3674,9 @@ public void testAccumulateWithSameBindingVariable() { assertThat((int) list.get(1)).isEqualTo(2); } - @Test - public void testAccumulateWithMaxCalendarNullDate() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithMaxCalendarNullDate(RUN_TYPE runType) { //DROOLS-4990 String str = "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -3597,7 +3689,7 @@ public void testAccumulateWithMaxCalendarNullDate() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StockTick st = new StockTick("RHT"); ksession.insert(st); @@ -3607,8 +3699,9 @@ public void testAccumulateWithMaxCalendarNullDate() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testSubnetworkTuple() { + @ParameterizedTest + @MethodSource("parameters") + public void testSubnetworkTuple(RUN_TYPE runType) { final String drl = "import java.math.*; " + "import " + InputDataTypes.class.getCanonicalName() + "; " + @@ -3624,7 +3717,7 @@ public void testSubnetworkTuple() { " result.add($min); " + "end"; - final KieSession ksession = getKieSession(drl); + final KieSession ksession = getKieSession(runType, drl); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -3685,8 +3778,9 @@ private GregorianCalendar calendarFromString(String inputString) { return GregorianCalendar.from( ZonedDateTime.from( DateTimeFormatter.ISO_DATE_TIME.parse(inputString))); } - @Test - public void testAccumulateCountWithExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateCountWithExists(RUN_TYPE runType) { // The following rule uses an accumulate to count all the name Strings for which at least one Person // of that name exists. Expected behavior: // - A name should be counted exactly once no matter how many Persons with that name exists. @@ -3704,7 +3798,7 @@ public void testAccumulateCountWithExists() { + " insert( new Result($count));\n" + " System.out.println(kcontext.getMatch().getObjects());\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ReteDumper.dumpRete(ksession); @@ -3725,8 +3819,9 @@ public void testAccumulateCountWithExists() { assertThat(results.iterator().next().getValue()).isEqualTo(2L); } - @Test - public void testAccumulateWithIndirectArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithIndirectArgument(RUN_TYPE runType) { String str = "global java.util.List resultTotal; \n" + "global java.util.List resultPair; \n" + @@ -3745,7 +3840,7 @@ public void testAccumulateWithIndirectArgument() { " resultPair.add($pair);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List resultTotal = new ArrayList<>(); ksession.setGlobal("resultTotal", resultTotal); @@ -3766,8 +3861,9 @@ public void testAccumulateWithIndirectArgument() { assertThat(firstPair.getSecond()).isEqualTo("Mario"); } - @Test - public void testVariableWithMethodCallInAccFunc() { + @ParameterizedTest + @MethodSource("parameters") + public void testVariableWithMethodCallInAccFunc(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "import " + ControlFact.class.getCanonicalName() + ";" + "import " + Payment.class.getCanonicalName() + ";" + @@ -3785,7 +3881,7 @@ public void testVariableWithMethodCallInAccFunc() { System.out.println(str); - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final Payment payment = new Payment(); payment.setDueDate(Calendar.getInstance()); @@ -3799,8 +3895,9 @@ public void testVariableWithMethodCallInAccFunc() { assertThat(rules).isEqualTo(1); } - @Test - public void testVariableWithMethodCallInAccFuncSimple() { + @ParameterizedTest + @MethodSource("parameters") + public void testVariableWithMethodCallInAccFuncSimple(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "import " + FactA.class.getCanonicalName() + ";" + "rule r1\n" + @@ -3814,7 +3911,7 @@ public void testVariableWithMethodCallInAccFuncSimple() { System.out.println(str); - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final FactA factA = new FactA(); factA.setValue(1); @@ -3863,8 +3960,9 @@ public void setValue(Integer value) { } } - @Test - public void testAccumulateOnTwoPatterns() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateOnTwoPatterns(RUN_TYPE runType) { // DROOLS-5738 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -3876,7 +3974,7 @@ public void testAccumulateOnTwoPatterns() { " insert($sum);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 46 ) ); ksession.insert( new Person( "Mark", 44 ) ); @@ -3888,8 +3986,9 @@ public void testAccumulateOnTwoPatterns() { assertThat(results.get(0)).isEqualTo(90); } - @Test - public void testPositionalAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalAccumulate(RUN_TYPE runType) { // DROOLS-6128 String str = "import " + Result.class.getCanonicalName() + ";" + @@ -3912,7 +4011,7 @@ public void testPositionalAccumulate() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -3921,8 +4020,9 @@ public void testPositionalAccumulate() { assertThat(results.iterator().next().getValue()).isEqualTo(112); } - @Test - public void testAccumulateOnSet() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateOnSet(RUN_TYPE runType) { String str = "import java.util.*;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -3933,7 +4033,7 @@ public void testAccumulateOnSet() { " holder.set($size); \n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); AtomicReference holder = new AtomicReference<>(0); ksession.setGlobal("holder", holder); @@ -3954,8 +4054,9 @@ public void testAccumulateOnSet() { assertThat((int) holder.get()).isEqualTo(4); } - @Test - public void testNestedAccumulates() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedAccumulates(RUN_TYPE runType) { // DROOLS-6202 String str = "import java.util.*;\n" + @@ -3970,7 +4071,7 @@ public void testNestedAccumulates() { " holder.set($max); \n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); AtomicReference holder = new AtomicReference<>(0); ksession.setGlobal("holder", holder); @@ -3991,8 +4092,9 @@ public void testNestedAccumulates() { assertThat((int) holder.get()).isEqualTo(4); } - @Test - public void testIfInInlineAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testIfInInlineAccumulate(RUN_TYPE runType) { // DROOLS-6429 String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -4006,7 +4108,7 @@ public void testIfInInlineAccumulate() { " insert($avg);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Sofia", 10)); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); @@ -4026,8 +4128,9 @@ public void testIfInInlineAccumulate() { assertThat(results).contains(36); } - @Test - public void testBindVariableUsedInSubsequentAccumulateString() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindVariableUsedInSubsequentAccumulateString(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;\n" + @@ -4044,7 +4147,7 @@ public void testBindVariableUsedInSubsequentAccumulateString() { " result.add($maxAge);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -4058,8 +4161,9 @@ public void testBindVariableUsedInSubsequentAccumulateString() { assertThat(result).containsExactly(50); } - @Test - public void testBindVariableUsedInSubsequentAccumulateBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindVariableUsedInSubsequentAccumulateBigDecimal(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;\n" + @@ -4076,7 +4180,7 @@ public void testBindVariableUsedInSubsequentAccumulateBigDecimal() { " result.add($maxAge);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -4090,8 +4194,9 @@ public void testBindVariableUsedInSubsequentAccumulateBigDecimal() { assertThat(result).containsExactly(50); } - @Test - public void testCollectAfterAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testCollectAfterAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "import " + ArrayList.class.getCanonicalName() + ";\n" + @@ -4109,7 +4214,7 @@ public void testCollectAfterAccumulate() { " result.addAll($list)\n" + "end"; try { - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -4130,8 +4235,9 @@ public void testCollectAfterAccumulate() { } } - @Test - public void testExistsFromAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testExistsFromAccumulate(RUN_TYPE runType) { // DROOLS-6959 String str = "import " + Set.class.getCanonicalName() + ";\n" + @@ -4140,15 +4246,16 @@ public void testExistsFromAccumulate() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("String1"); ksession.insert("String2"); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAccumulateWithBetaConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithBetaConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -4161,7 +4268,7 @@ public void testAccumulateWithBetaConstraint() { " insert(new Result($sum + \":\" + $i));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(5); ksession.insert(new Person("Mark", 37)); @@ -4175,8 +4282,9 @@ public void testAccumulateWithBetaConstraint() { assertThat(results).containsExactly(new Result("75:5")); } - @Test - public void testJoinInAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinInAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -4188,7 +4296,7 @@ public void testJoinInAccumulate() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -4207,8 +4315,9 @@ public void testJoinInAccumulate() { assertThat(results).containsExactlyInAnyOrder(new Result(0), new Result(75)); } - @Test - public void testAccumulateSumMultipleParametersExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateSumMultipleParametersExpression(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -4220,8 +4329,8 @@ public void testAccumulateSumMultipleParametersExpression() { " insert(new Result($sum));\n" + "end"; - Results results = createKieBuilder(str).getResults(); - if (testRunType.isExecutableModel()) { + Results results = createKieBuilder(runType, str).getResults(); + if (runType.isExecutableModel()) { assertThat(results.getMessages(Message.Level.ERROR).get(0).getText().contains( "Function \"sum\" cannot have more than 1 parameter")).isTrue(); } else { @@ -4230,8 +4339,9 @@ public void testAccumulateSumMultipleParametersExpression() { } } - @Test - public void testAccumulateSumUnaryExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateSumUnaryExpression(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -4243,7 +4353,7 @@ public void testAccumulateSumUnaryExpression() { " insert(new Result($sum));\n" + "end"; - KieSession kieSession = getKieSession( str ); + KieSession kieSession = getKieSession(runType, str); kieSession.insert(new Person("Mark", 37)); kieSession.insert(new Person("Edson", 35)); @@ -4256,8 +4366,9 @@ public void testAccumulateSumUnaryExpression() { assertThat(results.iterator().next().getValue()).isEqualTo(-77); } - @Test - public void testAccumulateSumBinaryExpWithNestedUnaryExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateSumBinaryExpWithNestedUnaryExpression(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -4269,7 +4380,7 @@ public void testAccumulateSumBinaryExpWithNestedUnaryExpression() { " insert(new Result($sum));\n" + "end"; - KieSession kieSession = getKieSession( str ); + KieSession kieSession = getKieSession(runType, str); kieSession.insert(new Person("Mark", 37)); kieSession.insert(new Person("Edson", 35)); 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 5d99cc628fe..20e3bfe6141 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 @@ -21,6 +21,7 @@ import java.util.List; import java.util.UUID; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.drools.compiler.kie.builder.impl.DrlProject; import org.drools.compiler.kie.builder.impl.InternalKieModule; @@ -28,9 +29,6 @@ import org.drools.core.reteoo.ObjectTypeNode; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; @@ -47,7 +45,6 @@ import static org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE.PATTERN_WITH_ALPHA_NETWORK; import static org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE.STANDARD_WITH_ALPHA_NETWORK; -@RunWith(Parameterized.class) public abstract class BaseModelTest { public enum RUN_TYPE { PATTERN_DSL( true, false ), @@ -72,66 +69,55 @@ public boolean isExecutableModel() { } } - final static Object[] PLAIN = { - RUN_TYPE.STANDARD_FROM_DRL, - PATTERN_DSL, - }; - - final static Object[] WITH_ALPHA_NETWORK = { - RUN_TYPE.STANDARD_FROM_DRL, - PATTERN_DSL, - STANDARD_WITH_ALPHA_NETWORK, - PATTERN_WITH_ALPHA_NETWORK, - }; - - - @Parameters(name = "{0}") - public static Object[] params() { + + public static Stream parameters() { if(Boolean.valueOf(System.getProperty("alphanetworkCompilerEnabled"))) { - return WITH_ALPHA_NETWORK; + return Stream.of(RUN_TYPE.STANDARD_FROM_DRL, + PATTERN_DSL, + STANDARD_WITH_ALPHA_NETWORK, + PATTERN_WITH_ALPHA_NETWORK); } else { - return PLAIN; + return Stream.of(RUN_TYPE.STANDARD_FROM_DRL, + PATTERN_DSL); } } - protected final CompilerTest.RUN_TYPE testRunType; - - public BaseModelTest( CompilerTest.RUN_TYPE testRunType ) { - this.testRunType = testRunType; + public BaseModelTest() { } - protected KieSession getKieSession(String... rules) { + protected KieSession getKieSession(BaseModelTest.RUN_TYPE testRunType, String... rules) { KieModuleModel model = testRunType.isAlphaNetworkCompiler() ? getKieModuleModelWithAlphaNetworkCompiler() : null; - return getKieSession(model, rules); + return getKieSession(testRunType, model, rules); } + - protected KieSession getKieSession(KieModuleModel model, String... stringRules) { - return getKieContainer( model, stringRules ).newKieSession(); + protected KieSession getKieSession(BaseModelTest.RUN_TYPE testRunType, KieModuleModel model, String... stringRules) { + return getKieContainer(testRunType, model, stringRules ).newKieSession(); } - protected KieContainer getKieContainer( KieModuleModel model, String... stringRules ) { - return getKieContainer( model, toKieFiles( stringRules ) ); + protected KieContainer getKieContainer(BaseModelTest.RUN_TYPE testRunType, KieModuleModel model, String... stringRules ) { + return getKieContainer(testRunType, model, toKieFiles( stringRules ) ); } - protected KieContainer getKieContainer( KieModuleModel model, KieFile... stringRules ) { + protected KieContainer getKieContainer(BaseModelTest.RUN_TYPE testRunType, KieModuleModel model, KieFile... stringRules ) { KieServices ks = KieServices.get(); ReleaseId releaseId = ks.newReleaseId( "org.kie", "kjar-test-" + UUID.randomUUID(), "1.0" ); - KieBuilder kieBuilder = createKieBuilder( ks, model, releaseId, stringRules ); + KieBuilder kieBuilder = createKieBuilder(testRunType, ks, model, releaseId, stringRules ); return ks.newKieContainer( releaseId ); } - protected KieBuilder createKieBuilder( String... stringRules ) { + protected KieBuilder createKieBuilder(BaseModelTest.RUN_TYPE testRunType, String... stringRules ) { KieServices ks = KieServices.get(); ReleaseId releaseId = ks.newReleaseId( "org.kie", "kjar-test-" + UUID.randomUUID(), "1.0" ); - return createKieBuilder( ks, null, releaseId, false, toKieFiles( stringRules ) ); + return createKieBuilder(testRunType, ks, null, releaseId, false, toKieFiles( stringRules ) ); } - protected KieBuilder createKieBuilder( KieServices ks, KieModuleModel model, ReleaseId releaseId, KieFile... stringRules ) { - return createKieBuilder( ks, model, releaseId, true, stringRules ); + protected KieBuilder createKieBuilder(BaseModelTest.RUN_TYPE testRunType, KieServices ks, KieModuleModel model, ReleaseId releaseId, KieFile... stringRules ) { + return createKieBuilder(testRunType, ks, model, releaseId, true, stringRules ); } - protected KieBuilder createKieBuilder( KieServices ks, KieModuleModel model, ReleaseId releaseId, boolean failIfBuildError, KieFile... stringRules ) { + protected KieBuilder createKieBuilder(BaseModelTest.RUN_TYPE testRunType, KieServices ks, KieModuleModel model, ReleaseId releaseId, boolean failIfBuildError, KieFile... stringRules ) { ks.getRepository().removeKieModule( releaseId ); KieFileSystem kfs = ks.newKieFileSystem(); @@ -170,20 +156,20 @@ public static List getObjectsIntoList(KieSession ksession, Class clazz return ksession.getInstancesOf(clazz).stream().collect(Collectors.toList()); } - protected void createAndDeployJar( KieServices ks, ReleaseId releaseId, String... drls ) { - createAndDeployJar( ks, null, releaseId, drls ); + protected void createAndDeployJar(BaseModelTest.RUN_TYPE testRunType, KieServices ks, ReleaseId releaseId, String... drls ) { + createAndDeployJar(testRunType, ks, null, releaseId, drls ); } - protected void createAndDeployJar( KieServices ks, ReleaseId releaseId, KieFile... ruleFiles ) { - createAndDeployJar( ks, null, releaseId, ruleFiles ); + protected void createAndDeployJar(BaseModelTest.RUN_TYPE testRunType, KieServices ks, ReleaseId releaseId, KieFile... ruleFiles ) { + createAndDeployJar(testRunType, ks, null, releaseId, ruleFiles ); } - protected void createAndDeployJar( KieServices ks, KieModuleModel model, ReleaseId releaseId, String... drls ) { - createAndDeployJar( ks, model, releaseId, toKieFiles( drls ) ); + protected void createAndDeployJar(BaseModelTest.RUN_TYPE testRunType, KieServices ks, KieModuleModel model, ReleaseId releaseId, String... drls ) { + createAndDeployJar(testRunType, ks, model, releaseId, toKieFiles( drls ) ); } - protected void createAndDeployJar( KieServices ks, KieModuleModel model, ReleaseId releaseId, KieFile... ruleFiles ) { - KieBuilder kieBuilder = createKieBuilder( ks, model, releaseId, ruleFiles ); + protected void createAndDeployJar(BaseModelTest.RUN_TYPE testRunType, KieServices ks, KieModuleModel model, ReleaseId releaseId, KieFile... ruleFiles ) { + KieBuilder kieBuilder = createKieBuilder(testRunType, ks, model, releaseId, ruleFiles ); InternalKieModule kieModule = (InternalKieModule) kieBuilder.getKieModule(); ks.getRepository().addKieModule( kieModule ); } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BetaConditionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BetaConditionTest.java index 03ba9de14c8..2c0eb97cdf5 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BetaConditionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BetaConditionTest.java @@ -22,7 +22,8 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +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; @@ -30,12 +31,10 @@ // DROOLS-5852 public class BetaConditionTest extends BaseModelTest { - public BetaConditionTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - @Test - public void betaCheckTwoConditionsExplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckTwoConditionsExplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -46,11 +45,12 @@ public void betaCheckTwoConditionsExplicit() { " list.add($p2);" + "end\n"; - verify(drl, 2); + verify(runType, drl, 2); } - @Test - public void betaCheckTwoConditionsImplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckTwoConditionsImplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -61,11 +61,12 @@ public void betaCheckTwoConditionsImplicit() { " list.add($p2);" + "end\n"; - verify(drl, 2); + verify(runType, drl, 2); } - @Test - public void betaCheckORExplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckORExplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -76,11 +77,12 @@ public void betaCheckORExplicit() { " list.add($p2);" + "end\n"; - verify(drl, 3); + verify(runType, drl, 3); } - @Test - public void betaCheckORImplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckORImplicit(RUN_TYPE runType) { final String str = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -91,11 +93,12 @@ public void betaCheckORImplicit() { " list.add($p2);" + "end\n"; - verify(str, 3); + verify(runType, str, 3); } - @Test - public void betaCheckExplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckExplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -106,12 +109,13 @@ public void betaCheckExplicit() { " list.add($p2);" + "end\n"; - verify(drl, 2); + verify(runType, drl, 2); } - @Test - public void betaCheckImplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckImplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -122,11 +126,12 @@ public void betaCheckImplicit() { " list.add($p2);" + "end\n"; - verify(drl, 2); + verify(runType, drl, 2); } - @Test - public void checkBooleanExplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void checkBooleanExplicit(RUN_TYPE runType) { final String str = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -136,12 +141,13 @@ public void checkBooleanExplicit() { " list.add($p2);" + "end\n"; - verify(str, 1); + verify(runType, str, 1); } - @Test - public void checkBooleanImplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void checkBooleanImplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -151,11 +157,11 @@ public void checkBooleanImplicit() { " list.add($p2);" + "end\n"; - verify(drl, 1); + verify(runType, drl, 1); } - private void verify(String str, int numberOfResults) { - KieSession ksession = getKieSession(str); + private void verify(RUN_TYPE runType, String str, int numberOfResults) { + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("list", results); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BigPojoExecModelGenerationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BigPojoExecModelGenerationTest.java index 2611f306c22..776e0e7b23b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BigPojoExecModelGenerationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BigPojoExecModelGenerationTest.java @@ -21,7 +21,7 @@ import java.util.UUID; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BindingTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BindingTest.java index 9512691161f..93546bc13a9 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BindingTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BindingTest.java @@ -22,19 +22,17 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +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; public class BindingTest extends BaseModelTest { - public BindingTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testBindUnaryBooleanExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindUnaryBooleanExpression(RUN_TYPE runType) { // RHDM-1612 final String str = "global java.util.List result;\n" + @@ -80,7 +78,7 @@ public void testBindUnaryBooleanExpression() { " result.add(\"R8\");\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal( "result", result ); @@ -105,8 +103,9 @@ public void testBindUnaryBooleanExpression() { assertThat(result.contains("R8")).isFalse(); } - @Test - public void testBindMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindMethodCall(RUN_TYPE runType) { // DROOLS-6521 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -118,7 +117,7 @@ public void testBindMethodCall() { " result.add($value);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal( "result", result ); @@ -130,8 +129,9 @@ public void testBindMethodCall() { assertThat((char) result.get(0)).isEqualTo('r'); } - @Test - public void testEnclosedBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testEnclosedBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;\n" + @@ -141,7 +141,7 @@ public void testEnclosedBinding() { " result.add($n);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -152,8 +152,9 @@ public void testEnclosedBinding() { assertThat(result).containsExactly("Mario"); } - @Test - public void testComplexEnclosedBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexEnclosedBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;\n" + @@ -163,7 +164,7 @@ public void testComplexEnclosedBinding() { " result.add($n);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -174,8 +175,9 @@ public void testComplexEnclosedBinding() { assertThat(result).containsExactly("Mario"); } - @Test - public void testComplexEnclosedDoubleBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexEnclosedDoubleBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;\n" + @@ -185,7 +187,7 @@ public void testComplexEnclosedDoubleBinding() { " result.add($n);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -196,8 +198,9 @@ public void testComplexEnclosedDoubleBinding() { assertThat(result).containsExactly("Mario"); } - @Test - public void testBindingOnRight() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOnRight(RUN_TYPE runType) { // DROOLS-6611 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -208,7 +211,7 @@ public void testBindingOnRight() { " result.add($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -219,8 +222,9 @@ public void testBindingOnRight() { assertThat(result).containsExactly(40); } - @Test - public void testBindingOnBoth() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOnBoth(RUN_TYPE runType) { // DROOLS-6611 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -232,7 +236,7 @@ public void testBindingOnBoth() { " result.add($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -243,8 +247,9 @@ public void testBindingOnBoth() { assertThat(result).containsExactlyInAnyOrder("Mario", 40); } - @Test - public void test3BindingOn3Conditions() { + @ParameterizedTest + @MethodSource("parameters") + public void test3BindingOn3Conditions(RUN_TYPE runType) { // DROOLS-6611 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -257,7 +262,7 @@ public void test3BindingOn3Conditions() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -269,8 +274,9 @@ public void test3BindingOn3Conditions() { assertThat(result).containsExactlyInAnyOrder("Mario", 40, "Cheddar"); } - @Test - public void test2BindingOn3Conditions() { + @ParameterizedTest + @MethodSource("parameters") + public void test2BindingOn3Conditions(RUN_TYPE runType) { // DROOLS-6611 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -282,7 +288,7 @@ public void test2BindingOn3Conditions() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -294,8 +300,9 @@ public void test2BindingOn3Conditions() { assertThat(result).containsExactlyInAnyOrder(40, "Cheddar"); } - @Test - public void testBindingOnRightWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOnRightWithOr(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -306,7 +313,7 @@ public void testBindingOnRightWithOr() { " result.add($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -317,8 +324,9 @@ public void testBindingOnRightWithOr() { assertThat(result).containsExactly(40); } - @Test - public void testBindingOnBothWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOnBothWithOr(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -330,7 +338,7 @@ public void testBindingOnBothWithOr() { " result.add($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -341,8 +349,9 @@ public void testBindingOnBothWithOr() { assertThat(result).containsExactlyInAnyOrder("Toshiya", 40); } - @Test - public void test3BindingOn3ConditionsWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void test3BindingOn3ConditionsWithOr(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -355,7 +364,7 @@ public void test3BindingOn3ConditionsWithOr() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -367,8 +376,9 @@ public void test3BindingOn3ConditionsWithOr() { assertThat(result).containsExactlyInAnyOrder("Toshiya", 10, "Cheddar"); } - @Test - public void test2BindingOn3ConditionsWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void test2BindingOn3ConditionsWithOr(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -380,7 +390,7 @@ public void test2BindingOn3ConditionsWithOr() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -392,8 +402,9 @@ public void test2BindingOn3ConditionsWithOr() { assertThat(result).containsExactlyInAnyOrder(10, "Cheddar"); } - @Test - public void test3BindingOn3ConditionsWithAndOr() { + @ParameterizedTest + @MethodSource("parameters") + public void test3BindingOn3ConditionsWithAndOr(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -406,7 +417,7 @@ public void test3BindingOn3ConditionsWithAndOr() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -434,8 +445,9 @@ public void test3BindingOn3ConditionsWithAndOr() { assertThat(result).isEmpty(); } - @Test - public void test3BindingOn3ConditionsWithOrAnd() { + @ParameterizedTest + @MethodSource("parameters") + public void test3BindingOn3ConditionsWithOrAnd(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -448,7 +460,7 @@ public void test3BindingOn3ConditionsWithOrAnd() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -476,8 +488,9 @@ public void test3BindingOn3ConditionsWithOrAnd() { assertThat(result).isEmpty(); } - @Test - public void testConstraintExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintExpression(RUN_TYPE runType) { String str = "package constraintexpression\n" + "\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -492,7 +505,7 @@ public void testConstraintExpression() { " booleanListGlobal.add($booleanVariable); \n " + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); try { final List booleanListGlobal = new ArrayList<>(); ksession.setGlobal("booleanListGlobal", booleanListGlobal); @@ -511,8 +524,9 @@ public void testConstraintExpression() { * enclosed in parentheses. This is intentional behaviour, agreed in discussions, * which may be revised in the future. */ - @Test - public void testIgnoreConstraintInParentheses() { + @ParameterizedTest + @MethodSource("parameters") + public void testIgnoreConstraintInParentheses(RUN_TYPE runType) { String str = "package constraintexpression\n" + "\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -527,7 +541,7 @@ public void testIgnoreConstraintInParentheses() { " booleanListGlobal.add($booleanVariable); \n " + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); try { final List booleanListGlobal = new ArrayList<>(); ksession.setGlobal("booleanListGlobal", booleanListGlobal); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromDescrTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromDescrTest.java index 2a1f216cf96..44f176c2251 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromDescrTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromDescrTest.java @@ -25,7 +25,7 @@ import org.drools.model.codegen.ExecutableModelProject; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.runtime.KieSession; import org.kie.internal.utils.KieHelper; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromKJarTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromKJarTest.java index 865a9384474..f0fe20d1cb0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromKJarTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromKJarTest.java @@ -21,10 +21,9 @@ import java.util.List; import org.drools.compiler.kie.builder.impl.InternalKieModule; -import org.drools.compiler.kie.builder.impl.KieBuilderImpl; import org.drools.model.codegen.ExecutableModelProject; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CepTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CepTest.java index f1a4080f8b5..c44597ea046 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CepTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CepTest.java @@ -37,7 +37,8 @@ import org.drools.model.codegen.execmodel.domain.StockFact; import org.drools.model.codegen.execmodel.domain.StockTick; import org.drools.model.codegen.execmodel.domain.StockTickEx; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.conf.EventProcessingOption; @@ -53,9 +54,6 @@ public class CepTest extends BaseModelTest { - public CepTest( RUN_TYPE testRunType ) { - super( testRunType ); - } public static KieModuleModel getCepKieModuleModel() { KieModuleModel kproj = KieServices.get().newKieModuleModel(); @@ -67,8 +65,9 @@ public static KieModuleModel getCepKieModuleModel() { return kproj; } - @Test - public void testAfter() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfter(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -78,7 +77,7 @@ public void testAfter() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -93,8 +92,9 @@ public void testAfter() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testNegatedAfter() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegatedAfter(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -104,7 +104,7 @@ public void testNegatedAfter() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -119,8 +119,9 @@ public void testNegatedAfter() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAfterWithEntryPoints() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterWithEntryPoints(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -130,7 +131,7 @@ public void testAfterWithEntryPoints() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.getEntryPoint( "ep1" ).insert( new StockTick( "DROO" ) ); @@ -148,8 +149,9 @@ public void testAfterWithEntryPoints() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testSlidingWindow() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testSlidingWindow(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -158,7 +160,7 @@ public void testSlidingWindow() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); clock.advanceTime( 1, TimeUnit.SECONDS ); @@ -173,8 +175,9 @@ public void testSlidingWindow() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testNotAfter() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNotAfter(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -184,7 +187,7 @@ public void testNotAfter() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick("DROO") ); @@ -202,8 +205,9 @@ public void testNotAfter() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testDeclaredSlidingWindow() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindow(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "declare window DeclaredWindow\n" + @@ -215,7 +219,7 @@ public void testDeclaredSlidingWindow() throws Exception { " System.out.println($a.getCompany());\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); clock.advanceTime( 2, TimeUnit.SECONDS ); @@ -230,8 +234,9 @@ public void testDeclaredSlidingWindow() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testDeclaredSlidingWindowWithEntryPoint() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindowWithEntryPoint(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "declare window DeclaredWindow\n" + @@ -243,7 +248,7 @@ public void testDeclaredSlidingWindowWithEntryPoint() throws Exception { " System.out.println($a.getCompany());\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); EntryPoint ep = ksession.getEntryPoint("ticks"); @@ -260,8 +265,9 @@ public void testDeclaredSlidingWindowWithEntryPoint() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindowOnEventInTypeDeclaration(RUN_TYPE runType) throws Exception { String str = "declare String\n" + " @role( event )\n" + @@ -275,7 +281,7 @@ public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception " System.out.println($a);\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( "ACME" ); @@ -284,8 +290,9 @@ public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testDeclaredSlidingWindowOnDeclaredType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindowOnDeclaredType(RUN_TYPE runType) throws Exception { String str = "declare MyEvent\n" + " @role( event )\n" + @@ -303,13 +310,14 @@ public void testDeclaredSlidingWindowOnDeclaredType() throws Exception { " System.out.println($a);\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testDeclaredSlidingWindowWith2Arguments() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindowWith2Arguments(RUN_TYPE runType) throws Exception { String str = "declare String\n" + " @role( event )\n" + @@ -323,7 +331,7 @@ public void testDeclaredSlidingWindowWith2Arguments() throws Exception { " System.out.println($a);\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( "ACME" ); @@ -332,8 +340,9 @@ public void testDeclaredSlidingWindowWith2Arguments() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testWithDeclaredEvent() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testWithDeclaredEvent(RUN_TYPE runType) throws Exception { String str = "import " + StockFact.class.getCanonicalName() + ";\n" + "declare StockFact @role( event ) end;\n" + @@ -344,7 +353,7 @@ public void testWithDeclaredEvent() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockFact( "DROO" ) ); @@ -359,8 +368,9 @@ public void testWithDeclaredEvent() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testExpireEventOnEndTimestamp() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExpireEventOnEndTimestamp(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler;\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -374,7 +384,7 @@ public void testExpireEventOnEndTimestamp() throws Exception { " resultsAfter.add( $b );\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); List resultsAfter = new ArrayList(); @@ -393,8 +403,9 @@ public void testExpireEventOnEndTimestamp() throws Exception { assertThat(resultsAfter.size()).isEqualTo(1); } - @Test - public void testExpireEventOnEndTimestampWithDeclaredEvent() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExpireEventOnEndTimestampWithDeclaredEvent(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler;\n" + "import " + StockFact.class.getCanonicalName() + ";\n" + @@ -413,7 +424,7 @@ public void testExpireEventOnEndTimestampWithDeclaredEvent() throws Exception { " resultsAfter.add( $b );\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); List resultsAfter = new ArrayList(); @@ -432,8 +443,9 @@ public void testExpireEventOnEndTimestampWithDeclaredEvent() throws Exception { assertThat(resultsAfter.size()).isEqualTo(1); } - @Test - public void testExpires() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExpires(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler;\n" + "import " + StockFact.class.getCanonicalName() + ";\n" + @@ -449,7 +461,7 @@ public void testExpires() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockFact("DROO")); @@ -463,8 +475,9 @@ public void testExpires() throws Exception { assertThat(ksession.getObjects().size()).isEqualTo(0); } - @Test - public void testDeclareAndExpires() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclareAndExpires(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler;\n" + "declare StockFact\n" + @@ -480,7 +493,7 @@ public void testDeclareAndExpires() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); FactType stockFactType = ksession.getKieBase().getFactType("org.drools.compiler", "StockFact"); @@ -498,8 +511,9 @@ public void testDeclareAndExpires() throws Exception { assertThat(ksession.getObjects().size()).isEqualTo(0); } - @Test - public void testNoEvent() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoEvent(RUN_TYPE runType) { String str = "declare BaseEvent\n" + " @role(event)\n" + @@ -526,12 +540,13 @@ public void testNoEvent() { "\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testIntervalTimer() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testIntervalTimer(RUN_TYPE runType) throws Exception { String str = ""; str += "package org.simple \n"; str += "global java.util.List list \n"; @@ -542,7 +557,7 @@ public void testIntervalTimer() throws Exception { str += " list.add(\"fired\"); \n"; str += "end \n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); List list = new ArrayList(); @@ -576,8 +591,9 @@ public void testIntervalTimer() throws Exception { assertThat(list.size()).isEqualTo(3); } - @Test - public void testAfterWithAnd() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterWithAnd(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -587,7 +603,7 @@ public void testAfterWithAnd() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -602,8 +618,9 @@ public void testAfterWithAnd() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnLongFields() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnLongFields(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -613,7 +630,7 @@ public void testAfterOnLongFields() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ).setTimeField( 0 ) ); @@ -626,8 +643,9 @@ public void testAfterOnLongFields() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnDateFields() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnDateFields(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -637,7 +655,7 @@ public void testAfterOnDateFields() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ).setTimeField( 0 ) ); @@ -650,8 +668,9 @@ public void testAfterOnDateFields() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnDateFieldsWithBinding() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnDateFieldsWithBinding(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -661,7 +680,7 @@ public void testAfterOnDateFieldsWithBinding() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); clock.advanceTime( 100, TimeUnit.MILLISECONDS ); @@ -675,8 +694,9 @@ public void testAfterOnDateFieldsWithBinding() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnFactAndField() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnFactAndField(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -686,7 +706,7 @@ public void testAfterOnFactAndField() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ).setTimeField( 0 ) ); @@ -701,8 +721,9 @@ public void testAfterOnFactAndField() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testComplexTimestamp() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexTimestamp(RUN_TYPE runType) { final String str = "import " + Message.class.getCanonicalName() + "\n" + "declare " + Message.class.getCanonicalName() + "\n" + @@ -711,7 +732,7 @@ public void testComplexTimestamp() { " @duration( getProperties().get( 'duration' ) + 1 ) \n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); try { final Message msg = new Message(); @@ -759,8 +780,9 @@ public void setDuration(final Long duration) { } } - @Test - public void testTimerWithMillisPrecision() { + @ParameterizedTest + @MethodSource("parameters") + public void testTimerWithMillisPrecision(RUN_TYPE runType) { final String drl = "import " + MyEvent.class.getCanonicalName() + "\n" + "import " + AtomicInteger.class.getCanonicalName() + "\n" + "declare MyEvent\n" + @@ -781,7 +803,7 @@ public void testTimerWithMillisPrecision() { " }\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), drl); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), drl); try { final long now = 1000; @@ -911,8 +933,9 @@ public void setPrice( Double price ) { } } - @Test - public void testCollectWithDeclaredWindow() { + @ParameterizedTest + @MethodSource("parameters") + public void testCollectWithDeclaredWindow(RUN_TYPE runType) { // DROOLS-4492 final String drl = "import " + Quote.class.getCanonicalName() + "\n" + @@ -942,7 +965,7 @@ public void testCollectWithDeclaredWindow() { " }\n" + "end"; - KieSession ksession = getKieSession( getCepKieModuleModel(), drl ); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), drl ); try { ksession.insert( new Quote("RHT", 10.0) ); @@ -957,8 +980,9 @@ public void testCollectWithDeclaredWindow() { } } - @Test - public void testAfterBindingFirst() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterBindingFirst(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -968,7 +992,7 @@ public void testAfterBindingFirst() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "ACME" ) ); @@ -983,8 +1007,9 @@ public void testAfterBindingFirst() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnLongFieldsBindingFirst() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnLongFieldsBindingFirst(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick @timestamp(timeFieldAsLong) end\n" + @@ -995,7 +1020,7 @@ public void testAfterOnLongFieldsBindingFirst() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockTick("ACME").setTimeField(0)); @@ -1008,8 +1033,9 @@ public void testAfterOnLongFieldsBindingFirst() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBefore() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBefore(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -1019,7 +1045,7 @@ public void testBefore() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "ACME" ) ); @@ -1034,8 +1060,9 @@ public void testBefore() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBeforeBindingFirst() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBeforeBindingFirst(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -1045,7 +1072,7 @@ public void testBeforeBindingFirst() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -1060,8 +1087,9 @@ public void testBeforeBindingFirst() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBeforeOnLongFields() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBeforeOnLongFields(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick @timestamp(timeFieldAsLong) end\n" + @@ -1072,7 +1100,7 @@ public void testBeforeOnLongFields() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockTick("ACME").setTimeField(0)); @@ -1085,8 +1113,9 @@ public void testBeforeOnLongFields() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBeforeOnLongFieldsBindingFirst() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBeforeOnLongFieldsBindingFirst(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick @timestamp(timeFieldAsLong) end\n" + @@ -1097,7 +1126,7 @@ public void testBeforeOnLongFieldsBindingFirst() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockTick("DROO").setTimeField(0)); @@ -1110,8 +1139,9 @@ public void testBeforeOnLongFieldsBindingFirst() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBeforeOnLongFieldsWithDifferentMethod() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBeforeOnLongFieldsWithDifferentMethod(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "import " + StockTickEx.class.getCanonicalName() + ";\n" + @@ -1124,7 +1154,7 @@ public void testBeforeOnLongFieldsWithDifferentMethod() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockTick("ACME").setTimeField(0)); @@ -1137,8 +1167,9 @@ public void testBeforeOnLongFieldsWithDifferentMethod() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnLongFieldsBindingFirstWithDifferentMethod() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnLongFieldsBindingFirstWithDifferentMethod(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "import " + StockTickEx.class.getCanonicalName() + ";\n" + @@ -1151,7 +1182,7 @@ public void testAfterOnLongFieldsBindingFirstWithDifferentMethod() throws Except " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockTick("ACME").setTimeField(0)); @@ -1164,8 +1195,9 @@ public void testAfterOnLongFieldsBindingFirstWithDifferentMethod() throws Except assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testLiteral() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testLiteral(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "declare StockTick @timestamp(timeFieldAsLong) end\n" + @@ -1175,7 +1207,7 @@ public void testLiteral() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); long time = LocalDateTime.of(2020, 1, 1, 0, 0, 0).atZone(ZoneId.of("UTC")).toInstant().getEpochSecond() * 1000; ksession.insert(new StockTick("DROO").setTimeField(time)); @@ -1183,8 +1215,9 @@ public void testLiteral() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testZonedDateTime() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testZonedDateTime(RUN_TYPE runType) throws Exception { String str = "import " + DateTimeHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -1193,7 +1226,7 @@ public void testZonedDateTime() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new DateTimeHolder( ZonedDateTime.now() ) ); @@ -1202,8 +1235,9 @@ public void testZonedDateTime() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCalendarsWithCronAndStartAndEnd() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCalendarsWithCronAndStartAndEnd(RUN_TYPE runType) throws Exception { final Locale defaultLoc = Locale.getDefault(); try { Locale.setDefault(Locale.UK); // Because of the date strings in the DRL, fixable with JBRULES-3444 @@ -1220,7 +1254,7 @@ public void testCalendarsWithCronAndStartAndEnd() throws Exception { " list.add(\"fired\"); \n" + "end \n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); try { final List list = new ArrayList(); final PseudoClockScheduler timeService = ksession.getSessionClock(); @@ -1263,8 +1297,9 @@ public void testCalendarsWithCronAndStartAndEnd() throws Exception { } } - @Test - public void testNegate() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegate(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -1274,7 +1309,7 @@ public void testNegate() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -1289,8 +1324,9 @@ public void testNegate() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNegateFromCollect() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateFromCollect(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "import " + List.class.getCanonicalName() + ";" + @@ -1301,7 +1337,7 @@ public void testNegateFromCollect() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -1316,8 +1352,9 @@ public void testNegateFromCollect() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNegateFromCollectWithDeclaredTimestamp() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateFromCollectWithDeclaredTimestamp(RUN_TYPE runType) throws Exception { String str = "import " + TransactionHistory.class.getCanonicalName() + ";" + "import " + List.class.getCanonicalName() + ";" + @@ -1332,7 +1369,7 @@ public void testNegateFromCollectWithDeclaredTimestamp() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new TransactionHistory(10, toEpochMilliYMD(2022, 5, 12))); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ChannelTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ChannelTest.java index a14a545717d..d9dd067d4a2 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ChannelTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ChannelTest.java @@ -22,7 +22,8 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.Channel; import org.kie.api.runtime.KieSession; @@ -31,11 +32,7 @@ public class ChannelTest extends BaseModelTest { - public ChannelTest(RUN_TYPE testRunType) { - super(testRunType); - } - - public void testChannel(boolean isMvel) { + public void testChannel(RUN_TYPE runType, boolean isMvel) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R \n" + @@ -46,7 +43,7 @@ public void testChannel(boolean isMvel) { " channels[\"testChannel\"].send(\"Test Message\");\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); TestChannel testChannel = new TestChannel(); ksession.registerChannel("testChannel", testChannel); @@ -58,14 +55,16 @@ public void testChannel(boolean isMvel) { assertThat(testChannel.getChannelMessages()).contains("Test Message"); } - @Test - public void testChannelWithJava() { - testChannel(false); + @ParameterizedTest + @MethodSource("parameters") + public void testChannelWithJava(RUN_TYPE runType) { + testChannel(runType, false); } - @Test - public void testChannelWithMvel() { - testChannel(true); + @ParameterizedTest + @MethodSource("parameters") + public void testChannelWithMvel(RUN_TYPE runType) { + testChannel(runType, true); } public static class TestChannel implements Channel { diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilationFailuresTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilationFailuresTest.java index 398ff751800..8dce6906c13 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilationFailuresTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilationFailuresTest.java @@ -22,7 +22,8 @@ import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Message; import org.kie.api.builder.Results; @@ -30,12 +31,10 @@ public class CompilationFailuresTest extends BaseModelTest { - public CompilationFailuresTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - @Test - public void testNonQuotedStringComapre() { + @ParameterizedTest + @MethodSource("parameters") + public void testNonQuotedStringComapre(RUN_TYPE runType) { String drl = "declare Fact\n" + " field : String\n" + @@ -45,15 +44,16 @@ public void testNonQuotedStringComapre() { "then\n" + "end\n"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); // line = -1 even with STANDARD_FROM_DRL (PredicateDescr) assertThat(results.getMessages().get(0).getLine()).isEqualTo(-1); } - @Test - public void testUseNotExistingEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseNotExistingEnum(RUN_TYPE runType) { String drl = "import " + NumberRestriction.class.getCanonicalName() + "\n" + "rule R when\n" + @@ -61,14 +61,14 @@ public void testUseNotExistingEnum() { "then\n" + "end\n"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); assertThat(results.getMessages().get(0).getLine()).isEqualTo(3); } - private Results getCompilationResults( String drl ) { - return createKieBuilder( drl ).getResults(); + private Results getCompilationResults(RUN_TYPE runType, String drl ) { + return createKieBuilder(runType, drl).getResults(); } public static class NumberRestriction { @@ -96,27 +96,31 @@ public String getValueType() { } } - @Test - public void testMaxIntegerResultOnDoublePatternShouldntCompile() { - checkCompilationFailureOnMismatchingAccumulate("Integer", "max"); + @ParameterizedTest + @MethodSource("parameters") + public void testMaxIntegerResultOnDoublePatternShouldntCompile(RUN_TYPE runType) { + checkCompilationFailureOnMismatchingAccumulate(runType, "Integer", "max"); } - @Test - public void testMinIntegerResultOnDoublePatternShouldntCompile() { - checkCompilationFailureOnMismatchingAccumulate("Integer", "min"); + @ParameterizedTest + @MethodSource("parameters") + public void testMinIntegerResultOnDoublePatternShouldntCompile(RUN_TYPE runType) { + checkCompilationFailureOnMismatchingAccumulate(runType, "Integer", "min"); } - @Test - public void testMaxLongResultOnDoublePatternShouldntCompile() { - checkCompilationFailureOnMismatchingAccumulate("Long", "max"); + @ParameterizedTest + @MethodSource("parameters") + public void testMaxLongResultOnDoublePatternShouldntCompile(RUN_TYPE runType) { + checkCompilationFailureOnMismatchingAccumulate(runType, "Long", "max"); } - @Test - public void testMinLongResultOnDoublePatternShouldntCompile() { - checkCompilationFailureOnMismatchingAccumulate("Long", "min"); + @ParameterizedTest + @MethodSource("parameters") + public void testMinLongResultOnDoublePatternShouldntCompile(RUN_TYPE runType) { + checkCompilationFailureOnMismatchingAccumulate(runType, "Long", "min"); } - private void checkCompilationFailureOnMismatchingAccumulate(String type, String accFunc) { + private void checkCompilationFailureOnMismatchingAccumulate(RUN_TYPE runType, String type, String accFunc) { String drl = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -128,7 +132,7 @@ private void checkCompilationFailureOnMismatchingAccumulate(String type, String " System.out.println($max);\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); // line = 1 with STANDARD_FROM_DRL (RuleDescr) @@ -136,8 +140,9 @@ private void checkCompilationFailureOnMismatchingAccumulate(String type, String } - @Test - public void modify_factInScope_java() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_java(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -148,12 +153,13 @@ public void modify_factInScope_java() { " modify($p) { $p.setName(\"Mark\") }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void modify_factInScope_mvel() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_mvel(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -165,12 +171,13 @@ public void modify_factInScope_mvel() { " modify($p) { $p.setName(\"Mark\") }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void modify_factInScope_nestedPropertySetter_java() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_nestedPropertySetter_java(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -181,12 +188,13 @@ public void modify_factInScope_nestedPropertySetter_java() { " modify($p) { $p.address.setCity(\"London\") }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void modify_factInScope_nestedPropertySetter_mvel() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_nestedPropertySetter_mvel(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -198,12 +206,13 @@ public void modify_factInScope_nestedPropertySetter_mvel() { " modify($p) { $p.address.setCity(\"London\") }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void modify_factInScope_nestedPropertyAssign_java() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_nestedPropertyAssign_java(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -214,12 +223,13 @@ public void modify_factInScope_nestedPropertyAssign_java() { " modify($p) { $p.address.city = \"London\" }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void modify_factInScope_nestedPropertyAssign_mvel() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_nestedPropertyAssign_mvel(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -231,12 +241,13 @@ public void modify_factInScope_nestedPropertyAssign_mvel() { " modify($p) { $p.address.city = \"London\" }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void testVariableInsideBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testVariableInsideBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + NameLengthCount.class.getCanonicalName() + ";" + @@ -246,13 +257,14 @@ public void testVariableInsideBinding() { "then\n" + "end"; - Results results = createKieBuilder(str ).getResults(); + Results results = createKieBuilder(runType, str).getResults(); assertThat(results.getMessages(Message.Level.ERROR).stream().map(Message::getText)) .contains("Variables can not be used inside bindings. Variable [$nlc] is being used in binding '$nlc.self.getNameLength(name)'"); } - @Test - public void testVariableInsideBindingInParameter() { + @ParameterizedTest + @MethodSource("parameters") + public void testVariableInsideBindingInParameter(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + NameLengthCount.class.getCanonicalName() + ";" + @@ -262,7 +274,7 @@ public void testVariableInsideBindingInParameter() { "then\n" + "end"; - Results results = createKieBuilder(str ).getResults(); + Results results = createKieBuilder(runType, str ).getResults(); assertThat(results.getMessages(Message.Level.ERROR).stream().map(Message::getText)) .contains("Variables can not be used inside bindings. Variable [$nlc] is being used in binding 'identityBigDecimal($nlc.fortyTwo)'"); } @@ -282,8 +294,9 @@ public BigDecimal getFortyTwo() { } } - @Test - public void testTypeSafe() { + @ParameterizedTest + @MethodSource("parameters") + public void testTypeSafe(RUN_TYPE runType) { String str = "import " + Parent.class.getCanonicalName() + ";" + "declare\n" + @@ -295,8 +308,8 @@ public void testTypeSafe() { "then\n" + "end\n"; - Results results = createKieBuilder(str).getResults(); - if (testRunType.isExecutableModel()) { + Results results = createKieBuilder(runType, str).getResults(); + if (runType.isExecutableModel()) { assertThat(results.getMessages(Message.Level.ERROR).get(0).getText().contains("@typesafe(false) is not supported in executable model")); } else { assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isTrue(); 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 702020fb7e5..abe40ca412c 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 @@ -43,10 +43,10 @@ import org.drools.model.codegen.execmodel.domain.StockTick; import org.drools.model.codegen.execmodel.domain.Toy; import org.drools.model.codegen.execmodel.domain.Woman; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.process.ProcessContext; @@ -57,12 +57,10 @@ public class CompilerTest extends BaseModelTest { - public CompilerTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test(timeout = 5000) - public void testPropertyReactivity() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(5000) + public void testPropertyReactivity(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -71,7 +69,7 @@ public void testPropertyReactivity() { " modify($p) { setAge($p.getAge()+1) }\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); ksession.insert( me ); @@ -80,8 +78,9 @@ public void testPropertyReactivity() { assertThat(me.getAge()).isEqualTo(41); } - @Test - public void testPropertyReactivityWithArguments() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityWithArguments(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R \n" + @@ -91,7 +90,7 @@ public void testPropertyReactivityWithArguments() { " modify($p) { setLikes( String.valueOf(($p.getAddress().getStreet() + $p.getAddress().getCity()))) };\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); me.setAddress(new Address("street1", 2, "city1")); @@ -101,8 +100,9 @@ public void testPropertyReactivityWithArguments() { assertThat(me.getLikes()).isEqualTo("street1city1"); } - @Test - public void testPropertyReactvityOnFinalField() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactvityOnFinalField(RUN_TYPE runType) throws Exception { String str = "rule R when\n" + " $a : String( length > 3 )\n" + @@ -110,7 +110,7 @@ public void testPropertyReactvityOnFinalField() throws Exception { " System.out.println($a);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "abcd" ); ksession.insert( "xy" ); @@ -118,8 +118,9 @@ public void testPropertyReactvityOnFinalField() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEqualityCheckOnNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testEqualityCheckOnNull(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -129,7 +130,7 @@ public void testEqualityCheckOnNull() { " insert(new Result($name));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final Person mario = new Person("Mario", 40); final Person luca = new Person(null, 33); @@ -144,8 +145,9 @@ public void testEqualityCheckOnNull() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testOrWithFixedLeftOperand() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWithFixedLeftOperand(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -155,7 +157,7 @@ public void testOrWithFixedLeftOperand() { " insert(new Result($p));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final Person mario = new Person("Mario", 40); final Person luca = new Person("Luca", 33); @@ -174,8 +176,9 @@ public void testOrWithFixedLeftOperand() { assertThat(results.stream().map(r -> r.getValue())).containsExactlyInAnyOrder(mario, luca, edoardo); } - @Test - public void testCapitalLetterProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testCapitalLetterProperty(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -185,7 +188,7 @@ public void testCapitalLetterProperty() { " insert(new Result($p));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final Person luca = new Person("Luca", 35); final Person leonardo = new Person("Leonardo", 2).setParentP(luca); @@ -202,8 +205,9 @@ public void testCapitalLetterProperty() { assertThat(results.stream().map(Result::getValue)).containsExactlyInAnyOrder(leonardo); } - @Test - public void testBeta() { + @ParameterizedTest + @MethodSource("parameters") + public void testBeta(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -215,7 +219,7 @@ public void testBeta() { " $r.setValue($olderV.getName() + \" is older than \" + $markV.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -244,8 +248,9 @@ public void testBeta() { } - @Test - public void testBetaMap() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaMap(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + @@ -258,7 +263,7 @@ public void testBetaMap() { " $r.setValue($olderV.get(\"name\") + \" is older than \" + $markV.get(\"name\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -287,8 +292,9 @@ public void testBetaMap() { assertThat(result.getValue()).isEqualTo("Edson is older than Mark"); } - @Test - public void testBetaMapComparisonWithLiteral() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaMapComparisonWithLiteral(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Map.class.getCanonicalName() + ";" + @@ -299,7 +305,7 @@ public void testBetaMapComparisonWithLiteral() { " $r.setValue($olderV.get(\"name\") + \" is older than Mark\"\n);" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -328,8 +334,9 @@ private Map mapPerson(String name, int age) { return person; } - @Test - public void testRuleExtends() { + @ParameterizedTest + @MethodSource("parameters") + public void testRuleExtends(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -347,7 +354,7 @@ public void testRuleExtends() { " $r.setValue($p2.getName() + \" is older than \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -363,8 +370,9 @@ public void testRuleExtends() { assertThat(result.getValue()).isEqualTo("Mario is older than Mark"); } - @Test - public void testBetaWithDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaWithDeclaration(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -376,7 +384,7 @@ public void testBetaWithDeclaration() { " $r.setValue($p2.getName() + \" is older than \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -404,8 +412,9 @@ public void testBetaWithDeclaration() { assertThat(result.getValue()).isEqualTo("Edson is older than Mark"); } - @Test - public void test3Patterns() { + @ParameterizedTest + @MethodSource("parameters") + public void test3Patterns(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -416,7 +425,7 @@ public void test3Patterns() { " System.out.println(\"Found: \" + $s);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); ksession.insert( new Person( "Mark", 37 ) ); @@ -425,8 +434,9 @@ public void test3Patterns() { ksession.fireAllRules(); } - @Test - public void testSimpleInsert() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleInsert(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -437,7 +447,7 @@ public void testSimpleInsert() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 37 ) ); ksession.insert( new Person( "Mario", 40 ) ); @@ -448,8 +458,9 @@ public void testSimpleInsert() { assertThat(results.iterator().next().getValue()).isEqualTo("Mark"); } - @Test - public void testSimpleInsertWithProperties() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleInsertWithProperties(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -460,7 +471,7 @@ public void testSimpleInsertWithProperties() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 37, new Address("London")) ); ksession.insert( new Person( "Luca", 32 , new Address("Milan")) ); @@ -471,8 +482,9 @@ public void testSimpleInsertWithProperties() { assertThat(results.iterator().next().getValue()).isEqualTo("Luca"); } - @Test - public void testSimpleDelete() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleDelete(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -484,7 +496,7 @@ public void testSimpleDelete() { " delete($p);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 37 ) ); ksession.insert( new Person( "Mario", 40 ) ); @@ -496,8 +508,9 @@ public void testSimpleDelete() { assertThat(getObjectsIntoList(ksession, Person.class).size()).isEqualTo(1); } - @Test - public void testSimpleInsertDeleteExplicitScope() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleInsertDeleteExplicitScope(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -509,7 +522,7 @@ public void testSimpleInsertDeleteExplicitScope() { " drools.delete($p);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 37 ) ); ksession.insert( new Person( "Mario", 40 ) ); @@ -521,8 +534,9 @@ public void testSimpleInsertDeleteExplicitScope() { assertThat(getObjectsIntoList(ksession, Person.class).size()).isEqualTo(1); } - @Test - public void testSimpleUpdate() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleUpdate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -532,7 +546,7 @@ public void testSimpleUpdate() { " update($p);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mark = new Person( "Mark", 37 ); Person mario = new Person( "Mario", 40 ); @@ -545,8 +559,9 @@ public void testSimpleUpdate() { assertThat(mario.getAge()).isEqualTo(40); } - @Test - public void testSimpleModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleModify(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -555,7 +570,7 @@ public void testSimpleModify() { " modify($p) { setAge($p.getAge()+1) }\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mark = new Person( "Mark", 37 ); Person mario = new Person( "Mario", 40 ); @@ -568,8 +583,9 @@ public void testSimpleModify() { assertThat(mario.getAge()).isEqualTo(40); } - @Test - public void testEmptyPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testEmptyPattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -579,7 +595,7 @@ public void testEmptyPattern() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person( "Mario", 40 ); @@ -591,8 +607,9 @@ public void testEmptyPattern() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testEmptyPatternWithBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testEmptyPatternWithBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -602,7 +619,7 @@ public void testEmptyPatternWithBinding() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person( "Mario", 40 ); @@ -614,8 +631,9 @@ public void testEmptyPatternWithBinding() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testFrom(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Adult.class.getCanonicalName() + ";\n" + @@ -628,7 +646,7 @@ public void testFrom() { " $r.setValue($c.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -642,17 +660,19 @@ public void testFrom() { assertThat(result.getValue()).isEqualTo("Alan"); } - @Test - public void testConcatenatedFrom() { - checkConcatenatedFrom(true); + @ParameterizedTest + @MethodSource("parameters") + public void testConcatenatedFrom(RUN_TYPE runType) { + checkConcatenatedFrom(runType, true); } - @Test - public void testConcatenatedFromWithCondition() { - checkConcatenatedFrom(false); + @ParameterizedTest + @MethodSource("parameters") + public void testConcatenatedFromWithCondition(RUN_TYPE runType) { + checkConcatenatedFrom(runType, false); } - private void checkConcatenatedFrom(boolean withCondition) { + private void checkConcatenatedFrom(RUN_TYPE runType, boolean withCondition) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Man.class.getCanonicalName() + ";\n" + @@ -669,7 +689,7 @@ private void checkConcatenatedFrom(boolean withCondition) { " list.add($t.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -696,8 +716,9 @@ private void checkConcatenatedFrom(boolean withCondition) { assertThat(list).containsExactlyInAnyOrder("car", "ball"); } - @Test - public void testAgeWithSum() { + @ParameterizedTest + @MethodSource("parameters") + public void testAgeWithSum(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -708,7 +729,7 @@ public void testAgeWithSum() { " insert(new Result($plusTwo.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -720,8 +741,9 @@ public void testAgeWithSum() { assertThat(results.iterator().next().getValue()).isEqualTo("Mark"); } - @Test - public void testAgeWithSumUsing2DeclarationInBeta() { + @ParameterizedTest + @MethodSource("parameters") + public void testAgeWithSumUsing2DeclarationInBeta(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -732,7 +754,7 @@ public void testAgeWithSumUsing2DeclarationInBeta() { " insert(new Result($plusTwo.getName()));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.insert(new Person("Mark", 37)); @@ -745,8 +767,9 @@ public void testAgeWithSumUsing2DeclarationInBeta() { assertThat(results.iterator().next().getValue()).isEqualTo("Mark"); } - @Test - public void testFunction3() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunction3(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -759,7 +782,7 @@ public void testFunction3() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -771,15 +794,16 @@ public void testFunction3() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testInsertLogical() { + @ParameterizedTest + @MethodSource("parameters") + public void testInsertLogical(RUN_TYPE runType) { String str = "rule R when\n" + " Integer()" + "then\n" + " insertLogical(\"Hello World\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_47 = ksession.insert(47); ksession.fireAllRules(); @@ -794,8 +818,9 @@ public void testInsertLogical() { assertThat(results.contains("Hello World")).isFalse(); } - @Test - public void testModifyRewriteAvoidTwiceThePreceeding() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyRewriteAvoidTwiceThePreceeding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List globalA \n" + "global java.util.List globalB \n" + @@ -808,7 +833,7 @@ public void testModifyRewriteAvoidTwiceThePreceeding() { " globalB.add(\"B\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List globalA = new ArrayList<>(); List globalB = new ArrayList<>(); @@ -822,8 +847,9 @@ public void testModifyRewriteAvoidTwiceThePreceeding() { assertThat(globalB.size()).isEqualTo(1); } - @Test - public void testEmptyModifyRewrite() { + @ParameterizedTest + @MethodSource("parameters") + public void testEmptyModifyRewrite(RUN_TYPE runType) { String str = "rule R \n" + "no-loop \n" + "when\n" + @@ -833,7 +859,7 @@ public void testEmptyModifyRewrite() { " modify( $s ) { }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Hello World"); int fired = ksession.fireAllRules(); @@ -841,8 +867,9 @@ public void testEmptyModifyRewrite() { assertThat(fired).isEqualTo(1); } - @Test() - public void testModifyRewriteWithComments() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyRewriteWithComments(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List globalA \n" + "global java.util.List globalB \n" + @@ -861,7 +888,7 @@ public void testModifyRewriteWithComments() { " /* modify ; something */\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List globalA = new ArrayList<>(); List globalB = new ArrayList<>(); @@ -877,9 +904,10 @@ public void testModifyRewriteWithComments() { assertThat(person1.getAge()).isEqualTo(47); } - @Test() - @Ignore("fails for exec model, is not recognizing properly start/ends of modify block") - public void testModifyRewriteWithCommentsAbsurd() { + @ParameterizedTest + @MethodSource("parameters") + @Disabled("fails for exec model, is not recognizing properly start/ends of modify block") + public void testModifyRewriteWithCommentsAbsurd(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List globalA \n" + "global java.util.List globalB \n" + @@ -898,7 +926,7 @@ public void testModifyRewriteWithCommentsAbsurd() { " /* modify( $p ) { setAge(2) } */\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List globalA = new ArrayList<>(); List globalB = new ArrayList<>(); @@ -914,8 +942,9 @@ public void testModifyRewriteWithCommentsAbsurd() { assertThat(person1.getAge()).isEqualTo(47); } - @Test - public void testConstraintContainingAMethodCallWithParams() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintContainingAMethodCallWithParams(RUN_TYPE runType) { String str = "import " + Overloaded.class.getCanonicalName() + ";" + "rule OverloadedMethods\n" + "when\n" + @@ -924,7 +953,7 @@ public void testConstraintContainingAMethodCallWithParams() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Overloaded()); ksession.fireAllRules(); @@ -933,8 +962,9 @@ public void testConstraintContainingAMethodCallWithParams() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testSimpleModifyUsingNameRefFollowedByMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleModifyUsingNameRefFollowedByMethodCall(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -943,7 +973,7 @@ public void testSimpleModifyUsingNameRefFollowedByMethodCall() { " modify($p) { setAge($p.getAge()+1) }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person mark = new Person("Mark", 37); Person mario = new Person("Mario", 40); @@ -956,8 +986,9 @@ public void testSimpleModifyUsingNameRefFollowedByMethodCall() { assertThat(mario.getAge()).isEqualTo(40); } - @Test - public void testChainOfMethodCallInConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testChainOfMethodCallInConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $p : Person( getAddress().getCity().length() == 5 )\n" + @@ -965,7 +996,7 @@ public void testChainOfMethodCallInConstraint() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); Address a = new Address("Italy"); @@ -978,8 +1009,9 @@ public void testChainOfMethodCallInConstraint() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testChainOfMethodCallInConstraintSub() { + @ParameterizedTest + @MethodSource("parameters") + public void testChainOfMethodCallInConstraintSub(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $p : Person( address.(city.startsWith(\"I\") && city.length() == 5 ) )\n" + // DRL feature "Grouped accessors for nested objects" is addressed by the RuleDescr directly. @@ -987,7 +1019,7 @@ public void testChainOfMethodCallInConstraintSub() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); Address a = new Address("Italy"); @@ -1000,8 +1032,9 @@ public void testChainOfMethodCallInConstraintSub() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testChainFieldAccessorsAndMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testChainFieldAccessorsAndMethodCall(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $p : Person( address.getCity().length == 5 )\n" + @@ -1009,7 +1042,7 @@ public void testChainFieldAccessorsAndMethodCall() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); Address a = new Address("Italy"); @@ -1022,8 +1055,9 @@ public void testChainFieldAccessorsAndMethodCall() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testInnerBindingWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerBindingWithOr(RUN_TYPE runType) { String str = "global java.util.List list\n" + "\n" + @@ -1033,7 +1067,7 @@ public void testInnerBindingWithOr() { " list.add(s);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList(); ksession.setGlobal("list", list); @@ -1045,8 +1079,9 @@ public void testInnerBindingWithOr() { assertThat(list.get(0)).isEqualTo("y"); } - @Test - public void testRHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testRHS(RUN_TYPE runType) { String str = "rule R when\n" + " //conditions\n" + @@ -1060,11 +1095,12 @@ public void testRHS() { " kcontext.getKnowledgeRuntime();\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); } - @Test - public void testBindWith2Arguments() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindWith2Arguments(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -1075,7 +1111,7 @@ public void testBindWith2Arguments() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); ksession.insert( a ); @@ -1085,8 +1121,9 @@ public void testBindWith2Arguments() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(48); } - @Test - public void testLockOnActiveWithModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testLockOnActiveWithModify(RUN_TYPE runType) { String str = "package org.drools.test; \n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1112,7 +1149,7 @@ public void testLockOnActiveWithModify() { " modify ( $p ) { setName( \"john\" ); } \n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -1124,8 +1161,9 @@ public void testLockOnActiveWithModify() { assertThat(p.getName()).isEqualTo("john"); } - @Test - public void testAlphaConstraintOn2Properties() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintOn2Properties(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -1133,15 +1171,16 @@ public void testAlphaConstraintOn2Properties() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); ksession.insert( me ); ksession.fireAllRules(); } - @Test - public void testAlphaNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaNull(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1162,7 +1201,7 @@ public void testAlphaNull() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person first = new Person(null, 40); Person second = new Person("Luca", 40); @@ -1179,8 +1218,9 @@ public void testAlphaNull() { assertThat(results).containsExactlyInAnyOrder("Luca", null); } - @Test - public void testAlphaNullBoolean() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaNullBoolean(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1190,7 +1230,7 @@ public void testAlphaNullBoolean() { " insert(new Result($p.getName()));\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person first = new Person("First", 40); first.setEmployed(null); @@ -1207,8 +1247,9 @@ public void testAlphaNullBoolean() { assertThat(results).containsExactlyInAnyOrder("Second"); } - @Test - public void testStringValueOf() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringValueOf(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -1219,7 +1260,7 @@ public void testStringValueOf() { " insert(new Result($i));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 44 ); ksession.insert( new Person( "44", 44 ) ); @@ -1229,8 +1270,9 @@ public void testStringValueOf() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(44); } - @Test - public void testBigDecimalBigIntegerCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalBigIntegerCoercion(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigInteger.class.getCanonicalName() + ";\n" + "rule \"rule1\"\n" + @@ -1250,7 +1292,7 @@ public void testBigDecimalBigIntegerCoercion() { "end\n"; - KieSession ksession1 = getKieSession(str); + KieSession ksession1 = getKieSession(runType, str); Person p1 = new Person(); p1.setMoney( new BigDecimal(1 ) ); @@ -1259,8 +1301,9 @@ public void testBigDecimalBigIntegerCoercion() { } - @Test - public void testBigDecimalOperationsInConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalOperationsInConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List results;\n" + @@ -1271,7 +1314,7 @@ public void testBigDecimalOperationsInConstraint() { " results.add($moneyDoubled);\n" + "end\n"; - KieSession ksession1 = getKieSession(str); + KieSession ksession1 = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession1.setGlobal("results", results); @@ -1285,8 +1328,9 @@ public void testBigDecimalOperationsInConstraint() { } - @Test - public void testSingleQuoteString() { + @ParameterizedTest + @MethodSource("parameters") + public void testSingleQuoteString(RUN_TYPE runType) { String str = "rule R1 when\n" + " String( this == 'x' )\n" + @@ -1297,15 +1341,16 @@ public void testSingleQuoteString() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "x" ); ksession.insert( "xx" ); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testIntToLongComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testIntToLongComparison(RUN_TYPE runType) { String str = "rule R when\n" + " $i : Integer()\n" + @@ -1313,7 +1358,7 @@ public void testIntToLongComparison() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 1 ); ksession.insert( 2L ); @@ -1321,8 +1366,9 @@ public void testIntToLongComparison() { } - @Test - public void testUseGlobalInLHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseGlobalInLHS(RUN_TYPE runType) { // DROOLS-1025 final String drl1 = "import " + Result.class.getCanonicalName() + ";\n" + @@ -1333,7 +1379,7 @@ public void testUseGlobalInLHS() { " insert(new Result(\"match\"));\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.setGlobal("globalInt", new AtomicInteger(0)); @@ -1343,8 +1389,9 @@ public void testUseGlobalInLHS() { assertThat(results.iterator().next().getValue().toString()).isEqualTo("match"); } - @Test - public void testMapAccess() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccess(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "rule R1 when\n" + @@ -1352,7 +1399,7 @@ public void testMapAccess() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put("type", "Goods"); @@ -1361,8 +1408,9 @@ public void testMapAccess() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapAccessBindingConstant() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessBindingConstant(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "rule R1 when\n" + @@ -1370,7 +1418,7 @@ public void testMapAccessBindingConstant() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put("type", "Goods"); @@ -1379,8 +1427,9 @@ public void testMapAccessBindingConstant() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapAccessBindingConstantJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessBindingConstantJoin(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1394,7 +1443,7 @@ public void testMapAccessBindingConstantJoin() { " results.add($p.getName());\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ArrayList results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1413,8 +1462,9 @@ public void testMapAccessBindingConstantJoin() { assertThat(results).containsExactlyInAnyOrder("Andrea", "Luca"); } - @Test - public void testMapAccessBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessBinding(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "rule R1 when\n" + @@ -1423,7 +1473,7 @@ public void testMapAccessBinding() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put("type", "Goods"); @@ -1433,8 +1483,9 @@ public void testMapAccessBinding() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStringBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringBinding(RUN_TYPE runType) { final String drl1 = "import " + Result.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -1443,7 +1494,7 @@ public void testStringBinding() { " insert(new Result($t));\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( "whatever" ); assertThat(ksession.fireAllRules()).isEqualTo(1); @@ -1452,8 +1503,9 @@ public void testStringBinding() { assertThat(results.iterator().next().getValue().toString()).isEqualTo("type"); } - @Test - public void testMapAccessProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessProperty(RUN_TYPE runType) { final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + "import java.util.Map;\n" + @@ -1462,7 +1514,7 @@ public void testMapAccessProperty() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put(1, 2000); @@ -1478,8 +1530,9 @@ public void testMapAccessProperty() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapInitialization() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapInitialization(RUN_TYPE runType) { final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + "import java.util.Map;\n" + @@ -1489,7 +1542,7 @@ public void testMapInitialization() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Person luca = new Person("Luca"); luca.setNumberOfItems(2); @@ -1502,8 +1555,9 @@ public void testMapInitialization() { } - @Test - public void testErrorTwoPatterns() { + @ParameterizedTest + @MethodSource("parameters") + public void testErrorTwoPatterns(RUN_TYPE runType) { // DROOLS-3850 final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1515,7 +1569,7 @@ public void testErrorTwoPatterns() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Person luca = new Person("Luca"); luca.setNumberOfItems(2); @@ -1528,8 +1582,9 @@ public void testErrorTwoPatterns() { } - @Test - public void testMapWithBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapWithBinding(RUN_TYPE runType) { // DROOLS-3558 final String drl1 = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1541,7 +1596,7 @@ public void testMapWithBinding() { " then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Person john = new Person("John"); HashMap items = new HashMap(); @@ -1557,8 +1612,9 @@ public void testMapWithBinding() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapAccessPropertyWithCast() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessPropertyWithCast(RUN_TYPE runType) { final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + "import java.util.Map;\n" + @@ -1567,7 +1623,7 @@ public void testMapAccessPropertyWithCast() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put(1, 2000); @@ -1583,8 +1639,9 @@ public void testMapAccessPropertyWithCast() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testArrayAccess() { + @ParameterizedTest + @MethodSource("parameters") + public void testArrayAccess(RUN_TYPE runType) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1596,13 +1653,14 @@ public void testArrayAccess() { "then\n" + "end\n"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testInOperators() { + @ParameterizedTest + @MethodSource("parameters") + public void testInOperators(RUN_TYPE runType) { final String drl1 = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"eval rewrite with 'in'\"\n" + @@ -1611,7 +1669,7 @@ public void testInOperators() { " then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Person luca = new Person("Luca"); luca.setAge(2); @@ -1640,8 +1698,9 @@ public void setaBcde(String aBcde) { } } - @Test - public void testGetterSetterCase() { + @ParameterizedTest + @MethodSource("parameters") + public void testGetterSetterCase(RUN_TYPE runType) { // DROOLS-2724 final String drl = "import " + TestFact.class.getCanonicalName() + ";\n" + @@ -1650,13 +1709,14 @@ public void testGetterSetterCase() { "when \n" + " TestFact(aBcde == \"test\")\n" + "then end"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); kieSession.insert(new TestFact("test")); assertThat(kieSession.fireAllRules()).isEqualTo(1); } - @Test - public void testCommaInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testCommaInModify(RUN_TYPE runType) { // DROOLS-3505 final String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -1667,7 +1727,7 @@ public void testCommaInModify() { "then\n" + " modify($p) { setAge(1), setLikes(\"bread\"); }\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); Person john = new Person("John", 24); kieSession.insert(john); assertThat(kieSession.fireAllRules()).isEqualTo(1); @@ -1701,8 +1761,9 @@ public void setStatus( int status ) { } } - @Test - public void testStaticFieldClashingWithClassName() { + @ParameterizedTest + @MethodSource("parameters") + public void testStaticFieldClashingWithClassName(RUN_TYPE runType) { // DROOLS-3560 final String drl = "import " + Message.class.getCanonicalName() + "\n" + @@ -1723,7 +1784,7 @@ public void testStaticFieldClashingWithClassName() { " System.out.println( myMessage );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); Message message = new Message(); message.setMessage( "Hi" ); message.setStatus( Message.HELLO ); @@ -1731,8 +1792,9 @@ public void testStaticFieldClashingWithClassName() { assertThat(kieSession.fireAllRules()).isEqualTo(2); } - @Test - public void testDoubleModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoubleModify(RUN_TYPE runType) { // DROOLS-3560 final String drl = "import " + Message.class.getCanonicalName() + "\n" + @@ -1754,7 +1816,7 @@ public void testDoubleModify() { " System.out.println( myMessage );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); Message message = new Message(); message.setMessage( "Hi" ); message.setStatus( Message.HELLO ); @@ -1762,8 +1824,9 @@ public void testDoubleModify() { assertThat(kieSession.fireAllRules()).isEqualTo(2); } - @Test - public void testPrettyPrinterCrashing() { + @ParameterizedTest + @MethodSource("parameters") + public void testPrettyPrinterCrashing(RUN_TYPE runType) { final String drl = "" + "package org.drools.compiler.test \n" + @@ -1801,7 +1864,7 @@ public void testPrettyPrinterCrashing() { "end\n" + "\n"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); try { final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1816,8 +1879,9 @@ public void testPrettyPrinterCrashing() { } } - @Test - public void testBetaJoinBigInteger() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaJoinBigInteger(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -1829,7 +1893,7 @@ public void testBetaJoinBigInteger() { " $r.setValue($olderV.getName() + \" is older than \" + $markV.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -1846,8 +1910,9 @@ public void testBetaJoinBigInteger() { assertThat(result.getValue()).isEqualTo("Mario is older than Mark"); } - @Test - public void testBetaJoinBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaJoinBigDecimal(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -1859,7 +1924,7 @@ public void testBetaJoinBigDecimal() { " $r.setValue($richerV.getName() + \" is richer than \" + $markV.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -1876,8 +1941,9 @@ public void testBetaJoinBigDecimal() { assertThat(result.getValue()).isEqualTo("Mario is richer than Mark"); } - @Test - public void testBetaCast() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaCast(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -1890,7 +1956,7 @@ public void testBetaCast() { " $r.setValue($a.getCity() + \" number has the same value of \" + $p.getName() + \" age\");\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -1916,8 +1982,9 @@ public void testBetaCast() { assertThat(result.getValue()).isEqualTo("Milan number has the same value of Mark age"); } - @Test - public void testNumericLimitsLiteral() { + @ParameterizedTest + @MethodSource("parameters") + public void testNumericLimitsLiteral(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -1928,7 +1995,7 @@ public void testNumericLimitsLiteral() { " $r.setValue($p.getName() + \" is very old\");\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -1949,8 +2016,9 @@ public void testNumericLimitsLiteral() { - @Test - public void testBetaCastGreaterThan() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaCastGreaterThan(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -1963,7 +2031,7 @@ public void testBetaCastGreaterThan() { " $r.setValue($a.getCity() + \" number is greater than \" + $p.getName() + \" age\");\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -1995,8 +2063,9 @@ public void testBetaCastGreaterThan() { } - @Test - public void testNumericLimits() { + @ParameterizedTest + @MethodSource("parameters") + public void testNumericLimits(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -2007,7 +2076,7 @@ public void testNumericLimits() { " $r.setValue($p.getName() + \" is very old\");\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -2026,8 +2095,9 @@ public void testNumericLimits() { } - @Test - public void testMapAbbreviatedComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAbbreviatedComparison(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "rule R1 when\n" + @@ -2035,7 +2105,7 @@ public void testMapAbbreviatedComparison() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put("money", new BigDecimal(70)); @@ -2044,8 +2114,9 @@ public void testMapAbbreviatedComparison() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapPrimitiveComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapPrimitiveComparison(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -2055,7 +2126,7 @@ public void testMapPrimitiveComparison() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put("age", 20); @@ -2068,8 +2139,9 @@ public void testMapPrimitiveComparison() { public static final int CONSTANT = 1; - @Test - public void testMapCheckForExistence() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapCheckForExistence(RUN_TYPE runType) { final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";" + @@ -2079,7 +2151,7 @@ public void testMapCheckForExistence() { " insert(new Result($p.getName()));\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map items = new HashMap<>(); items.put(CONSTANT, 2000); @@ -2098,8 +2170,9 @@ public void testMapCheckForExistence() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testBigDecimalIntCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalIntCoercion(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "rule \"rule1\"\n" + "when\n" + @@ -2107,7 +2180,7 @@ public void testBigDecimalIntCoercion() { "then\n" + "end\n"; - KieSession ksession1 = getKieSession(str); + KieSession ksession1 = getKieSession(runType, str); Result fact = new Result(); fact.setValue( new BigDecimal(10) ); @@ -2115,8 +2188,9 @@ public void testBigDecimalIntCoercion() { assertThat(ksession1.fireAllRules()).isEqualTo(1); } - @Test - public void testBooleanCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testBooleanCoercion(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -2125,7 +2199,7 @@ public void testBooleanCoercion() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person first = new Person("First", 40); first.setEmployed(true); @@ -2133,8 +2207,9 @@ public void testBooleanCoercion() { assertThat(ksession.fireAllRules()).isEqualTo(1);; } - @Test - public void testUseMatch() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseMatch(RUN_TYPE runType) { // DROOLS-4579 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -2144,15 +2219,16 @@ public void testUseMatch() { " if ($p != drools.getMatch().getObjects().get(0)) throw new RuntimeException();\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); ksession.insert( me ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMultilinePattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultilinePattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -2161,7 +2237,7 @@ public void testMultilinePattern() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person first = new Person("John", 40); first.setEmployed(true); @@ -2169,8 +2245,9 @@ public void testMultilinePattern() { assertThat(ksession.fireAllRules()).isEqualTo(1);; } - @Test - public void testAccumulateWithMax() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithMax(RUN_TYPE runType) { String str = "import " + StockTick.class.getCanonicalName() + ";" + "import " + StockTick.class.getCanonicalName() + ";" + @@ -2181,7 +2258,7 @@ public void testAccumulateWithMax() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StockTick st = new StockTick("RHT"); st.setTimeField(new Date().getTime()); @@ -2189,8 +2266,9 @@ public void testAccumulateWithMax() { assertThat(ksession.fireAllRules()).isEqualTo(1);; } - @Test() - public void testMultipleModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleModify(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -2201,7 +2279,7 @@ public void testMultipleModify() { " modify($p2) { setAge($p2.getAge()+5) }\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p1 = new Person( "John", 40 ); Person p2 = new Person( "Paul", 38 ); @@ -2214,8 +2292,9 @@ public void testMultipleModify() { assertThat(p2.getAge()).isEqualTo(43); } - @Test() - public void testMultipleModifyWithDifferentFacts() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleModifyWithDifferentFacts(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Pet.class.getCanonicalName() + ";" + @@ -2233,7 +2312,7 @@ public void testMultipleModifyWithDifferentFacts() { " modify($pet) { setAge($pet.getAge()+1) }\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person person = new Person( "John", 40 ); Pet pet = new Pet( Pet.PetType.dog, 3 ); @@ -2341,8 +2420,10 @@ public String getValue(Object o) { } } - @Test // DROOLS-5007 - public void testIntToShortCast() { + // DROOLS-5007 + @ParameterizedTest + @MethodSource("parameters") + public void testIntToShortCast(RUN_TYPE runType) { String str = "import " + Address.class.getCanonicalName() + ";\n" + "rule \"rule1\"\n" + "when\n" + @@ -2353,7 +2434,7 @@ public void testIntToShortCast() { " update($address);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Address address = new Address(); address.setNumber(1); @@ -2362,8 +2443,10 @@ public void testIntToShortCast() { } - @Test // DROOLS-5709 // DROOLS-5768 - public void testCastingIntegerToShort() { + // DROOLS-5709 // DROOLS-5768 + @ParameterizedTest + @MethodSource("parameters") + public void testCastingIntegerToShort(RUN_TYPE runType) { String str = "import " + IntegerToShort.class.getCanonicalName() + ";\n " + "rule \"test_rule\"\n" + @@ -2381,7 +2464,7 @@ public void testCastingIntegerToShort() { " update($integerToShort);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); IntegerToShort integerToShort = new IntegerToShort(false, Short.MAX_VALUE, (short)0, (double)0); ksession.insert(integerToShort); @@ -2391,8 +2474,10 @@ public void testCastingIntegerToShort() { assertThat(integerToShort).isEqualTo(new IntegerToShort(true, Short.MAX_VALUE, Short.MAX_VALUE, (double)0)); } - @Test // DROOLS-5998 - public void testCastingIntegerToShortWithNegativeNumbers() { + // DROOLS-5998 + @ParameterizedTest + @MethodSource("parameters") + public void testCastingIntegerToShortWithNegativeNumbers(RUN_TYPE runType) { String str = "import " + IntegerToShort.class.getCanonicalName() + ";\n " + "rule \"test_rule\"\n" + @@ -2409,7 +2494,7 @@ public void testCastingIntegerToShortWithNegativeNumbers() { " update($integerToShort);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); IntegerToShort integerToShort = new IntegerToShort(false, Short.MAX_VALUE, (short)0, (double)0); ksession.insert(integerToShort); @@ -2419,8 +2504,10 @@ public void testCastingIntegerToShortWithNegativeNumbers() { assertThat(integerToShort).isEqualTo(new IntegerToShort(true, Short.MAX_VALUE, (short)-12, (double)0)); } - @Test // RHDM-1644 // DROOLS-6196 - public void testCastingIntegerToShortWithDoubleVar() { + // RHDM-1644 // DROOLS-6196 + @ParameterizedTest + @MethodSource("parameters") + public void testCastingIntegerToShortWithDoubleVar(RUN_TYPE runType) { String str = "import " + IntegerToShort.class.getCanonicalName() + ";\n " + "rule \"test_rule\"\n" + @@ -2438,7 +2525,7 @@ public void testCastingIntegerToShortWithDoubleVar() { " update($integerToShort);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); IntegerToShort integerToShort = new IntegerToShort(false, Short.MAX_VALUE, (short)0, (double)1); ksession.insert(integerToShort); @@ -2448,8 +2535,10 @@ public void testCastingIntegerToShortWithDoubleVar() { assertThat(integerToShort).isEqualTo(new IntegerToShort(true, Short.MAX_VALUE, (short)17, (double)1)); } - @Test // RHDM-1644 // DROOLS-6196 - public void testUseOfVarCreatedAsInputArgInGlobalFuntionAsA_Var() { + // RHDM-1644 // DROOLS-6196 + @ParameterizedTest + @MethodSource("parameters") + public void testUseOfVarCreatedAsInputArgInGlobalFuntionAsA_Var(RUN_TYPE runType) { String str = "import " + IntegerToShort.class.getCanonicalName() + ";\n " + "global " + GlobalFunctions.class.getCanonicalName() + " functions;\n " + @@ -2468,7 +2557,7 @@ public void testUseOfVarCreatedAsInputArgInGlobalFuntionAsA_Var() { " update($integerToShort);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); IntegerToShort integerToShort = new IntegerToShort(false, Short.MAX_VALUE, (short)0); ksession.insert(integerToShort); @@ -2479,8 +2568,9 @@ public void testUseOfVarCreatedAsInputArgInGlobalFuntionAsA_Var() { assertThat(integerToShort).isEqualTo(new IntegerToShort(true, 1, (short)0)); } - @Test - public void testConsequenceGetContext() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceGetContext(RUN_TYPE runType) throws Exception { String str = "import " + ProcessContext.class.getCanonicalName() + ";" + "rule R when\n" + @@ -2489,12 +2579,14 @@ public void testConsequenceGetContext() throws Exception { " ProcessContext clazz = drools.getContext(ProcessContext.class);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession).isNotNull(); } - @Test // DROOLS-6034 - public void testConsequenceInsertThenUpdate() throws Exception { + // DROOLS-6034 + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceInsertThenUpdate(RUN_TYPE runType) throws Exception { String str = "global java.util.List children;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -2508,7 +2600,7 @@ public void testConsequenceInsertThenUpdate() throws Exception { " children.add(andrea.getName());\n" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); ArrayList children = new ArrayList<>(); kSession.setGlobal("children", children); @@ -2521,8 +2613,10 @@ public void testConsequenceInsertThenUpdate() throws Exception { assertThat(children).containsOnly("Andrea"); } - @Test // DROOLS-6034 - public void testConsequenceInsertThenModify() throws Exception { + // DROOLS-6034 + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceInsertThenModify(RUN_TYPE runType) throws Exception { String str = "global java.util.List children;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -2538,7 +2632,7 @@ public void testConsequenceInsertThenModify() throws Exception { " children.add(andrea.getName());\n" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); ArrayList children = new ArrayList<>(); kSession.setGlobal("children", children); @@ -2551,8 +2645,10 @@ public void testConsequenceInsertThenModify() throws Exception { assertThat(children).containsOnly("Andrea"); } - @Test // DROOLS-6034 - public void testConsequenceInsertThenUpdateWithPatternInitializer() throws Exception { + // DROOLS-6034 + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceInsertThenUpdateWithPatternInitializer(RUN_TYPE runType) throws Exception { String str = "global java.util.List result;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -2569,7 +2665,7 @@ public void testConsequenceInsertThenUpdateWithPatternInitializer() throws Excep " result.add(fromNameExprTwice.getName());\n" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); ArrayList children = new ArrayList<>(); kSession.setGlobal("result", children); @@ -2582,8 +2678,9 @@ public void testConsequenceInsertThenUpdateWithPatternInitializer() throws Excep assertThat(children).containsOnly("Luca"); } - @Test - public void testExtraParenthes() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExtraParenthes(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -2591,7 +2688,7 @@ public void testExtraParenthes() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person person = new Person( "John", 20 ); @@ -2599,8 +2696,9 @@ public void testExtraParenthes() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testNegateBigDecimal() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateBigDecimal(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -2610,7 +2708,7 @@ public void testNegateBigDecimal() throws Exception { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -2626,8 +2724,9 @@ public void testNegateBigDecimal() throws Exception { assertThat(list).containsExactly("John"); } - @Test - public void testNegateJoin() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateJoin(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -2637,7 +2736,7 @@ public void testNegateJoin() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Address a = new Address("Milan"); Person p = new Person("Toshiya"); @@ -2649,8 +2748,9 @@ public void testNegateJoin() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNegateComplex() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateComplex(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -2660,7 +2760,7 @@ public void testNegateComplex() throws Exception { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -2679,8 +2779,9 @@ public void testNegateComplex() throws Exception { assertThat(list).containsExactlyInAnyOrder("John", "George"); } - @Test - public void testMapStringProp() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMapStringProp(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -2689,7 +2790,7 @@ public void testMapStringProp() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final Person p = new Person("Toshiya"); p.getItemsString().put("AAA", "XXX"); @@ -2698,8 +2799,9 @@ public void testMapStringProp() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapString() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMapString(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Map.class.getCanonicalName() + ";\n" + @@ -2708,7 +2810,7 @@ public void testMapString() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Map map = new HashMap<>(); map.put("AAA", "XXX"); @@ -2717,8 +2819,9 @@ public void testMapString() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testHashSet() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testHashSet(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + HashSet.class.getCanonicalName() + ";\n" + @@ -2739,7 +2842,7 @@ public void testHashSet() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); FactType appType = ksession.getKieBase().getFactType("org.drools.test", "Application"); Object appObj = appType.newInstance(); @@ -2750,8 +2853,9 @@ public void testHashSet() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test() - public void testRhsOrderWithModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testRhsOrderWithModify(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -2769,7 +2873,7 @@ public void testRhsOrderWithModify() { " list.add($p2.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -2783,8 +2887,9 @@ public void testRhsOrderWithModify() { assertThat(list).containsExactlyInAnyOrder(40, 38, 41, 38, 41, 43); } - @Test() - public void testStringRelationalComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringRelationalComparison(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -2794,7 +2899,7 @@ public void testStringRelationalComparison() { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -2805,11 +2910,9 @@ public void testStringRelationalComparison() { assertThat(list).containsExactly("John"); } - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); - - @Test - public void testNPEOnConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testNPEOnConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -2817,7 +2920,7 @@ public void testNPEOnConstraint() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Luca"); me.setMoney(null); @@ -2826,8 +2929,9 @@ public void testNPEOnConstraint() { .isThrownBy(() -> ksession.fireAllRules()) .withMessage("Error evaluating constraint 'money < salary * 20' in [Rule \"R\" in r0.drl]"); } - @Test - public void testSharedPredicateInformation() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedPredicateInformation(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -2839,7 +2943,7 @@ public void testSharedPredicateInformation() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person me = new Person("Luca"); me.setSalary(null); @@ -2851,8 +2955,9 @@ public void testSharedPredicateInformation() { .withMessage("Error evaluating constraint 'money < salary * 20' in [Rule \"R1\", \"R2\" in r0.drl]"); } - @Test - public void testSharedPredicateInformationWithNonSharedRule() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedPredicateInformationWithNonSharedRule(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + @@ -2869,7 +2974,7 @@ public void testSharedPredicateInformationWithNonSharedRule() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person me = new Person("Luca"); me.setSalary(null); @@ -2882,8 +2987,9 @@ public void testSharedPredicateInformationWithNonSharedRule() { } - @Test - public void testSharedPredicateInformationWithMultipleFiles() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedPredicateInformationWithMultipleFiles(RUN_TYPE runType) { String str1 = "import " + Person.class.getCanonicalName() + ";" + @@ -2906,7 +3012,7 @@ public void testSharedPredicateInformationWithMultipleFiles() { "then\n" + "end"; - KieSession ksession = getKieSession(str1, str2); + KieSession ksession = getKieSession(runType, str1, str2); Person me = new Person("Luca"); me.setSalary(null); @@ -2919,8 +3025,9 @@ public void testSharedPredicateInformationWithMultipleFiles() { } - @Test - public void testSharedBetaPredicateInformationWithMultipleFiles() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedBetaPredicateInformationWithMultipleFiles(RUN_TYPE runType) { String str1 = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -2946,7 +3053,7 @@ public void testSharedBetaPredicateInformationWithMultipleFiles() { "then\n" + "end"; - KieSession ksession = getKieSession(str1, str2); + KieSession ksession = getKieSession(runType, str1, str2); Person me = new Person("Luca"); me.setSalary(null); @@ -2959,8 +3066,9 @@ public void testSharedBetaPredicateInformationWithMultipleFiles() { .withMessage("Error evaluating constraint '$i < salary * 20' in [Rule \"R1\", \"R2\" in r0.drl] [Rule \"R3\", \"R4\" in r1.drl]"); } - @Test - public void testSharedPredicateInformationExceedMaxRuleDefs() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedPredicateInformationExceedMaxRuleDefs(RUN_TYPE runType) { // shared by 11 rules String str1 = "import " + Person.class.getCanonicalName() + ";" + @@ -3024,7 +3132,7 @@ public void testSharedPredicateInformationExceedMaxRuleDefs() { "then\n" + "end"; - KieSession ksession = getKieSession(str1, str2, str3); + KieSession ksession = getKieSession(runType, str1, str2, str3); Person me = new Person("Luca"); me.setSalary(null); @@ -3039,8 +3147,9 @@ public void testSharedPredicateInformationExceedMaxRuleDefs() { } - @Test - public void testWithQuotedStringConcatenationOnConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testWithQuotedStringConcatenationOnConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -3048,7 +3157,7 @@ public void testWithQuotedStringConcatenationOnConstraint() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Luca II"); me.setMoney(null); @@ -3057,8 +3166,9 @@ public void testWithQuotedStringConcatenationOnConstraint() { assertThat(rulesFired).isEqualTo(1); } - @Test - public void testNegatedConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testNegatedConstraint(RUN_TYPE runType) { // DROOLS-5791 String str = "rule R when\n" + @@ -3067,15 +3177,16 @@ public void testNegatedConstraint() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 5 ); ksession.insert( "test" ); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testMethodCallWithClass() { + @ParameterizedTest + @MethodSource("parameters") + public void testMethodCallWithClass(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "import " + FactWithMethod.class.getCanonicalName() + ";" + "rule r1\n" + @@ -3084,7 +3195,7 @@ public void testMethodCallWithClass() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final FactWithMethod fact = new FactWithMethod(); ksession.insert(fact); final int rules = ksession.fireAllRules(); @@ -3108,8 +3219,9 @@ default String getDefaultString() { public static class MyClass implements MyInterface { } - @Test - public void testUseDefaultMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseDefaultMethod(RUN_TYPE runType) { // DROOLS-6358 final String str = "package org.drools.mvel.compiler\n" + @@ -3122,7 +3234,7 @@ public void testUseDefaultMethod() { " list.add(val);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -3133,8 +3245,9 @@ public void testUseDefaultMethod() { assertThat(list.get(0)).isEqualTo("DEFAULT"); } - @Test - public void testSharedConstraintWithExtraParenthesis() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedConstraintWithExtraParenthesis(RUN_TYPE runType) { // DROOLS-6548 final String str = "package org.drools.mvel.compiler\n" + @@ -3152,7 +3265,7 @@ public void testSharedConstraintWithExtraParenthesis() { " list.add(\"r2\");" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -3162,8 +3275,9 @@ public void testSharedConstraintWithExtraParenthesis() { assertThat(list.get(0)).isEqualTo("r1"); } - @Test - public void orWithMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void orWithMethodCall(RUN_TYPE runType) { final String str = "package org.example\n" + "import " + MyFact.class.getCanonicalName() + ";" + @@ -3172,15 +3286,16 @@ public void orWithMethodCall() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new MyFact(5)); int fired = ksession.fireAllRules(); assertThat(fired).isEqualTo(1); } - @Test - public void orWithMethodCallWithArg() { + @ParameterizedTest + @MethodSource("parameters") + public void orWithMethodCallWithArg(RUN_TYPE runType) { final String str = "package org.example\n" + "import " + MyFact.class.getCanonicalName() + ";" + @@ -3189,7 +3304,7 @@ public void orWithMethodCallWithArg() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new MyFact(5)); int fired = ksession.fireAllRules(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ComplexRulesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ComplexRulesTest.java index 7853acecf99..adce0b0f321 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ComplexRulesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ComplexRulesTest.java @@ -20,7 +20,6 @@ import java.time.LocalDateTime; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -41,19 +40,17 @@ import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.RootFact; import org.drools.model.codegen.execmodel.domain.SubFact; -import org.junit.Test; +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; public class ComplexRulesTest extends BaseModelTest { - public ComplexRulesTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void test1() { + @ParameterizedTest + @MethodSource("parameters") + public void test1(RUN_TYPE runType) { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + EnumFact2.class.getCanonicalName() + ";\n" + @@ -100,11 +97,12 @@ public void test1() { " list.add($result);\n" + "end\n"; - testComplexRule(str); + testComplexRule(runType, str); } - @Test - public void testNotWithEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotWithEval(RUN_TYPE runType) { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + EnumFact2.class.getCanonicalName() + ";\n" + @@ -151,11 +149,11 @@ public void testNotWithEval() { " list.add($result);\n" + "end\n"; - testComplexRule(str); + testComplexRule(runType, str); } - private void testComplexRule(final String rule) { - KieSession ksession = getKieSession( rule ); + private void testComplexRule(RUN_TYPE runType, String rule) { + KieSession ksession = getKieSession(runType, rule); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -176,8 +174,9 @@ private void testComplexRule(final String rule) { assertThat((int) list.get(0)).isEqualTo(1); } - @Test - public void test2() { + @ParameterizedTest + @MethodSource("parameters") + public void test2(RUN_TYPE runType) { final String drl = " import org.drools.model.codegen.execmodel.domain.*;\n" + " rule \"R1\"\n" + @@ -200,7 +199,7 @@ public void test2() { " update($childFact4);\n" + " end\n"; - KieSession ksession = getKieSession( drl ); + KieSession ksession = getKieSession(runType, drl ); int initialId = 1; final RootFact rootFact = new RootFact(initialId); @@ -220,8 +219,9 @@ public void test2() { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void test3() { + @ParameterizedTest + @MethodSource("parameters") + public void test3(RUN_TYPE runType) { String str = "import " + RootFact.class.getCanonicalName() + ";\n" + "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + @@ -243,7 +243,7 @@ public void test3() { " list.add($result);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -258,8 +258,9 @@ public void test3() { assertThat((int) list.get(0)).isEqualTo(1); } - @Test - public void test4() { + @ParameterizedTest + @MethodSource("parameters") + public void test4(RUN_TYPE runType) { String str = "import " + RootFact.class.getCanonicalName() + ";\n" + "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + @@ -280,7 +281,7 @@ public void test4() { " list.add($result);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -294,8 +295,9 @@ public void test4() { assertThat((int) list.get(0)).isEqualTo(1); } - @Test - public void testEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testEnum(RUN_TYPE runType) { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + @@ -305,13 +307,14 @@ public void testEnum() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithEnum1(1, 3, EnumFact1.FIRST) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNotInEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotInEnum(RUN_TYPE runType) { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + @@ -321,13 +324,14 @@ public void testNotInEnum() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithEnum1(1, 3, EnumFact1.SECOND) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNotInInterfaceAsEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotInInterfaceAsEnum(RUN_TYPE runType) { String str = "import " + InterfaceAsEnum.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + @@ -337,13 +341,14 @@ public void testNotInInterfaceAsEnum() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithEnum1(1, 3, EnumFact1.SECOND) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testConstraintWithFunctionUsingThis() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintWithFunctionUsingThis(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -356,14 +361,15 @@ public void testConstraintWithFunctionUsingThis() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testConstraintWithTernaryOperator() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintWithTernaryOperator(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -377,15 +383,16 @@ public void testConstraintWithTernaryOperator() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( "test" ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCastInConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testCastInConstraint(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -395,14 +402,15 @@ public void testCastInConstraint() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testConstraintWithFunctionAndStringConcatenation() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintWithFunctionAndStringConcatenation(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -416,14 +424,15 @@ public void testConstraintWithFunctionAndStringConcatenation() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEvalWithFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithFunction(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -437,14 +446,15 @@ public void testEvalWithFunction() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEqualOnShortField() { + @ParameterizedTest + @MethodSource("parameters") + public void testEqualOnShortField(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -453,13 +463,14 @@ public void testEqualOnShortField() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGreaterOnShortField() { + @ParameterizedTest + @MethodSource("parameters") + public void testGreaterOnShortField(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -468,13 +479,14 @@ public void testGreaterOnShortField() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBooleanField() { + @ParameterizedTest + @MethodSource("parameters") + public void testBooleanField(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -483,13 +495,14 @@ public void testBooleanField() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testConsequenceThrowingException() { + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceThrowingException(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -501,14 +514,15 @@ public void testConsequenceThrowingException() { " functions.doSomethingRisky($c);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCompareDate() { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareDate(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -518,14 +532,15 @@ public void testCompareDate() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); ksession.insert( new ChildFactWithObject(6, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCompareDateWithString() { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareDateWithString(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -534,13 +549,14 @@ public void testCompareDateWithString() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void test2UpperCaseProp() { + @ParameterizedTest + @MethodSource("parameters") + public void test2UpperCaseProp(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -550,7 +566,7 @@ public void test2UpperCaseProp() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } @@ -571,8 +587,9 @@ public List getList() { } } - @Test - public void testNameClashBetweenAttributeAndGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void testNameClashBetweenAttributeAndGlobal(RUN_TYPE runType) { String str = "import " + ListContainer.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -582,7 +599,7 @@ public void testNameClashBetweenAttributeAndGlobal() { " list.add($l);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList(); ksession.setGlobal( "list", list ); @@ -598,8 +615,9 @@ public char[] getCharArray() { } } - @Test - public void testPrimitiveArray() { + @ParameterizedTest + @MethodSource("parameters") + public void testPrimitiveArray(RUN_TYPE runType) { String str = "import " + Primitives.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -609,7 +627,7 @@ public void testPrimitiveArray() { " list.add($c);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList(); ksession.setGlobal( "list", list ); @@ -619,8 +637,9 @@ public void testPrimitiveArray() { assertThat(list.size()).isEqualTo(1); } - @Test - public void testUseConstructorInConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseConstructorInConstraint(RUN_TYPE runType) { // DROOLS-2990 String str = "rule R when\n" + @@ -629,15 +648,16 @@ public void testUseConstructorInConstraint() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( (short) 1 ); ksession.insert( 2.0 ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testManyPropFactWithNot() { + @ParameterizedTest + @MethodSource("parameters") + public void testManyPropFactWithNot(RUN_TYPE runType) { // DROOLS-4572 try { System.setProperty("drools.propertySpecific", "ALLOWED"); @@ -660,7 +680,7 @@ public void testManyPropFactWithNot() { " update($subFact);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ManyPropFact fact = new ManyPropFact(); fact.setId(1); @@ -698,8 +718,9 @@ public CaseData getMe() { } } - @Test - public void testGetOnMapField() { + @ParameterizedTest + @MethodSource("parameters") + public void testGetOnMapField(RUN_TYPE runType) { // DROOLS-4999 String str = "import " + CaseData.class.getCanonicalName() + ";\n" + @@ -708,15 +729,16 @@ public void testGetOnMapField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new CaseData( 5 ) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEqualsOnMapField() { + @ParameterizedTest + @MethodSource("parameters") + public void testEqualsOnMapField(RUN_TYPE runType) { // DROOLS-4999 String str = "import " + CaseData.class.getCanonicalName() + ";\n" + @@ -725,15 +747,16 @@ public void testEqualsOnMapField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new CaseData( "OK" ) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testDoubleNegation() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoubleNegation(RUN_TYPE runType) { // DROOLS-5545 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -742,13 +765,14 @@ public void testDoubleNegation() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 45 ) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGlobalAsFunctionArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalAsFunctionArgument(RUN_TYPE runType) { // DROOLS-5999 String str = "import java.util.*;\n"+ @@ -773,7 +797,7 @@ public void testGlobalAsFunctionArgument() { " result.add(Integer.valueOf(42));\n"+ "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConditionalExprTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConditionalExprTest.java index a8d5908248c..5b08b24674c 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConditionalExprTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConditionalExprTest.java @@ -22,8 +22,10 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +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; @@ -47,41 +49,40 @@ public class ConditionalExprTest extends BaseModelTest { private KieSession ksession; private List booleanListGlobal; - public ConditionalExprTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Before + @BeforeEach public void setup() { - ksession = getKieSession(RULE_STRING); booleanListGlobal = new ArrayList<>(); - ksession.setGlobal("booleanListGlobal", booleanListGlobal); + } + + @AfterEach + public void tearDown() { + if (ksession != null) { + ksession.dispose(); + } } - @Test - public void testConditionalExpressionWithNamedPerson() { - try { - Person person = new Person("someName"); - ksession.insert(person); - int rulesFired = ksession.fireAllRules(); - assertThat(rulesFired).isEqualTo(1); - assertThat(booleanListGlobal).isNotEmpty().containsExactly(Boolean.TRUE); - } finally { - ksession.dispose(); - } + @ParameterizedTest + @MethodSource("parameters") + public void testConditionalExpressionWithNamedPerson(RUN_TYPE runType) { + ksession = getKieSession(runType, RULE_STRING); + ksession.setGlobal("booleanListGlobal", booleanListGlobal); + Person person = new Person("someName"); + ksession.insert(person); + int rulesFired = ksession.fireAllRules(); + assertThat(rulesFired).isEqualTo(1); + assertThat(booleanListGlobal).isNotEmpty().containsExactly(Boolean.TRUE); } - @Test - public void testConditionalExpressionWithUnnamedPerson() { - try { - Person person = new Person(); - ksession.insert(person); - int rulesFired = ksession.fireAllRules(); - assertThat(rulesFired).isEqualTo(1); - assertThat(booleanListGlobal).isNotEmpty().containsExactly(Boolean.FALSE); - } finally { - ksession.dispose(); - } + @ParameterizedTest + @MethodSource("parameters") + public void testConditionalExpressionWithUnnamedPerson(RUN_TYPE runType) { + ksession = getKieSession(runType, RULE_STRING); + ksession.setGlobal("booleanListGlobal", booleanListGlobal); + Person person = new Person(); + ksession.insert(person); + int rulesFired = ksession.fireAllRules(); + assertThat(rulesFired).isEqualTo(1); + assertThat(booleanListGlobal).isNotEmpty().containsExactly(Boolean.FALSE); } } \ No newline at end of file diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintNormalizationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintNormalizationTest.java index 939722b9bee..058242c8cc5 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintNormalizationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintNormalizationTest.java @@ -32,7 +32,8 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Toy; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; @@ -40,12 +41,9 @@ public class ConstraintNormalizationTest extends BaseModelTest { - public ConstraintNormalizationTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testNormalizationForPropertyReactivity() { + @ParameterizedTest + @MethodSource("parameters") + public void testNormalizationForPropertyReactivity(RUN_TYPE runType) { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -62,7 +60,7 @@ public void testNormalizationForPropertyReactivity() { "then\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final Toy t = new Toy("Ball"); t.setOwner("Toshiya"); @@ -72,8 +70,9 @@ public void testNormalizationForPropertyReactivity() { assertThat(ksession.fireAllRules(10)).isEqualTo(2); // no infinite loop } - @Test - public void testNormalizationForPropertyReactivity2() { + @ParameterizedTest + @MethodSource("parameters") + public void testNormalizationForPropertyReactivity2(RUN_TYPE runType) { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -89,7 +88,7 @@ public void testNormalizationForPropertyReactivity2() { "then\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final Person p = new Person("Toshiya", 45); ksession.insert(new Integer(30)); @@ -97,8 +96,9 @@ public void testNormalizationForPropertyReactivity2() { assertThat(ksession.fireAllRules(10)).isEqualTo(2); // no infinite loop } - @Test - public void testNormalizationForAlphaIndexing() { + @ParameterizedTest + @MethodSource("parameters") + public void testNormalizationForAlphaIndexing(RUN_TYPE runType) { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -115,7 +115,7 @@ public void testNormalizationForAlphaIndexing() { "then\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = ((NamedEntryPoint) ksession.getEntryPoint("DEFAULT")).getEntryPointNode().getObjectTypeNodes().entrySet() .stream() @@ -134,8 +134,9 @@ public void testNormalizationForAlphaIndexing() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNormalizationForNodeSharing() { + @ParameterizedTest + @MethodSource("parameters") + public void testNormalizationForNodeSharing(RUN_TYPE runType) { final String str = "package org.drools.test;\n" + @@ -149,7 +150,7 @@ public void testNormalizationForNodeSharing() { "then\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -158,8 +159,9 @@ public void testNormalizationForNodeSharing() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testOperators() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testOperators(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + @@ -176,7 +178,7 @@ public void testOperators() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(4); @@ -189,8 +191,9 @@ public void testOperators() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testNestedProperty() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedProperty(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -204,7 +207,7 @@ public void testNestedProperty() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -216,8 +219,9 @@ public void testNestedProperty() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testComplexMethod() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexMethod(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -232,7 +236,7 @@ public void testComplexMethod() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -244,8 +248,9 @@ public void testComplexMethod() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testPropsOnBothSide() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPropsOnBothSide(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -259,7 +264,7 @@ public void testPropsOnBothSide() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -271,8 +276,9 @@ public void testPropsOnBothSide() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testExtraParentheses() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExtraParentheses(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -286,7 +292,7 @@ public void testExtraParentheses() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -297,8 +303,9 @@ public void testExtraParentheses() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testAnd() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAnd(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -312,10 +319,10 @@ public void testAnd() throws Exception { "then\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly - if (testRunType == RUN_TYPE.STANDARD_FROM_DRL || testRunType == RUN_TYPE.STANDARD_WITH_ALPHA_NETWORK) { + if (runType == RUN_TYPE.STANDARD_FROM_DRL || runType == RUN_TYPE.STANDARD_WITH_ALPHA_NETWORK) { assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(2); } else { // && is not split in case of executable-model @@ -329,8 +336,9 @@ public void testAnd() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testOr() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testOr(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -344,7 +352,7 @@ public void testOr() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -356,8 +364,9 @@ public void testOr() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testNegate() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegate(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -371,7 +380,7 @@ public void testNegate() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -382,8 +391,9 @@ public void testNegate() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testBigDecimal() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimal(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -396,7 +406,7 @@ public void testBigDecimal() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -409,8 +419,9 @@ public void testBigDecimal() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testNegateComplex() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateComplex(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -426,7 +437,7 @@ public void testNegateComplex() throws Exception { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -449,8 +460,9 @@ public void testNegateComplex() throws Exception { assertThat(list).containsExactlyInAnyOrder("John", "George", "John", "George"); } - @Test - public void testNegateComplex2() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateComplex2(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -466,7 +478,7 @@ public void testNegateComplex2() throws Exception { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -489,8 +501,9 @@ public void testNegateComplex2() throws Exception { assertThat(list).containsExactlyInAnyOrder("John", "George", "John", "George"); } - @Test - public void testDeclaredType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredType(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "declare Person\n" + @@ -507,7 +520,7 @@ public void testDeclaredType() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(2); @@ -520,8 +533,9 @@ public void testDeclaredType() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testMapProp() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMapProp(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -535,7 +549,7 @@ public void testMapProp() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -547,8 +561,9 @@ public void testMapProp() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testMapStringProp() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMapStringProp(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -562,7 +577,7 @@ public void testMapStringProp() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -574,8 +589,9 @@ public void testMapStringProp() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testMapStringThis() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMapStringThis(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Map.class.getCanonicalName() + ";\n" + @@ -589,7 +605,7 @@ public void testMapStringThis() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java index b3475e58c2d..5eced33ee03 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java @@ -23,8 +23,10 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +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; @@ -50,41 +52,40 @@ public class ConstraintTest extends BaseModelTest { private List bigDecimalListGlobal; - public ConstraintTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Before + @BeforeEach public void setup() { - ksession = getKieSession(RULE_STRING); bigDecimalListGlobal = new ArrayList<>(); - ksession.setGlobal("bigDecimalListGlobal", bigDecimalListGlobal); + } + + @AfterEach + public void tearDown() { + if (ksession != null) { + ksession.dispose(); + } } - @Test - public void testConstraintWithMoney() { - try { - BigDecimal money = BigDecimal.valueOf(34.45); - Person person = new Person("", money); - ksession.insert(person); - int rulesFired = ksession.fireAllRules(); - assertThat(rulesFired).isEqualTo(1); - assertThat(bigDecimalListGlobal).isNotEmpty().containsExactly(money); - } finally { - ksession.dispose(); - } + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintWithMoney(RUN_TYPE runType) { + ksession = getKieSession(runType, RULE_STRING); + ksession.setGlobal("bigDecimalListGlobal", bigDecimalListGlobal); + BigDecimal money = BigDecimal.valueOf(34.45); + Person person = new Person("", money); + ksession.insert(person); + int rulesFired = ksession.fireAllRules(); + assertThat(rulesFired).isEqualTo(1); + assertThat(bigDecimalListGlobal).isNotEmpty().containsExactly(money); } - @Test - public void testConstraintWithoutMoney() { - try { - Person person = new Person(); - ksession.insert(person); - int rulesFired = ksession.fireAllRules(); - assertThat(rulesFired).isEqualTo(1); - assertThat(bigDecimalListGlobal).isNotEmpty().containsExactly(BigDecimal.valueOf(100.0)); - } finally { - ksession.dispose(); - } + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintWithoutMoney(RUN_TYPE runType) { + ksession = getKieSession(runType, RULE_STRING); + ksession.setGlobal("bigDecimalListGlobal", bigDecimalListGlobal); + Person person = new Person(); + ksession.insert(person); + int rulesFired = ksession.fireAllRules(); + assertThat(rulesFired).isEqualTo(1); + assertThat(bigDecimalListGlobal).isNotEmpty().containsExactly(BigDecimal.valueOf(100.0)); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CustomConstraintOperatorTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CustomConstraintOperatorTest.java index d1b5c6f7768..4a5ad46f851 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CustomConstraintOperatorTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CustomConstraintOperatorTest.java @@ -37,7 +37,7 @@ import org.drools.model.prototype.PrototypeVariable; import org.drools.modelcompiler.KieBaseBuilder; import org.drools.modelcompiler.constraints.LambdaConstraint; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.prototype.PrototypeFact; import org.kie.api.prototype.PrototypeFactInstance; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypeDifferentKJarIncludesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypeDifferentKJarIncludesTest.java index a51146f0c5b..26d837003a5 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypeDifferentKJarIncludesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypeDifferentKJarIncludesTest.java @@ -20,8 +20,9 @@ import org.drools.compiler.kie.builder.impl.DrlProject; import org.drools.model.codegen.ExecutableModelProject; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.drools.io.ByteArrayResource; -import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; @@ -49,9 +50,6 @@ public class DeclaredTypeDifferentKJarIncludesTest extends BaseModelTest { private final String SUPER_KBASE_PACKAGE = "org.superkbase"; private final ReleaseIdImpl SUPER_RELEASE_ID = new ReleaseIdImpl(SUPER_KBASE_PACKAGE, "superkbase", "1.0.0"); - public DeclaredTypeDifferentKJarIncludesTest(RUN_TYPE testRunType) { - super(testRunType); - } private static final String SUPER_RULE = "package org.superkbase;\n" + "\n" + @@ -80,9 +78,10 @@ public DeclaredTypeDifferentKJarIncludesTest(RUN_TYPE testRunType) { " delete($s);\n" + "end\n"; - @Test - public void testChildIncludingSuper() { - KieBase kBase = createKieBase(); + @ParameterizedTest + @MethodSource("parameters") + public void testChildIncludingSuper(RUN_TYPE runType) { + KieBase kBase = createKieBase(runType); KieSession newSuperKieBase = kBase.newKieSession(); newSuperKieBase.insert(10); @@ -92,16 +91,16 @@ public void testChildIncludingSuper() { assertThat(newSuperKieBase.getObjects().size()).isEqualTo(0); } - private KieBase createKieBase() { + private KieBase createKieBase(RUN_TYPE runType) { KieServices kieServices = KieServices.Factory.get(); - superKieBase(kieServices); - childKieBase(kieServices); + superKieBase(kieServices, runType); + childKieBase(kieServices, runType); return kieServices.newKieContainer(CHILD_RELEASE_ID).getKieBase(CHILD_KBASE_NAME); } - private void superKieBase(KieServices kieServices) { + private void superKieBase(KieServices kieServices, RUN_TYPE runType) { KieModuleModel superKModule = kieServices.newKieModuleModel(); KieBaseModel superKieBase = superKModule.newKieBaseModel(SUPER_KBASE_NAME); @@ -116,10 +115,10 @@ private void superKieBase(KieServices kieServices) { superFileSystem.writeKModuleXML(superKModule.toXML()); superFileSystem.write("pom.xml", generatePomXmlWithDependencies(SUPER_RELEASE_ID)); - kieServices.newKieBuilder(superFileSystem).buildAll(buildProjectClass()); + kieServices.newKieBuilder(superFileSystem).buildAll(buildProjectClass(runType)); } - private void childKieBase(KieServices kieServices) { + private void childKieBase(KieServices kieServices, RUN_TYPE runType) { KieModuleModel childKModule = kieServices.newKieModuleModel(); KieBaseModel childKbase = childKModule.newKieBaseModel(CHILD_KBASE_NAME) .setDefault(true) @@ -135,7 +134,7 @@ private void childKieBase(KieServices kieServices) { childFileSystem.writeKModuleXML(childKModule.toXML()); childFileSystem.write("pom.xml", generatePomXmlWithDependencies(CHILD_RELEASE_ID, SUPER_RELEASE_ID)); - kieServices.newKieBuilder(childFileSystem).buildAll(buildProjectClass()); + kieServices.newKieBuilder(childFileSystem).buildAll(buildProjectClass(runType)); } private static String generatePomXmlWithDependencies(ReleaseId releaseId, ReleaseId... dependencies) { @@ -176,8 +175,8 @@ private static void toGAV(ReleaseId releaseId, StringBuilder sBuilder) { sBuilder.append(" \n"); } - private Class buildProjectClass() { - if (asList(PATTERN_DSL, PATTERN_WITH_ALPHA_NETWORK).contains(testRunType)) { + private Class buildProjectClass(RUN_TYPE runType) { + if (asList(PATTERN_DSL, PATTERN_WITH_ALPHA_NETWORK).contains(runType)) { return ExecutableModelProject.class; } else { return DrlProject.class; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypesTest.java index 664ae7534ed..a6d4ba52f95 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypesTest.java @@ -35,7 +35,8 @@ import org.drools.base.rule.constraint.AlphaNodeFieldConstraint; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; @@ -44,12 +45,9 @@ public class DeclaredTypesTest extends BaseModelTest { - public DeclaredTypesTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testPojo() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPojo(RUN_TYPE runType) throws Exception { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -67,7 +65,7 @@ public void testPojo() throws Exception { " insert(new Result(p));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.insert(new Person("Mark", 37)); @@ -98,8 +96,9 @@ public void testPojo() throws Exception { assertThat(luca.toString()).isEqualTo("POJOPerson( name=Luca, surname=null, age=32 )"); } - @Test - public void testPojoInDifferentPackages() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPojoInDifferentPackages(RUN_TYPE runType) throws Exception { String ruleWithPojo = "package org.drools.pojo.model;" + "\n" + @@ -128,7 +127,7 @@ public void testPojoInDifferentPackages() throws Exception { " insert(new Result($p));\n" + "end\n"; - KieSession ksession = getKieSession(rule, ruleWithPojo); + KieSession ksession = getKieSession(runType, rule, ruleWithPojo); ksession.insert(new Person("Mario", 40)); ksession.insert(new Person("Mark", 37)); @@ -159,8 +158,9 @@ public void testPojoInDifferentPackages() throws Exception { assertThat(luca.toString()).isEqualTo("POJOPerson( name=Luca, surname=null, age=32 )"); } - @Test - public void testPojoReferencingEachOthers() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPojoReferencingEachOthers(RUN_TYPE runType) throws Exception { String factA = "package org.kie.test;" + "\n" + @@ -183,13 +183,14 @@ public void testPojoReferencingEachOthers() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(rule, factA, factB); + KieSession ksession = getKieSession(runType, rule, factA, factB); ksession.fireAllRules(); } - @Test - public void testDeclaredTypeInLhs() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredTypeInLhs(RUN_TYPE runType) throws Exception { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -212,7 +213,7 @@ public void testDeclaredTypeInLhs() throws Exception { " insert(new Result($p));\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.insert(new Person("Mark", 37)); @@ -265,8 +266,9 @@ public String toString() { } } - @Test - public void testPojoPredicateIsUsedAsConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testPojoPredicateIsUsedAsConstraint(RUN_TYPE runType) { String str = "import " + MyNumber.class.getCanonicalName() + ";" + "rule R when\n" + " MyNumber(even, $value : value)" + @@ -274,7 +276,7 @@ public void testPojoPredicateIsUsedAsConstraint() { " insert($value);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new MyNumber(2)); ksession.fireAllRules(); @@ -290,8 +292,9 @@ public void testPojoPredicateIsUsedAsConstraint() { assertThat(results.contains(1)).isFalse(); // This is because MyNumber(1) would fail for "even" predicate/getter used here in pattern as a constraint. } - @Test - public void testPojoPredicateIsUsedAsConstraintOK() { + @ParameterizedTest + @MethodSource("parameters") + public void testPojoPredicateIsUsedAsConstraintOK(RUN_TYPE runType) { String str = "import " + MyNumber.class.getCanonicalName() + ";" + "rule R when\n" + " $n : MyNumber(even, $value : value)" + @@ -299,7 +302,7 @@ public void testPojoPredicateIsUsedAsConstraintOK() { " insert($value);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new MyNumber(2)); ksession.fireAllRules(); @@ -315,8 +318,9 @@ public void testPojoPredicateIsUsedAsConstraintOK() { assertThat(results.contains(1)).isFalse(); // This is because MyNumber(1) would fail for "even" predicate/getter used here in pattern as a constraint. } - @Test - public void testBindingOfPredicateIsNotUsedAsConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOfPredicateIsNotUsedAsConstraint(RUN_TYPE runType) { String str = "import " + MyNumber.class.getCanonicalName() + ";" + "rule R when\n" + " MyNumber($even : even, $value : value)" + @@ -324,7 +328,7 @@ public void testBindingOfPredicateIsNotUsedAsConstraint() { " insert($value);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new MyNumber(2)); ksession.fireAllRules(); @@ -340,8 +344,9 @@ public void testBindingOfPredicateIsNotUsedAsConstraint() { assertThat(results.contains(1)).isTrue(); // This is because MyNumber(1) would simply bind for "even" predicate/getter to $even variable, and not used as a constraint. } - @Test - public void testDeclaredWithAllPrimitives() { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredWithAllPrimitives(RUN_TYPE runType) { String str = "declare DeclaredAllPrimitives\n" + " my_byte : byte \n" + " my_short : short \n" + @@ -358,7 +363,7 @@ public void testDeclaredWithAllPrimitives() { " insert(new DeclaredAllPrimitives((byte) 1, (short) 1, 1, 1L, 1f, 1d, 'x', true));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -366,8 +371,9 @@ public void testDeclaredWithAllPrimitives() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testFactType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testFactType(RUN_TYPE runType) throws Exception { // DROOLS-4784 String str = "package org.test;\n" + @@ -381,7 +387,7 @@ public void testFactType() throws Exception { " insert($v);" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); FactType nameType = ksession.getKieBase().getFactType("org.test", "Name"); Object name = nameType.newInstance(); @@ -408,8 +414,9 @@ public void testFactType() throws Exception { assertThat(index >= 0).isTrue(); } - @Test - public void testFactTypeNotUsedInRule() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testFactTypeNotUsedInRule(RUN_TYPE runType) throws Exception { String str = "package org.test;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -424,7 +431,7 @@ public void testFactTypeNotUsedInRule() throws Exception { " insert($v);" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); FactType nameType = ksession.getKieBase().getFactType("org.test", "ExtendedName"); Object name = nameType.newInstance(); @@ -440,8 +447,9 @@ public void testFactTypeNotUsedInRule() throws Exception { assertThat(results.iterator().next()).isEqualTo("Mario"); } - @Test - public void testTypeDeclarationsInheritance() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testTypeDeclarationsInheritance(RUN_TYPE runType) throws Exception { String str = "declare Person\n" + " id : int @key\n" + @@ -463,11 +471,12 @@ public void testTypeDeclarationsInheritance() throws Exception { " Person pe = new Employee();\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); } - @Test - public void testEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testEnum(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -485,7 +494,7 @@ public void testEnum() { " insert(new Result($p));\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario")); ksession.fireAllRules(); @@ -496,8 +505,9 @@ public void testEnum() { assertThat(p.getAge()).isEqualTo(11); } - @Test - public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindowOnEventInTypeDeclaration(RUN_TYPE runType) throws Exception { String str = "package org.test;\n" + "declare MyPojo\n" + @@ -505,7 +515,7 @@ public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception "end\n" + "rule R when then insert(new MyPojo()); end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); Object pojo = getObjectsIntoList(ksession, Object.class).iterator().next(); @@ -514,8 +524,9 @@ public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception assertThat((long) f.get(pojo)).isEqualTo(42L); } - @Test - public void testNestedDateConstraint() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedDateConstraint(RUN_TYPE runType) throws Exception { String str = "package org.test;\n" + "declare Fact\n" + @@ -530,7 +541,7 @@ public void testNestedDateConstraint() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); FactType factType = kbase.getFactType("org.test", "Fact"); @@ -548,8 +559,9 @@ public void testNestedDateConstraint() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testExtendPojo() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExtendPojo(RUN_TYPE runType) throws Exception { String str = "package org.test;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -562,7 +574,7 @@ public void testExtendPojo() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); FactType factType = kbase.getFactType("org.test", "MyPerson"); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DowncastTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DowncastTest.java index 477e120af45..981768ef1ca 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DowncastTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DowncastTest.java @@ -20,19 +20,17 @@ import java.math.BigDecimal; -import org.junit.Test; +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; public class DowncastTest extends BaseModelTest { - public DowncastTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testDowncast() { + @ParameterizedTest + @MethodSource("parameters") + public void testDowncast(RUN_TYPE runType) { // DROOLS-6520 String str = "import " + Product.class.getCanonicalName() + ";" + @@ -48,7 +46,7 @@ public void testDowncast() { " update($lp);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Proposal cashProposal = new Proposal(new CashProduct(new BigDecimal(2))); Proposal loanProposal = new Proposal(new LoanProduct(new BigDecimal(12))); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DroolsContextTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DroolsContextTest.java index 7a29973489d..9e6e502cf61 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DroolsContextTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DroolsContextTest.java @@ -21,19 +21,17 @@ import java.util.ArrayList; import java.util.List; -import org.junit.Test; +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; public class DroolsContextTest extends BaseModelTest { - public DroolsContextTest(final RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testDroolsContext() { + @ParameterizedTest + @MethodSource("parameters") + public void testDroolsContext(RUN_TYPE runType) { final String str = "global java.util.List list\n" + "global java.util.List list2\n" + @@ -43,7 +41,7 @@ public void testDroolsContext() { " list.add(list2.add(kcontext));\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -56,8 +54,9 @@ public void testDroolsContext() { assertThat(list.size()).isEqualTo(1); } - @Test - public void testDroolsContextInString() { + @ParameterizedTest + @MethodSource("parameters") + public void testDroolsContextInString(RUN_TYPE runType) { final String str = "global java.util.List list\n" + "global java.util.List list2\n" + @@ -67,7 +66,7 @@ public void testDroolsContextInString() { " list.add(list2.add(\"something\" + kcontext));\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -80,8 +79,9 @@ public void testDroolsContextInString() { assertThat(list.size()).isEqualTo(1); } - @Test - public void testDroolsContextWithoutReplacingStrings() { + @ParameterizedTest + @MethodSource("parameters") + public void testDroolsContextWithoutReplacingStrings(RUN_TYPE runType) { final String str = "global java.util.List list\n" + "\n" + @@ -90,7 +90,7 @@ public void testDroolsContextWithoutReplacingStrings() { " list.add(\"this kcontext shoudln't be replaced\");\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -100,8 +100,9 @@ public void testDroolsContextWithoutReplacingStrings() { assertThat(list.get(0)).isEqualTo("this kcontext shoudln't be replaced"); } - @Test - public void testRuleContext() { + @ParameterizedTest + @MethodSource("parameters") + public void testRuleContext(RUN_TYPE runType) { final String str = "import " + FactWithRuleContext.class.getCanonicalName() + ";\n" + "global java.util.List list\n" + @@ -112,7 +113,7 @@ public void testRuleContext() { " list.add($factWithRuleContext.getRuleName(kcontext));\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EnumTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EnumTest.java index 12be270f641..e95e6146fd0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EnumTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EnumTest.java @@ -18,19 +18,18 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.Test; import org.kie.api.runtime.KieSession; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import static org.assertj.core.api.Assertions.assertThat; public class EnumTest extends BaseModelTest { - public EnumTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testMatchEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testMatchEnum(RUN_TYPE runType) { String str = "import " + Bus.class.getCanonicalName() + ";" + "rule bus2 when\n" + @@ -39,7 +38,7 @@ public void testMatchEnum() { " System.out.println(\"bus=\" + $bus + \", maker=\" + $maker);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str ); Bus a = new Bus("blue", 25, Bus.Maker.HINO); ksession.insert(a); @@ -49,8 +48,9 @@ public void testMatchEnum() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBindEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindEnum(RUN_TYPE runType) { // DROOLS-5851 String str = "import " + Bus.class.getCanonicalName() + ";" + @@ -60,7 +60,7 @@ public void testBindEnum() { " System.out.println(\"bus=\" + $bus + \", maker=\" + $maker);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Bus a = new Bus("blue", 25, Bus.Maker.HINO); ksession.insert(a); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EvalTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EvalTest.java index 95562316462..6e307f092c0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EvalTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EvalTest.java @@ -24,19 +24,18 @@ import org.drools.model.codegen.execmodel.domain.Overloaded; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +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; public class EvalTest extends BaseModelTest { - public EvalTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - @Test - public void testEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testEval(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -47,7 +46,7 @@ public void testEval() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -59,8 +58,9 @@ public void testEval() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWithMethodInvocation() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithMethodInvocation(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -71,7 +71,7 @@ public void testEvalWithMethodInvocation() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -83,56 +83,61 @@ public void testEvalWithMethodInvocation() { assertThat(results.iterator().next().getValue()).isEqualTo("Edson"); } - @Test - public void testEvalTrue() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalTrue(RUN_TYPE runType) { String str = "rule R when\n" + " eval( true )\n" + "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEvalFalse() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalFalse(RUN_TYPE runType) { String str = "rule R when\n" + " eval( false )\n" + "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testEvalOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalOr(RUN_TYPE runType) { String str = "rule R when\n" + " eval( true ) or eval( false )\n" + "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEvalIdentity() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalIdentity(RUN_TYPE runType) { String str = "rule R when\n" + " eval( 1 == 1 )\n" + "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunction(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -146,7 +151,7 @@ public void testFunction() { " insert(new Result(hello($p.getName())));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -158,8 +163,9 @@ public void testFunction() { assertThat(results.iterator().next().getValue()).isEqualTo("Hello Mario!"); } - @Test - public void testFunction2() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunction2(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -173,7 +179,7 @@ public void testFunction2() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -185,8 +191,9 @@ public void testFunction2() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWith2Bindings() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWith2Bindings(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -198,7 +205,7 @@ public void testEvalWith2Bindings() { " insert(new Result($p1.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 38 ) ); @@ -210,8 +217,9 @@ public void testEvalWith2Bindings() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWith2BindingsInvokingMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWith2BindingsInvokingMethod(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -223,7 +231,7 @@ public void testEvalWith2BindingsInvokingMethod() { " insert(new Result($p1.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mario", 38 ) ); @@ -235,8 +243,9 @@ public void testEvalWith2BindingsInvokingMethod() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWithDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithDeclaration(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -247,7 +256,7 @@ public void testEvalWithDeclaration() { " insert(new Result($p1.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 38 ) ); @@ -259,8 +268,9 @@ public void testEvalWithDeclaration() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWith2Declarations() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWith2Declarations(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -272,7 +282,7 @@ public void testEvalWith2Declarations() { " insert(new Result($p1.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 38 ) ); @@ -284,8 +294,9 @@ public void testEvalWith2Declarations() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWithBinary() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithBinary(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -295,7 +306,7 @@ public void testEvalWithBinary() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.insert(new Person("Mark", 37)); @@ -307,8 +318,9 @@ public void testEvalWithBinary() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalInvokingMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalInvokingMethod(RUN_TYPE runType) { String str = "import " + Overloaded.class.getCanonicalName() + ";" + "rule OverloadedMethods\n" + "when\n" + @@ -318,7 +330,7 @@ public void testEvalInvokingMethod() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Overloaded()); ksession.fireAllRules(); @@ -327,8 +339,9 @@ public void testEvalInvokingMethod() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testEvalInvokingMethod2() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalInvokingMethod2(RUN_TYPE runType) { String str = "import " + Overloaded.class.getCanonicalName() + ";" + "rule OverloadedMethods\n" + "when\n" + @@ -338,7 +351,7 @@ public void testEvalInvokingMethod2() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Overloaded()); ksession.fireAllRules(); @@ -348,8 +361,9 @@ public void testEvalInvokingMethod2() { } - @Test - public void testEvalInvokingFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalInvokingFunction(RUN_TYPE runType) { String str = "function boolean isPositive(int i){\n" + " return i > 0;\n" + @@ -361,7 +375,7 @@ public void testEvalInvokingFunction() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(42); ksession.fireAllRules(); @@ -370,8 +384,9 @@ public void testEvalInvokingFunction() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testEvalWithGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithGlobal(RUN_TYPE runType) { final String drl1 = "import " + Result.class.getCanonicalName() + ";\n" + "global java.lang.Integer globalInt\n" + @@ -381,7 +396,7 @@ public void testEvalWithGlobal() { " insert(new Result(\"match\"));\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.setGlobal("globalInt", 1); ksession.insert(1); @@ -394,8 +409,9 @@ public void testEvalWithGlobal() { assertThat(results.iterator().next().getValue().toString()).isEqualTo("match"); } - @Test - public void testEvalWithGlobal2() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithGlobal2(RUN_TYPE runType) { final String drl1 = "import " + Result.class.getCanonicalName() + ";\n" + "global java.lang.Integer globalInt\n" + @@ -405,7 +421,7 @@ public void testEvalWithGlobal2() { " insert(new Result(\"match\"));\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.setGlobal("globalInt", 1); ksession.insert(1); @@ -419,8 +435,9 @@ public void testEvalWithGlobal2() { } - @Test - public void testEvalExprWithFunctionCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalExprWithFunctionCall(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global " + GlobalFunctions.class.getCanonicalName() + " functions;" + @@ -430,7 +447,7 @@ public void testEvalExprWithFunctionCall() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); GlobalFunctions gf = new GlobalFunctions(); ksession.setGlobal("functions", gf); @@ -445,8 +462,9 @@ public Integer add(int a, int b) { } } - @Test - public void testEvalCalculationWithParenthesis() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalCalculationWithParenthesis(RUN_TYPE runType) { String str = "import " + CalcFact.class.getCanonicalName() + ";" + "rule R when\n" + @@ -455,7 +473,7 @@ public void testEvalCalculationWithParenthesis() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new CalcFact(1.0d, 1.0d)); // (1.0 / (1.0 * 10) * 10) is 1. So this rule should not fire @@ -464,8 +482,9 @@ public void testEvalCalculationWithParenthesis() { assertThat(fired).isEqualTo(0); } - @Test - public void testParseIntStringConcatenation() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testParseIntStringConcatenation(RUN_TYPE runType) throws Exception { String str = "rule R when\n" + " $s : String()\n" + @@ -473,7 +492,7 @@ public void testParseIntStringConcatenation() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("5"); assertThat(ksession.fireAllRules()).isEqualTo(1); } @@ -502,8 +521,9 @@ public void setT(String t) { } } - @Test - public void testModifyEvalAfterJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyEvalAfterJoin(RUN_TYPE runType) { // DROOLS-7255 String str = "import " + Dt1.class.getCanonicalName() + ";" + @@ -534,7 +554,7 @@ public void testModifyEvalAfterJoin() { " }\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Dt1 dt1 = new Dt1(); dt1.setA(1); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExisistentialTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExisistentialTest.java index 38cc55ca3fa..f5de60b45ac 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExisistentialTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExisistentialTest.java @@ -25,7 +25,8 @@ import org.assertj.core.api.Assertions; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import org.kie.api.runtime.rule.Match; @@ -38,12 +39,9 @@ public class ExisistentialTest extends BaseModelTest { - public ExisistentialTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testNot() { + @ParameterizedTest + @MethodSource("parameters") + public void testNot(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -53,7 +51,7 @@ public void testNot() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person( "Mario", 40 ); @@ -65,8 +63,9 @@ public void testNot() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testNotEmptyPredicate() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotEmptyPredicate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -76,7 +75,7 @@ public void testNotEmptyPredicate() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person( "Mario", 40 ); @@ -87,8 +86,9 @@ public void testNotEmptyPredicate() { assertThat(results.size()).isEqualTo(0); } - @Test - public void testExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testExists(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -98,7 +98,7 @@ public void testExists() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person( "Mario", 40 ); @@ -110,8 +110,9 @@ public void testExists() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testForall() { + @ParameterizedTest + @MethodSource("parameters") + public void testForall(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -122,7 +123,7 @@ public void testForall() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 41 ) ); ksession.insert( new Person( "Mark", 39 ) ); @@ -134,8 +135,9 @@ public void testForall() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testForallInQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testForallInQuery(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query ifAllPersonsAreOlderReturnThem (int pAge)\n" + @@ -143,7 +145,7 @@ public void testForallInQuery() { " $person : Person()\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 41 ) ); ksession.insert( new Person( "Mark", 39 ) ); @@ -155,8 +157,9 @@ public void testForallInQuery() { assertThat(results.size()).isEqualTo(3); } - @Test - public void testForallSingleConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testForallSingleConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -166,7 +169,7 @@ public void testForallSingleConstraint() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario")); ksession.insert(new Person("Edson")); @@ -177,8 +180,9 @@ public void testForallSingleConstraint() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testForallEmptyConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testForallEmptyConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -188,7 +192,7 @@ public void testForallEmptyConstraint() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario")); ksession.insert(new Person("Mark")); @@ -200,8 +204,9 @@ public void testForallEmptyConstraint() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testExistsEmptyPredicate() { + @ParameterizedTest + @MethodSource("parameters") + public void testExistsEmptyPredicate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -211,7 +216,7 @@ public void testExistsEmptyPredicate() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mark = new Person( "Mark", 37 ); Person mario = new Person( "Mario", 40 ); @@ -225,8 +230,9 @@ public void testExistsEmptyPredicate() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testComplexNots() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexNots(RUN_TYPE runType) throws Exception { String str = "package org.drools.testcoverage.regression;\n" + "\n" + @@ -270,13 +276,14 @@ public void testComplexNots() throws Exception { "end\n" + ""; - KieSession ksession = getKieSession( getCepKieModuleModel(), str ); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str ); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testDuplicateBindingNameInDifferentScope() { + @ParameterizedTest + @MethodSource("parameters") + public void testDuplicateBindingNameInDifferentScope(RUN_TYPE runType) { final String drl1 = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -286,15 +293,16 @@ public void testDuplicateBindingNameInDifferentScope() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( "test" ); ksession.insert( new Person("test", 18) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNotWithDereferencingConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotWithDereferencingConstraint(RUN_TYPE runType) { final String drl1 = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -304,14 +312,15 @@ public void testNotWithDereferencingConstraint() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( new Person("test", 18) ); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void test2NotsWithAnd() { + @ParameterizedTest + @MethodSource("parameters") + public void test2NotsWithAnd(RUN_TYPE runType) { final String drl1 = "package org.drools.compiler\n" + "rule R when\n" + @@ -326,13 +335,14 @@ public void test2NotsWithAnd() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testExistsWithAJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testExistsWithAJoin(RUN_TYPE runType) { // DROOLS-7065 final String drl1 = "package org.drools.compiler\n" + @@ -344,7 +354,7 @@ public void testExistsWithAJoin() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); AtomicInteger matchCount = new AtomicInteger(0); // Atomic only so that I get an effectively-final int. ((RuleEventManager) ksession).addEventListener(new RuleEventListener() { diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExternalisedLambdaTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExternalisedLambdaTest.java index b0a31db75dc..a97c79568b2 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExternalisedLambdaTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExternalisedLambdaTest.java @@ -30,9 +30,10 @@ import org.drools.model.codegen.execmodel.domain.StockTick; import org.drools.model.codegen.execmodel.domain.Woman; import org.drools.model.codegen.execmodel.util.lambdareplace.NonExternalisedLambdaFoundException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.conf.EventProcessingOption; @@ -53,23 +54,20 @@ public class ExternalisedLambdaTest extends BaseModelTest { private boolean checkNonExternalisedLambdaOrig; - public ExternalisedLambdaTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Before + @BeforeEach public void init() { checkNonExternalisedLambdaOrig = RuleWriter.isCheckNonExternalisedLambda(); RuleWriter.setCheckNonExternalisedLambda(true); } - @After + @AfterEach public void clear() { RuleWriter.setCheckNonExternalisedLambda(checkNonExternalisedLambdaOrig); } - @Test - public void testConsequenceNoVariable() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceNoVariable(RUN_TYPE runType) { // DROOLS-4924 String str = "package defaultpkg;\n" + @@ -82,7 +80,7 @@ public void testConsequenceNoVariable() throws Exception { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -93,8 +91,9 @@ public void testConsequenceNoVariable() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testExternalizeBindingVariableLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalizeBindingVariableLambda(RUN_TYPE runType) { String str = "package defaultpkg;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -107,7 +106,7 @@ public void testExternalizeBindingVariableLambda() throws Exception { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -122,8 +121,9 @@ public void testExternalizeBindingVariableLambda() throws Exception { assertThat(list).containsExactlyInAnyOrder("Mario"); } - @Test - public void testExternalizeLambdaPredicate() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalizeLambdaPredicate(RUN_TYPE runType) { String str = "package defaultpkg;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -136,7 +136,7 @@ public void testExternalizeLambdaPredicate() throws Exception { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -151,8 +151,9 @@ public void testExternalizeLambdaPredicate() throws Exception { assertThat(list).containsExactlyInAnyOrder("Mario"); } - @Test - public void testExternalizeLambdaUsingVariable() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalizeLambdaUsingVariable(RUN_TYPE runType) { String str = "package defaultpkg;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -166,7 +167,7 @@ public void testExternalizeLambdaUsingVariable() throws Exception { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -181,8 +182,9 @@ public void testExternalizeLambdaUsingVariable() throws Exception { assertThat(list).containsExactlyInAnyOrder(43); } - @Test - public void testEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testEval(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -195,7 +197,7 @@ public void testEval() { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -210,8 +212,9 @@ public void testEval() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testFromExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromExpression(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -225,7 +228,7 @@ public void testFromExpression() { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -248,8 +251,9 @@ public void testFromExpression() { assertThat(list).containsExactlyInAnyOrder("Charles"); } - @Test - public void testAccumulateWithBinaryExpr() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithBinaryExpr(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -264,7 +268,7 @@ public void testAccumulateWithBinaryExpr() { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -281,8 +285,9 @@ public void testAccumulateWithBinaryExpr() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(77); } - @Test - public void testOOPath() { + @ParameterizedTest + @MethodSource("parameters") + public void testOOPath(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -295,7 +300,7 @@ public void testOOPath() { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -320,8 +325,9 @@ public void testOOPath() { assertThat(list).containsExactlyInAnyOrder("Bob"); } - @Test - public void testCep() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCep(RUN_TYPE runType) { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -339,7 +345,7 @@ public void testCep() throws Exception { .setDefault( true ).setClockType( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); KieSession ksession = null; try { - ksession = getKieSession(kmodel, str); + ksession = getKieSession(runType, kmodel, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FromTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FromTest.java index afbcfe18403..770896c5e90 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FromTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FromTest.java @@ -29,7 +29,9 @@ import org.drools.model.codegen.execmodel.domain.Toy; import org.drools.model.codegen.execmodel.domain.ToysStore; import org.drools.model.codegen.execmodel.domain.Woman; -import org.junit.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.runtime.KieSession; @@ -54,12 +56,9 @@ public class FromTest extends BaseModelTest { - public FromTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testFromGlobal() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testFromGlobal(RUN_TYPE runType) throws Exception { String str = "global java.util.List list \n" + "rule R when \n" + " $o : String(length > 3) from list\n" + @@ -67,7 +66,7 @@ public void testFromGlobal() throws Exception { " insert($o); \n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List strings = Arrays.asList("a", "Hello World!", "xyz"); @@ -81,8 +80,9 @@ public void testFromGlobal() throws Exception { assertThat(results.contains("xyz")).isFalse(); } - @Test - public void testFromVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromVariable(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -94,7 +94,7 @@ public void testFromVariable() { " list.add( $child.getName() );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -114,8 +114,9 @@ public void testFromVariable() { assertThat(list).containsExactlyInAnyOrder("Charles"); } - @Test - public void testFromExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromExpression(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -127,7 +128,7 @@ public void testFromExpression() { " list.add( $child.getName() );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -147,8 +148,9 @@ public void testFromExpression() { assertThat(list).containsExactlyInAnyOrder("Charles"); } - @Test - public void testModifyWithFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyWithFrom(RUN_TYPE runType) { // DROOLS-6486 final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + @@ -160,7 +162,7 @@ public void testModifyWithFrom() { " modify( $child ) { setName($child.getName() + \"x\") };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final Woman alice = new Woman( "Alice", 38 ); final Man bob = new Man( "Bob", 40 ); @@ -178,8 +180,9 @@ public void testModifyWithFrom() { assertThat(charlie.getName()).isEqualTo("Charlesx"); } - @Test - public void testModifyWithFromAndReevaluate() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyWithFromAndReevaluate(RUN_TYPE runType) { // DROOLS-7203 final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + @@ -208,7 +211,7 @@ public void testModifyWithFromAndReevaluate() { " delete($s);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -241,8 +244,10 @@ public void testModifyWithFromAndReevaluate() { assertThat(results).containsExactly("executed"); // R1 should not be executed twice because age is modified to 13 } - @Test(timeout = 20000) - public void testModifyWithFromSudoku() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(20000) + public void testModifyWithFromSudoku(RUN_TYPE runType) { // DROOLS-7203 : Slimmed down Sudoku final String str = "import " + Setting.class.getCanonicalName() + ";\n" + @@ -297,7 +302,7 @@ public void testModifyWithFromSudoku() { " insert( new Setting( $rn, $cn, i ) );\n" + "end\n"; - KieSession ksession = getKieSession(getDisablePropertyReactivityKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getDisablePropertyReactivityKieModuleModel(), str); Cell c1 = new Cell(0, 0, null); c1.setFree(new HashSet<>(Arrays.asList(1, 2, 3))); @@ -496,8 +501,9 @@ public static Integer getLength(String ignoredParameter, String s, Integer offse return s.length() + offset; } - @Test - public void testFromExternalFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromExternalFunction(RUN_TYPE runType) { final String str = "import " + FromTest.class.getCanonicalName() + ";\n" + "global java.util.List list\n" + @@ -509,7 +515,7 @@ public void testFromExternalFunction() { " list.add( \"received long message: \" + $s);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -520,8 +526,9 @@ public void testFromExternalFunction() { assertThat(list).containsExactlyInAnyOrder("received long message: Hello World!"); } - @Test - public void testFromExternalFunctionMultipleBindingArguments() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromExternalFunctionMultipleBindingArguments(RUN_TYPE runType) { final String str = "import " + FromTest.class.getCanonicalName() + ";\n" + "global java.util.List list\n" + @@ -534,7 +541,7 @@ public void testFromExternalFunctionMultipleBindingArguments() { " list.add( \"received long message: \" + $s);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -546,8 +553,9 @@ public void testFromExternalFunctionMultipleBindingArguments() { assertThat(list).containsExactlyInAnyOrder("received long message: Hello!"); } - @Test - public void testFromConstant() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromConstant(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "global java.util.List list\n" + @@ -558,7 +566,7 @@ public void testFromConstant() { " list.add( $s );\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -568,8 +576,9 @@ public void testFromConstant() { assertThat(list.get(0)).isEqualTo("test"); } - @Test - public void testFromConstructor() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromConstructor(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -583,7 +592,7 @@ public void testFromConstructor() { " list.add( $p );\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -597,8 +606,9 @@ public void testFromConstructor() { assertThat(list.get(0)).isEqualTo(new Person("Mario", 44)); } - @Test - public void testFromMapValues() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromMapValues(RUN_TYPE runType) { // DROOLS-3661 String str = "package org.drools.compiler.test \n" + @@ -611,7 +621,7 @@ public void testFromMapValues() { "then\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); PetPerson petPerson = new PetPerson( "me" ); Map petMap = new HashMap<>(); @@ -623,8 +633,9 @@ public void testFromMapValues() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGlobalInFromExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalInFromExpression(RUN_TYPE runType) { // DROOLS-4999 String str = "package org.drools.compiler.test \n" + @@ -638,7 +649,7 @@ public void testGlobalInFromExpression() { "then\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "petName", "Dog" ); @@ -652,8 +663,9 @@ public void testGlobalInFromExpression() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testLiteralFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testLiteralFrom(RUN_TYPE runType) { // DROOLS-5217 String str = "package com.sample\n" + @@ -665,15 +677,16 @@ public void testLiteralFrom() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,2,3) ) ); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(2); } - @Test - public void testLiteralFrom2() { + @ParameterizedTest + @MethodSource("parameters") + public void testLiteralFrom2(RUN_TYPE runType) { // DROOLS-5217 String str = "package com.sample\n" + @@ -685,15 +698,16 @@ public void testLiteralFrom2() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,2,3) ) ); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); } - @Test - public void testFromCollect() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollect(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -704,7 +718,7 @@ public void testFromCollect() { "then\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p1 = new Person("John", 32); Person p2 = new Person("Paul", 30); @@ -717,8 +731,9 @@ public void testFromCollect() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testFromCollectCustomSet() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectCustomSet(RUN_TYPE runType) { // DROOLS-7534 String str = "package org.drools.compiler.test \n" + @@ -732,7 +747,7 @@ public void testFromCollectCustomSet() { " FromTest.printPersons($set);" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p1 = new Person("John", 32); Person p1a = new Person("John", 32); @@ -758,8 +773,9 @@ public MyHashSet() { } } - @Test - public void testThisArray() { + @ParameterizedTest + @MethodSource("parameters") + public void testThisArray(RUN_TYPE runType) { // This test verifies the behavior when ArrayType is used as "_this" (which $childrenA is converted to) in from clause. String str = "package org.drools.compiler.test \n" + @@ -773,7 +789,7 @@ public void testThisArray() { " list.add($i);\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -786,8 +802,9 @@ public void testThisArray() { assertThat(list).containsExactlyInAnyOrder(2); } - @Test - public void testFromArray() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromArray(RUN_TYPE runType) { // This test verifies the behavior when the return type is ArrayType String str = "package org.drools.compiler.test \n" + @@ -802,7 +819,7 @@ public void testFromArray() { " list.add($p.getName());\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -815,8 +832,9 @@ public void testFromArray() { assertThat(list).containsExactlyInAnyOrder("Julian", "Sean"); } - @Test - public void testInnerClassCollection() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerClassCollection(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + MyPerson.class.getCanonicalName() + "\n" + @@ -827,7 +845,7 @@ public void testInnerClassCollection() { "then\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); MyPerson john = new MyPerson("John"); Collection kids = new ArrayList<>(); @@ -840,8 +858,9 @@ public void testInnerClassCollection() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testInnerClassWithInstanceMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerClassWithInstanceMethod(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + MyPerson.class.getCanonicalName() + "\n" + @@ -854,7 +873,7 @@ public void testInnerClassWithInstanceMethod() { " list.add($d.getName());" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -865,8 +884,9 @@ public void testInnerClassWithInstanceMethod() { assertThat(list).containsExactlyInAnyOrder("Dummy"); } - @Test - public void testInnerClassWithStaticMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerClassWithStaticMethod(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + MyPerson.class.getCanonicalName() + "\n" + @@ -878,7 +898,7 @@ public void testInnerClassWithStaticMethod() { " list.add($d.getName());" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -886,8 +906,9 @@ public void testInnerClassWithStaticMethod() { assertThat(list).containsExactlyInAnyOrder("Dummy"); } - @Test - public void testInnerClassWithStaticMethodWithArg() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerClassWithStaticMethodWithArg(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + MyPerson.class.getCanonicalName() + "\n" + @@ -900,7 +921,7 @@ public void testInnerClassWithStaticMethodWithArg() { " list.add($d.getName());" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -965,8 +986,9 @@ public static MyPerson getDummyPersonStatic(String name) { } } - @Test - public void testNew() { + @ParameterizedTest + @MethodSource("parameters") + public void testNew(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -978,7 +1000,7 @@ public void testNew() { " list.add($p);\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -987,8 +1009,9 @@ public void testNew() { assertThat(list.size()).isEqualTo(1); } - @Test - public void testFromOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromOr(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1008,7 +1031,7 @@ public void testFromOr() { " list.add($store.getStoreName());\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1066,8 +1089,9 @@ public Object getSomethingBy(Object o) { } } - @Test - public void testFromFunctionCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromFunctionCall(RUN_TYPE runType) { // DROOLS-5548 String str = "package com.sample;" + @@ -1101,7 +1125,7 @@ public void testFromFunctionCall() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1114,8 +1138,9 @@ public void testFromFunctionCall() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void testFromMap() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromMap(RUN_TYPE runType) { // DROOLS-5549 String str = "package com.sample;" + @@ -1137,7 +1162,7 @@ public void testFromMap() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1150,8 +1175,9 @@ public void testFromMap() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void testFromChainedCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromChainedCall(RUN_TYPE runType) { // DROOLS-5608 String str = "package com.sample;" + @@ -1170,7 +1196,7 @@ public void testFromChainedCall() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1200,8 +1226,9 @@ public static Map.Entry mapEntry(K key, V value) { } } - @Test - public void testNestedService() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedService(RUN_TYPE runType) { // DROOLS-5609 String str = "package com.sample;" + @@ -1218,7 +1245,7 @@ public void testNestedService() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1233,8 +1260,9 @@ public void testNestedService() { } - @Test - public void testMultipleFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleFrom(RUN_TYPE runType) { // DROOLS-5542 String str = "package com.sample;" + @@ -1254,7 +1282,7 @@ public void testMultipleFrom() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1268,8 +1296,9 @@ public void testMultipleFrom() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void testMultipleFromFromBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleFromFromBinding(RUN_TYPE runType) { // DROOLS-5591 String str = "package com.sample;" + @@ -1286,7 +1315,7 @@ public void testMultipleFromFromBinding() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1300,8 +1329,9 @@ public void testMultipleFromFromBinding() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void testMultipleFromList() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleFromList(RUN_TYPE runType) { // DROOLS-5590 String str = "package com.sample;" + @@ -1324,7 +1354,7 @@ public void testMultipleFromList() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1338,8 +1368,9 @@ public void testMultipleFromList() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void tesFromMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void tesFromMethodCall(RUN_TYPE runType) { // DROOLS-5641 String str = "package com.sample;" + @@ -1361,7 +1392,7 @@ public void tesFromMethodCall() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1376,8 +1407,9 @@ public void tesFromMethodCall() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void testFromStringConcatenation() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromStringConcatenation(RUN_TYPE runType) { // DROOLS-5640 String str = "global java.util.List list;\n" + @@ -1389,7 +1421,7 @@ public void testFromStringConcatenation() { " list.add($c);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1400,8 +1432,9 @@ public void testFromStringConcatenation() { assertThat(list).containsExactlyInAnyOrder("AA", "AB", "BA", "BB"); } - @Test - public void testFromBoolean() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromBoolean(RUN_TYPE runType) { // DROOLS-5830 String str = "rule R when\n" + @@ -1411,14 +1444,15 @@ public void testFromBoolean() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "A" ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testFromCollectWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithOr(RUN_TYPE runType) { // DROOLS-6531 String str = "import java.util.List;\n" + @@ -1432,7 +1466,7 @@ public void testFromCollectWithOr() { " $list.addAll($values);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.insert(list); @@ -1444,8 +1478,9 @@ public void testFromCollectWithOr() { assertThat(list.size()).isEqualTo(2); } - @Test - public void fromWithTernaryExpressionBoolean() { + @ParameterizedTest + @MethodSource("parameters") + public void fromWithTernaryExpressionBoolean(RUN_TYPE runType) { // DROOLS-7236 String str = "global java.util.List results;\n" + @@ -1457,7 +1492,7 @@ public void fromWithTernaryExpressionBoolean() { " results.add($bar);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1467,8 +1502,9 @@ public void fromWithTernaryExpressionBoolean() { assertThat(results).containsExactly(true); } - @Test - public void fromWithTernaryExpressionBooleanWithMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void fromWithTernaryExpressionBooleanWithMethodCall(RUN_TYPE runType) { // DROOLS-7236 String str = "import " + MyFact.class.getCanonicalName() + ";\n" + @@ -1481,7 +1517,7 @@ public void fromWithTernaryExpressionBooleanWithMethodCall() { " results.add($bar);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1491,8 +1527,9 @@ public void fromWithTernaryExpressionBooleanWithMethodCall() { assertThat(results).containsExactly(true); } - @Test - public void fromWithTernaryExpressionStringWithMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void fromWithTernaryExpressionStringWithMethodCall(RUN_TYPE runType) { // DROOLS-7236 String str = "import " + MyFact.class.getCanonicalName() + ";\n" + @@ -1505,7 +1542,7 @@ public void fromWithTernaryExpressionStringWithMethodCall() { " results.add($bar);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1544,8 +1581,9 @@ public void setStrValue(String strValue) { } - @Test - public void testFromGlobalWithDuplicates() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromGlobalWithDuplicates(RUN_TYPE runType) { String str = "import java.util.concurrent.atomic.AtomicInteger;\n" + "import " + NamedPerson.class.getCanonicalName() + ";\n" + @@ -1557,7 +1595,7 @@ public void testFromGlobalWithDuplicates() { " insert($o); \n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List strings = Arrays.asList(new NamedPerson("Mario", 1), new NamedPerson("Mario", 2)); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FunctionsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FunctionsTest.java index 04af90eab76..6fb44fa32dd 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FunctionsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FunctionsTest.java @@ -24,19 +24,17 @@ import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +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; public class FunctionsTest extends BaseModelTest { - public FunctionsTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testFunctionWithEquals() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunctionWithEquals(RUN_TYPE runType) { // DROOLS-3653 String str = "package com.sample\n" + "import " + Person.class.getName() + ";\n" + @@ -58,15 +56,16 @@ public void testFunctionWithEquals() { " then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("John", 10)); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); // only R1 should fire } - @Test - public void testConstraintCallingStaticFunctionInsideEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintCallingStaticFunctionInsideEnum(RUN_TYPE runType) { String str = "import " + Person.class.getName() + ";\n" + "import " + FunctionEnum.class.getCanonicalName() + ";\n" + @@ -76,7 +75,7 @@ public void testConstraintCallingStaticFunctionInsideEnum() { " then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 10); @@ -88,8 +87,9 @@ public void testConstraintCallingStaticFunctionInsideEnum() { assertThat(rulesFired).isEqualTo(1); } - @Test - public void testConstraintCallingImportedStaticFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintCallingImportedStaticFunction(RUN_TYPE runType) { String str = "import " + Person.class.getName() + ";\n" + "import " + FunctionEnum.class.getCanonicalName() + ";\n" + @@ -100,7 +100,7 @@ public void testConstraintCallingImportedStaticFunction() { " then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 10); @@ -121,8 +121,9 @@ public static FunctionEnum constantEnumValue(String input) { } - @Test - public void testStaticMethodCall1() { + @ParameterizedTest + @MethodSource("parameters") + public void testStaticMethodCall1(RUN_TYPE runType) { // DROOLS-5214 String str = "package com.sample\n" + @@ -134,15 +135,16 @@ public void testStaticMethodCall1() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,3) ) ); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); } - @Test - public void testStaticMethodCall2() { + @ParameterizedTest + @MethodSource("parameters") + public void testStaticMethodCall2(RUN_TYPE runType) { // DROOLS-5214 String str = "package com.sample\n" + @@ -154,15 +156,16 @@ public void testStaticMethodCall2() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,2,3) ) ); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); } - @Test - public void testFQNStaticMethodCall1() { + @ParameterizedTest + @MethodSource("parameters") + public void testFQNStaticMethodCall1(RUN_TYPE runType) { // DROOLS-5214 String str = "package com.sample\n" + @@ -173,15 +176,16 @@ public void testFQNStaticMethodCall1() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,3) ) ); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); } - @Test - public void testFQNStaticMethodCall2() { + @ParameterizedTest + @MethodSource("parameters") + public void testFQNStaticMethodCall2(RUN_TYPE runType) { // DROOLS-5214 String str = "package com.sample\n" + @@ -192,7 +196,7 @@ public void testFQNStaticMethodCall2() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,2,3) ) ); int rulesFired = ksession.fireAllRules(); @@ -211,8 +215,9 @@ public List getIntList() { } } - @Test - public void testInvokeFunctionWithDroolsKeyword() { + @ParameterizedTest + @MethodSource("parameters") + public void testInvokeFunctionWithDroolsKeyword(RUN_TYPE runType) { // DROOLS-5215 String str = "package com.sample\n" + @@ -226,14 +231,15 @@ public void testInvokeFunctionWithDroolsKeyword() { " printRuleName(drools.getRule().getName());\n" + " end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); } - @Test - public void testBindingFieldsIndexedWithSquareBrackets() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingFieldsIndexedWithSquareBrackets(RUN_TYPE runType) { // DROOLS-5216 String str = "package com.sample\n" + @@ -245,7 +251,7 @@ public void testBindingFieldsIndexedWithSquareBrackets() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,3) ) ); int rulesFired = ksession.fireAllRules(); @@ -256,8 +262,9 @@ public static String constantValue(String input) { return "whatever"; } - @Test - public void testExternalFunctionJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalFunctionJoin(RUN_TYPE runType) { // DROOLS-5288 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -273,7 +280,7 @@ public void testExternalFunctionJoin() { " insert(new Result($p2.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Luca")); ksession.insert(new Person("whatever")); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GeneratedClassNamesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GeneratedClassNamesTest.java index 97e765af554..4453582a29f 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GeneratedClassNamesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GeneratedClassNamesTest.java @@ -20,6 +20,7 @@ import java.util.Set; import java.util.UUID; +import java.util.stream.Stream; import org.drools.compiler.compiler.io.memory.MemoryFileSystem; import org.drools.compiler.kie.builder.impl.InternalKieModule; @@ -30,10 +31,10 @@ import org.drools.modelcompiler.CanonicalKieModule; import org.drools.wiring.api.classloader.ProjectClassLoader; import org.drools.wiring.api.classloader.ProjectClassLoaderTestUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; @@ -54,28 +55,24 @@ public class GeneratedClassNamesTest extends BaseModelTest { private boolean enableStoreFirstOrig; - public GeneratedClassNamesTest(RUN_TYPE testRunType) { - super(testRunType); + public static Stream parameters() { + return Stream.of(RUN_TYPE.PATTERN_DSL); } - @Parameters(name = "{0}") - public static Object[] params() { - return new Object[]{RUN_TYPE.PATTERN_DSL}; - } - - @Before - public void init() { + @BeforeEach + public void setUp() { enableStoreFirstOrig = ProjectClassLoader.isEnableStoreFirst(); ProjectClassLoaderTestUtil.setEnableStoreFirst(true); } - @After - public void clear() { + @AfterEach + public void tearDown() { ProjectClassLoaderTestUtil.setEnableStoreFirst(enableStoreFirstOrig); } - @Test - public void testGeneratedClassNames() { + @ParameterizedTest + @MethodSource("parameters") + public void testGeneratedClassNames(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -87,7 +84,7 @@ public void testGeneratedClassNames() { KieServices ks = KieServices.get(); ReleaseId releaseId = ks.newReleaseId("org.kie", "kjar-test-" + UUID.randomUUID(), "1.0"); - createKieBuilder(ks, getDefaultKieModuleModel( ks ), releaseId, toKieFiles(new String[]{str})); + createKieBuilder(runType, ks, getDefaultKieModuleModel( ks ), releaseId, toKieFiles(new String[]{str})); KieContainer kcontainer = ks.newKieContainer(releaseId); KieModule kieModule = ((KieContainerImpl) kcontainer).getKieModuleForKBase("kbase"); @@ -123,12 +120,14 @@ private void assertGeneratedClassNames(Set generatedClassNames) { } } - @Test + @ParameterizedTest + @MethodSource("parameters") public void testModuleWithDepWithoutClassLoader() throws Exception { testModuleWithDep(null); } - @Test + @ParameterizedTest + @MethodSource("parameters") public void testModuleWithDepWithClassLoader() throws Exception { ProjectClassLoader projectClassLoader = ProjectClassLoader.createProjectClassLoader(Thread.currentThread().getContextClassLoader()); testModuleWithDep(projectClassLoader); @@ -266,8 +265,9 @@ private void assertGeneratedClassNamesWithDep(Set generatedClassNames) { } } - @Test - public void testKjarWithoutGeneratedClassNames() { + @ParameterizedTest + @MethodSource("parameters") + public void testKjarWithoutGeneratedClassNames(RUN_TYPE runType) { // Build a kjar without generated-class-names file (= simulating a build by old drools version) ProjectClassLoaderTestUtil.setEnableStoreFirst(false); @@ -283,7 +283,7 @@ public void testKjarWithoutGeneratedClassNames() { KieServices ks = KieServices.get(); ReleaseId releaseId = ks.newReleaseId("org.kie", "kjar-test-" + UUID.randomUUID(), "1.0"); - KieBuilder kieBuilder = createKieBuilder(ks, getDefaultKieModuleModel( ks ), releaseId, toKieFiles(new String[]{str})); + KieBuilder kieBuilder = createKieBuilder(runType, ks, getDefaultKieModuleModel( ks ), releaseId, toKieFiles(new String[]{str})); final InternalKieModule kieModule = (InternalKieModule) kieBuilder.getKieModule(); byte[] kjar = kieModule.getBytes(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GenericsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GenericsTest.java index c08544f01e9..a2bccfaaece 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GenericsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GenericsTest.java @@ -24,19 +24,17 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +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; public class GenericsTest extends BaseModelTest { - public GenericsTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testGenericsAccumulateInlineCode() { + @ParameterizedTest + @MethodSource("parameters") + public void testGenericsAccumulateInlineCode(RUN_TYPE runType) { // accumulate inline code supports generics String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -55,7 +53,7 @@ public void testGenericsAccumulateInlineCode() { " results.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List> results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -94,8 +92,9 @@ public void setExtendedAddress(final P extendedAddress) { } } - @Test - public void testClassWithGenericField() { + @ParameterizedTest + @MethodSource("parameters") + public void testClassWithGenericField(RUN_TYPE runType) { // KIE-1077 String str = "import " + ClassWithGenericField.class.getCanonicalName() + ";\n " + @@ -107,7 +106,7 @@ public void testClassWithGenericField() { " results.add($addressStreet);\n " + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -118,8 +117,9 @@ public void testClassWithGenericField() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGenericsOnSuperclass() { + @ParameterizedTest + @MethodSource("parameters") + public void testGenericsOnSuperclass(RUN_TYPE runType) { // KIE-DROOLS-5925 String str = "import " + DieselCar.class.getCanonicalName() + ";\n " + @@ -143,11 +143,12 @@ public void testGenericsOnSuperclass() { " update($v);\n" + "end"; - runTestWithGenerics(str); + runTestWithGenerics(runType, str); } - @Test - public void testGenericsOnSuperclassWithRedundantVariableDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testGenericsOnSuperclassWithRedundantVariableDeclaration(RUN_TYPE runType) { // KIE-DROOLS-5925 String str = "import " + DieselCar.class.getCanonicalName() + ";\n " + @@ -171,11 +172,11 @@ public void testGenericsOnSuperclassWithRedundantVariableDeclaration() { " update($v);\n" + "end"; - runTestWithGenerics(str); + runTestWithGenerics(runType, str); } - private void runTestWithGenerics(String str) { - KieSession ksession = getKieSession(str); + private void runTestWithGenerics(RUN_TYPE runType, String str) { + KieSession ksession = getKieSession(runType, str); DieselCar vehicle1 = new DieselCar("Volkswagen", "Passat", 100); vehicle1.setFrameMaxTorque(500); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GetterOverloadingTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GetterOverloadingTest.java index 5c72aa7700a..d4408ce55e3 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GetterOverloadingTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GetterOverloadingTest.java @@ -20,7 +20,8 @@ import java.util.List; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.Message.Level; @@ -31,10 +32,6 @@ public class GetterOverloadingTest extends BaseModelTest { - public GetterOverloadingTest(RUN_TYPE testRunType) { - super(testRunType); - } - // NOTE: Drools/Mvel accepts 5 kinds of getters // e.g. for "resource" property, // @@ -46,8 +43,9 @@ public GetterOverloadingTest(RUN_TYPE testRunType) { // // If a class has multiple getters of those 5, one getter has to be chosen based on the above priority order - @Test - public void testDuplicateDifferentPropertyInClassHierarchy() { + @ParameterizedTest + @MethodSource("parameters") + public void testDuplicateDifferentPropertyInClassHierarchy(RUN_TYPE runType) { // ClassA.resource is boolean : isResource() // ClassB.resource is String : getResource() // Mvel picks a method from getResource or isResoure depending on the order of Class.getMethods() -> unreliable. So let's make this ERROR @@ -59,7 +57,7 @@ public void testDuplicateDifferentPropertyInClassHierarchy() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(Level.ERROR); assertThat(messages.get(0).getText()).contains("Incompatible Getter overloading detected"); } @@ -90,8 +88,9 @@ public void setResource(String resource) { } } - @Test - public void testBooleanAccessorOverload() { + @ParameterizedTest + @MethodSource("parameters") + public void testBooleanAccessorOverload(RUN_TYPE runType) { // ClassC implements both isResource() and getResource() for boolean (This is acceptable according to Javabeans spec) // isResource() has to be prioritized per Javabeans spec. // No Warning @@ -103,7 +102,7 @@ public void testBooleanAccessorOverload() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -135,8 +134,9 @@ public void setResource(boolean resource) { } } - @Test - public void testAccessorInMultipleInterfaces() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccessorInMultipleInterfaces(RUN_TYPE runType) { // 2 super interfaces have the same abstract method // Valid overriding. No warning. final String str = @@ -147,7 +147,7 @@ public void testAccessorInMultipleInterfaces() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -189,8 +189,9 @@ public String getName() { } } - @Test - public void testAccessorInSuperClassAndInterface() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccessorInSuperClassAndInterface(RUN_TYPE runType) { // Valid overriding from super class and interface. No Warning final String str = "import " + ClassF.class.getCanonicalName() + ";" + @@ -200,7 +201,7 @@ public void testAccessorInSuperClassAndInterface() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -240,8 +241,9 @@ public String getName() { } } - @Test - public void testAcceptableStringAccessorOverload() { + @ParameterizedTest + @MethodSource("parameters") + public void testAcceptableStringAccessorOverload(RUN_TYPE runType) { // ClassG implements getName(), getname() and name() for String // This is acceptable overloading and getName() has to be prioritized. No Warning. final String str = @@ -252,7 +254,7 @@ public void testAcceptableStringAccessorOverload() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -287,8 +289,9 @@ public String name() { } } - @Test - public void testCovariantOverload() { + @ParameterizedTest + @MethodSource("parameters") + public void testCovariantOverload(RUN_TYPE runType) { // ClassH : getValue() returns Number // ClassI : getValue() returns Integer // a more specialized getter (covariant overload) is preferred. @@ -300,7 +303,7 @@ public void testCovariantOverload() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -339,8 +342,9 @@ public Integer getValue() { } } - @Test - public void testContravariantOverload() { + @ParameterizedTest + @MethodSource("parameters") + public void testContravariantOverload(RUN_TYPE runType) { // ClassJ : getValue() returns Integer // ClassK : getvalue() returns Number // a more specialized getter (covariant overload) is preferred regardless of class hierarchy. @@ -352,7 +356,7 @@ public void testContravariantOverload() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -390,8 +394,9 @@ public Number getvalue() { // cannot define Number getValue() } } - @Test - public void testPossibleBooleanAccessorOverload() { + @ParameterizedTest + @MethodSource("parameters") + public void testPossibleBooleanAccessorOverload(RUN_TYPE runType) { // ClassL implements 5 possible getters // This is acceptable overloading and isResource() has to be prioritized. No Warning. final String str = @@ -402,7 +407,7 @@ public void testPossibleBooleanAccessorOverload() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GlobalTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GlobalTest.java index 190a6bc792a..b3bf58b9c81 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GlobalTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GlobalTest.java @@ -25,7 +25,8 @@ import org.drools.model.codegen.execmodel.domain.InputDataTypes; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.Message; import org.kie.api.builder.Results; @@ -36,12 +37,9 @@ public class GlobalTest extends BaseModelTest { - public GlobalTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testGlobalInConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalInConsequence(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Person.class.getCanonicalName() + ";" + @@ -53,7 +51,7 @@ public void testGlobalInConsequence() { " globalResult.setValue($p1.getName() + \" is \" + $p1.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.setGlobal("globalResult", result); @@ -67,8 +65,9 @@ public void testGlobalInConsequence() { assertThat(result.getValue()).isEqualTo("Mark is 37"); } - @Test - public void testGlobalInConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalInConstraint(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Person.class.getCanonicalName() + ";" + @@ -81,7 +80,7 @@ public void testGlobalInConstraint() { " resultG.setValue($p1.getName() + \" is \" + $p1.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("nameG", "Mark"); @@ -164,8 +163,9 @@ public Double sumOf(Object[] objects) { } - @Test - public void testGlobalBooleanFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalBooleanFunction(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Person.class.getCanonicalName() + ";" + @@ -179,7 +179,7 @@ public void testGlobalBooleanFunction() { " resultG.setValue($p1.getName() + \" is \" + $p1.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); @@ -195,8 +195,9 @@ public void testGlobalBooleanFunction() { assertThat(result.getValue()).isEqualTo("Mark is 37"); } - @Test - public void testGlobalFunctionOnLeft() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalFunctionOnLeft(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Person.class.getCanonicalName() + ";" + @@ -210,7 +211,7 @@ public void testGlobalFunctionOnLeft() { " resultG.setValue($p1.getName() + \" is \" + $p1.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); @@ -226,8 +227,9 @@ public void testGlobalFunctionOnLeft() { assertThat(result.getValue()).isEqualTo("Mark is 37"); } - @Test - public void testGlobalFunctionOnRight() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalFunctionOnRight(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Person.class.getCanonicalName() + ";" + @@ -241,7 +243,7 @@ public void testGlobalFunctionOnRight() { " resultG.setValue($p1.getName() + \" is \" + $p1.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); @@ -263,8 +265,9 @@ public Object getPersons() { } } - @Test - public void testComplexGlobalFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexGlobalFunction(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Family.class.getCanonicalName() + ";" + @@ -277,15 +280,16 @@ public void testComplexGlobalFunction() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new Family()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testComplexGlobalFunctionWithShort() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexGlobalFunctionWithShort(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Family.class.getCanonicalName() + ";" + @@ -298,15 +302,16 @@ public void testComplexGlobalFunctionWithShort() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new Family()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testComplexGlobalFunctionWithShortEvalOnJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexGlobalFunctionWithShortEvalOnJoin(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Family.class.getCanonicalName() + ";" + @@ -320,7 +325,7 @@ public void testComplexGlobalFunctionWithShortEvalOnJoin() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new Family()); ksession.insert("test"); @@ -328,8 +333,9 @@ public void testComplexGlobalFunctionWithShortEvalOnJoin() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testComplexGlobalFunctionWithShortNotFiring() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexGlobalFunctionWithShortNotFiring(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Family.class.getCanonicalName() + ";" + @@ -342,7 +348,7 @@ public void testComplexGlobalFunctionWithShortNotFiring() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new Family()); @@ -350,17 +356,19 @@ public void testComplexGlobalFunctionWithShortNotFiring() { } - @Test - public void testGlobalOnTypeDeclaration() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalOnTypeDeclaration(RUN_TYPE runType) throws Exception { String str = "declare MyObject end\n" + "global MyObject event;"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); } - @Test - public void testGlobalFunctionWithArrayInput() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalFunctionWithArrayInput(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + InputDataTypes.class.getCanonicalName() + ";" + @@ -384,15 +392,16 @@ public void testGlobalFunctionWithArrayInput() { " update($input);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new InputDataTypes()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGlobalFunctionWithLargeArrayInput() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalFunctionWithLargeArrayInput(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + InputDataTypes.class.getCanonicalName() + ";" + @@ -453,15 +462,16 @@ public void testGlobalFunctionWithLargeArrayInput() { " update($input);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new InputDataTypes()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGlobalInDifferentPackage() throws InstantiationException, IllegalAccessException { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalInDifferentPackage(RUN_TYPE runType) throws InstantiationException, IllegalAccessException { // DROOLS-6657 String def = "package org.drools.reproducer.definitions\n" + @@ -482,7 +492,7 @@ public void testGlobalInDifferentPackage() throws InstantiationException, Illega " globalList.add(\"FOO matched\");\n" + "end\n"; - KieSession ksession = getKieSession( rule, def ); + KieSession ksession = getKieSession(runType, rule, def); KieBase kb = ksession.getKieBase(); assertThat(ksession.fireAllRules()).isEqualTo(0); @@ -502,8 +512,9 @@ public void testGlobalInDifferentPackage() throws InstantiationException, Illega assertThat(globalList.get(0)).isEqualTo("FOO matched"); } - @Test - public void testGenericOnGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void testGenericOnGlobal(RUN_TYPE runType) { // DROOLS-7155 String def = "package org.drools.reproducer\n" + @@ -513,14 +524,15 @@ public void testGenericOnGlobal() { " globalList.add(\"test\");\n" + "end\n"; - KieSession ksession = getKieSession( def ); + KieSession ksession = getKieSession(runType, def); ksession.setGlobal("globalList", new ArrayList()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testWrongGenericOnGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void testWrongGenericOnGlobal(RUN_TYPE runType) { // DROOLS-7155 String def = "package org.drools.reproducer\n" + @@ -530,7 +542,7 @@ public void testWrongGenericOnGlobal() { " globalList.add(\"test\");\n" + "end\n"; - Results results = createKieBuilder(def).getResults(); + Results results = createKieBuilder(runType, def).getResults(); assertThat(results.getMessages(Message.Level.ERROR)).isNotEmpty(); assertThat(results.getMessages(Message.Level.ERROR).stream().map(Message::getText) .anyMatch(s -> s.contains("The method add(Integer) in the type List is not applicable for the arguments (String)"))).isTrue(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GroupByTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GroupByTest.java index 020cbce685e..1adc41e23d6 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GroupByTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GroupByTest.java @@ -25,7 +25,8 @@ import org.drools.model.codegen.execmodel.domain.Parent; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.functions.accumulate.GroupKey; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import org.kie.api.runtime.rule.Match; @@ -49,28 +50,25 @@ public class GroupByTest extends BaseModelTest { - public GroupByTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - public void assertSessionHasProperties(String ruleString, Consumer kieSessionConsumer) { + public void assertSessionHasProperties(RUN_TYPE testRunType, String ruleString, Consumer kieSessionConsumer) { if (testRunType.isExecutableModel()) { - KieSession ksession = getKieSession( ruleString ); + KieSession ksession = getKieSession(testRunType, ruleString); kieSessionConsumer.accept(ksession); } else { assertAll(() -> { - KieSession ksession = getKieSession( "dialect \"java\";\n" + ruleString); + KieSession ksession = getKieSession(testRunType, "dialect \"java\";\n" + ruleString); kieSessionConsumer.accept(ksession); }, () -> { - KieSession ksession = getKieSession( "dialect \"mvel\";\n" + ruleString); + KieSession ksession = getKieSession(testRunType, "dialect \"mvel\";\n" + ruleString); kieSessionConsumer.accept(ksession); }); } } - @Test - public void providedInstance() { + @ParameterizedTest + @MethodSource("parameters") + public void providedInstance(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Map.class.getCanonicalName() + ";\n" + "global Map results;\n" + @@ -83,7 +81,7 @@ public void providedInstance() { " results.put($key, $sumOfAges);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -117,8 +115,9 @@ public void providedInstance() { }); } - @Test - public void testSumPersonAgeGroupByInitialWithAcc() { + @ParameterizedTest + @MethodSource("parameters") + public void testSumPersonAgeGroupByInitialWithAcc(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + GroupKey.class.getCanonicalName() + ";" + @@ -146,7 +145,7 @@ public void testSumPersonAgeGroupByInitialWithAcc() { " results.put($key, $sumOfAges);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -181,8 +180,9 @@ public void testSumPersonAgeGroupByInitialWithAcc() { }); } - @Test - public void testGroupPersonsInitial() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupPersonsInitial(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + List.class.getCanonicalName() + ";" + @@ -194,7 +194,7 @@ public void testGroupPersonsInitial() { " results.add($key);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { List results = new ArrayList<>(); ksession.setGlobal( "results", results ); @@ -229,8 +229,9 @@ public void testGroupPersonsInitial() { }); } - @Test - public void testSumPersonAgeGroupByInitial() { + @ParameterizedTest + @MethodSource("parameters") + public void testSumPersonAgeGroupByInitial(RUN_TYPE runType) { // Note: this appears to be a duplicate of providedInstance String str = "import " + Person.class.getCanonicalName() + ";" + @@ -244,7 +245,7 @@ public void testSumPersonAgeGroupByInitial() { "then\n" + " results.put($key, $sumOfAges);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -279,8 +280,9 @@ public void testSumPersonAgeGroupByInitial() { }); } - @Test - public void testSumPersonAgeGroupByInitialWithBetaFilter() { + @ParameterizedTest + @MethodSource("parameters") + public void testSumPersonAgeGroupByInitialWithBetaFilter(RUN_TYPE runType) { // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = "import " + Person.class.getCanonicalName() + ";" + @@ -295,7 +297,7 @@ public void testSumPersonAgeGroupByInitialWithBetaFilter() { " results.put($key, $sum);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -331,8 +333,9 @@ public void testSumPersonAgeGroupByInitialWithBetaFilter() { }); } - @Test - public void testSumPersonAgeGroupByInitialWithExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testSumPersonAgeGroupByInitialWithExists(RUN_TYPE runType) { // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = "import " + Person.class.getCanonicalName() + ";" + @@ -348,7 +351,7 @@ public void testSumPersonAgeGroupByInitialWithExists() { " results.put($key, $sum);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -405,8 +408,9 @@ public MyType getNested() { } } - @Test - public void testWithNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testWithNull(RUN_TYPE runType) { String str = "import " + MyType.class.getCanonicalName() + ";" + "import " + List.class.getCanonicalName() + ";" + @@ -421,7 +425,7 @@ public void testWithNull() { " result.add($key);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { AtomicInteger mappingFunctionCallCounter = new AtomicInteger(); List result = new ArrayList<>(); ksession.setGlobal("mappingFunctionCallCounter", mappingFunctionCallCounter); @@ -440,8 +444,9 @@ public void testWithNull() { }); } - @Test - public void testWithGroupByAfterExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testWithGroupByAfterExists(RUN_TYPE runType) { String str = "import " + Map.class.getCanonicalName() + ";" + "import " + Math.class.getCanonicalName() + ";" + @@ -454,7 +459,7 @@ public void testWithGroupByAfterExists() { " glob.put($key, $count.intValue());\n" + "end"; - assertSessionHasProperties(str, session -> { + assertSessionHasProperties(runType, str, session -> { Map global = new HashMap<>(); session.setGlobal("glob", global); @@ -470,8 +475,9 @@ public void testWithGroupByAfterExists() { }); } - @Test - public void testWithGroupByAfterExistsWithFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testWithGroupByAfterExistsWithFrom(RUN_TYPE runType) { // Note: this looks exactly the same as testWithGroupByAfterExists String str = "import " + Map.class.getCanonicalName() + ";" + @@ -485,7 +491,7 @@ public void testWithGroupByAfterExistsWithFrom() { " glob.put($key, $count.intValue());\n" + "end"; - assertSessionHasProperties(str, session -> { + assertSessionHasProperties(runType, str, session -> { Map global = new HashMap<>(); session.setGlobal("glob", global); @@ -501,8 +507,9 @@ public void testWithGroupByAfterExistsWithFrom() { }); } - @Test - public void testGroupBy2Vars() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy2Vars(RUN_TYPE runType) { // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = "import " + Person.class.getCanonicalName() + ";" + @@ -516,7 +523,7 @@ public void testGroupBy2Vars() { " results.put($key, $sum);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -560,8 +567,9 @@ public void testGroupBy2Vars() { }); } - @Test - public void testUnexpectedRuleMatch() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnexpectedRuleMatch(RUN_TYPE runType) { String str = "import " + Parent.class.getCanonicalName() + ";" + "import " + Child.class.getCanonicalName() + ";" + @@ -578,7 +586,7 @@ public void testUnexpectedRuleMatch() { " results.add(Arrays.asList($child, $count));\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { List results = new ArrayList(); ksession.setGlobal("results", results); @@ -603,8 +611,9 @@ public void testUnexpectedRuleMatch() { }); } - @Test - public void testCompositeKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testCompositeKey(RUN_TYPE runType) { // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = "import " + Person.class.getCanonicalName() + ";" + @@ -623,7 +632,7 @@ public void testCompositeKey() { " results.put($key1, $sum);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -698,8 +707,9 @@ public String toString() { } } - @Test - public void testTwoExpressionsOnSecondPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoExpressionsOnSecondPattern(RUN_TYPE runType) { // DROOLS-5704 // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = @@ -716,7 +726,7 @@ public void testTwoExpressionsOnSecondPattern() { " results.add($key);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Set results = new LinkedHashSet<>(); ksession.setGlobal("results", results); @@ -730,8 +740,9 @@ public void testTwoExpressionsOnSecondPattern() { }); } - @Test - public void testFromAfterGroupBy() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromAfterGroupBy(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Set.class.getCanonicalName() + ";" + @@ -750,7 +761,7 @@ public void testFromAfterGroupBy() { " typeChecker.accept($remappedKey);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Set results = new LinkedHashSet<>(); ksession.setGlobal("results", results); @@ -768,8 +779,9 @@ public void testFromAfterGroupBy() { }); } - @Test - public void testBindingRemappedAfterGroupBy() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingRemappedAfterGroupBy(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Set.class.getCanonicalName() + ";" + @@ -788,7 +800,7 @@ public void testBindingRemappedAfterGroupBy() { " typeChecker.accept($remappedKey);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Set results = new LinkedHashSet<>(); ksession.setGlobal("results", results); @@ -806,8 +818,9 @@ public void testBindingRemappedAfterGroupBy() { }); } - @Test - public void testGroupByUpdatingKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupByUpdatingKey(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Map.class.getCanonicalName() + ";" + @@ -823,7 +836,7 @@ public void testGroupByUpdatingKey() { " results.put($key, $sumOfAges + $countOfPersons.intValue());" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -851,8 +864,9 @@ public void testGroupByUpdatingKey() { }); } - @Test - public void doesNotRemoveProperly() { + @ParameterizedTest + @MethodSource("parameters") + public void doesNotRemoveProperly(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Set.class.getCanonicalName() + ";" + @@ -867,7 +881,7 @@ public void doesNotRemoveProperly() { " results.add($key);" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Set results = new LinkedHashSet<>(); @@ -911,8 +925,9 @@ public void onUpdateMatch(Match match) { }); } - @Test - public void testTwoGroupBy() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoGroupBy(RUN_TYPE runType) { // DROOLS-5697 // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = @@ -936,7 +951,7 @@ public void testTwoGroupBy() { " results.put($key, $maxOfValues);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -991,8 +1006,9 @@ public void testTwoGroupBy() { }); } - @Test - public void testTwoGroupByUsingBindings() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoGroupByUsingBindings(RUN_TYPE runType) { // DROOLS-5697 // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = @@ -1016,7 +1032,7 @@ public void testTwoGroupByUsingBindings() { " results.put($key, $maxOfValues);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -1089,8 +1105,9 @@ public Object getValue() { } } - @Test - public void testEmptyPatternOnGroupByKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testEmptyPatternOnGroupByKey(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1107,7 +1124,7 @@ public void testEmptyPatternOnGroupByKey() { " results.add($key);" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { List results = new ArrayList(); ksession.setGlobal("results", results); @@ -1122,8 +1139,9 @@ public void testEmptyPatternOnGroupByKey() { }); } - @Test - public void testFilterOnGroupByKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testFilterOnGroupByKey(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1141,7 +1159,7 @@ public void testFilterOnGroupByKey() { " results.add($key);" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { List results = new ArrayList(); ksession.setGlobal("results", results); @@ -1156,8 +1174,9 @@ public void testFilterOnGroupByKey() { }); } - @Test - public void testDecomposedGroupByKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testDecomposedGroupByKey(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1177,7 +1196,7 @@ public void testDecomposedGroupByKey() { " results.add($subkeyB);" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1192,8 +1211,9 @@ public void testDecomposedGroupByKey() { }); } - @Test - public void testDecomposedGroupByKeyAndAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testDecomposedGroupByKeyAndAccumulate(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1215,7 +1235,7 @@ public void testDecomposedGroupByKeyAndAccumulate() { " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1231,8 +1251,9 @@ public void testDecomposedGroupByKeyAndAccumulate() { }); } - @Test - public void testDecomposedGroupByKeyAnd2Accumulates() { + @ParameterizedTest + @MethodSource("parameters") + public void testDecomposedGroupByKeyAnd2Accumulates(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1254,7 +1275,7 @@ public void testDecomposedGroupByKeyAnd2Accumulates() { " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1269,8 +1290,9 @@ public void testDecomposedGroupByKeyAnd2Accumulates() { }); } - @Test - public void testDecomposedGroupByKeyAnd2AccumulatesInConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testDecomposedGroupByKeyAnd2AccumulatesInConsequence(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1288,7 +1310,7 @@ public void testDecomposedGroupByKeyAnd2AccumulatesInConsequence() { " results.add($key);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1301,8 +1323,9 @@ public void testDecomposedGroupByKeyAnd2AccumulatesInConsequence() { }); } - @Test - public void testNestedGroupBy1a() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedGroupBy1a(RUN_TYPE runType) { // DROOLS-6045 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1317,7 +1340,7 @@ public void testNestedGroupBy1a() { " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1329,8 +1352,9 @@ public void testNestedGroupBy1a() { }); } - @Test - public void testNestedGroupBy1b() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedGroupBy1b(RUN_TYPE runType) { // DROOLS-6045 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1345,7 +1369,7 @@ public void testNestedGroupBy1b() { " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1356,8 +1380,9 @@ public void testNestedGroupBy1b() { }); } - @Test - public void testNestedGroupBy2() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedGroupBy2(RUN_TYPE runType) { // DROOLS-6045 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1374,7 +1399,7 @@ public void testNestedGroupBy2() { "then\n" + " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1386,8 +1411,9 @@ public void testNestedGroupBy2() { }); } - @Test - public void testNestedGroupBy3() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedGroupBy3(RUN_TYPE runType) { // DROOLS-6045 // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = @@ -1404,7 +1430,7 @@ public void testNestedGroupBy3() { "then\n" + " results.add($keyOuter);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1417,8 +1443,9 @@ public void testNestedGroupBy3() { }); } - @Test - public void testFilterOnAccumulateResultWithDecomposedGroupByKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testFilterOnAccumulateResultWithDecomposedGroupByKey(RUN_TYPE runType) { // DROOLS-6045 // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = @@ -1441,7 +1468,7 @@ public void testFilterOnAccumulateResultWithDecomposedGroupByKey() { " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1524,8 +1551,9 @@ public void testFilterOnAccumulateResultWithDecomposedGroupByKey() { // } // } - @Test - public void testNestedRewrite() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedRewrite(RUN_TYPE runType) { // DROOLS-5697 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1544,7 +1572,7 @@ public void testNestedRewrite() { " results.add($maxOfValues);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { List results = new ArrayList(); ksession.setGlobal("results", results); 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 f4514a36bde..df52b350958 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,26 +23,24 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +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; public class HalfBinaryTest extends BaseModelTest { - public HalfBinaryTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testHalfBinary() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinary(RUN_TYPE runType) { final String drl1 = "rule R1 when\n" + " Integer(this > 2 && < 5)\n" + "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( 3 ); ksession.insert( 4 ); @@ -50,8 +48,9 @@ public void testHalfBinary() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testHalfBinaryWithParenthesis() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinaryWithParenthesis(RUN_TYPE runType) { // DROOLS-6006 final String drl1 = "rule R1 when\n" + @@ -59,7 +58,7 @@ public void testHalfBinaryWithParenthesis() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( 3 ); ksession.insert( 4 ); @@ -67,8 +66,9 @@ public void testHalfBinaryWithParenthesis() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testHalfBinaryOrWithParenthesis() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinaryOrWithParenthesis(RUN_TYPE runType) { // DROOLS-6006 final String drl1 = "rule R1 when\n" + @@ -76,7 +76,7 @@ public void testHalfBinaryOrWithParenthesis() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( 3 ); ksession.insert( 4 ); @@ -84,8 +84,9 @@ public void testHalfBinaryOrWithParenthesis() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testComplexHalfBinary() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexHalfBinary(RUN_TYPE runType) { // DROOLS-6006 final String drl1 = "rule R1 when\n" + @@ -93,7 +94,7 @@ public void testComplexHalfBinary() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( 3 ); ksession.insert( 4 ); @@ -101,8 +102,9 @@ public void testComplexHalfBinary() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testHalfBinaryOnComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinaryOnComparable(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "rule R1 when\n" + @@ -110,7 +112,7 @@ public void testHalfBinaryOnComparable() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( "B" ); ksession.insert( "D" ); @@ -119,8 +121,9 @@ public void testHalfBinaryOnComparable() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testHalfBinaryOrOnComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinaryOrOnComparable(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "rule R1 when\n" + @@ -128,7 +131,7 @@ public void testHalfBinaryOrOnComparable() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( "B" ); ksession.insert( "D" ); @@ -137,8 +140,9 @@ public void testHalfBinaryOrOnComparable() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testComplexHalfBinaryOnComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexHalfBinaryOnComparable(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "rule R1 when\n" + @@ -146,7 +150,7 @@ public void testComplexHalfBinaryOnComparable() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( "B" ); ksession.insert( "D" ); @@ -155,8 +159,9 @@ public void testComplexHalfBinaryOnComparable() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testComplexHalfBinaryOnComparableField() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexHalfBinaryOnComparableField(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + @@ -165,7 +170,7 @@ public void testComplexHalfBinaryOnComparableField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( new Person("B") ); ksession.insert( new Person("D") ); @@ -174,8 +179,9 @@ public void testComplexHalfBinaryOnComparableField() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testComplexHalfBinaryOnComparableInternalField() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexHalfBinaryOnComparableInternalField(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + @@ -184,7 +190,7 @@ public void testComplexHalfBinaryOnComparableInternalField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); Person b = new Person("B"); b.setAddress(new Address("B")); @@ -202,8 +208,9 @@ public void testComplexHalfBinaryOnComparableInternalField() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testComplexHalfBinaryOnComparableInternalNullSafeField() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexHalfBinaryOnComparableInternalNullSafeField(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + @@ -212,7 +219,7 @@ public void testComplexHalfBinaryOnComparableInternalNullSafeField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); Person a = new Person("A"); a.setAddress(new Address(null)); @@ -233,8 +240,9 @@ public void testComplexHalfBinaryOnComparableInternalNullSafeField() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testHalfBinaryOrAndAmpersand() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinaryOrAndAmpersand(RUN_TYPE runType) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -244,7 +252,7 @@ public void testHalfBinaryOrAndAmpersand() { " result.add($p.getName());\n" + "end\n"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -257,8 +265,9 @@ public void testHalfBinaryOrAndAmpersand() { assertThat(result).containsExactlyInAnyOrder("A", "C"); } - @Test - public void testNestedHalfBinaryOrAndAmpersand() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedHalfBinaryOrAndAmpersand(RUN_TYPE runType) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -268,7 +277,7 @@ public void testNestedHalfBinaryOrAndAmpersand() { " result.add($p.getName());\n" + "end\n"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List result = new ArrayList<>(); ksession.setGlobal("result", result); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HierarchyRulesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HierarchyRulesTest.java index 173f3c1fdbf..5ff5d6627a1 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HierarchyRulesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HierarchyRulesTest.java @@ -18,19 +18,18 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.Test; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -public class HierarchyRulesTest extends BaseModelTest { +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - public HierarchyRulesTest(RUN_TYPE testRunType ) { - super( testRunType ); - } +public class HierarchyRulesTest extends BaseModelTest { - @Test - public void test() { + @ParameterizedTest + @MethodSource("parameters") + public void test(RUN_TYPE runType) { // DROOLS-7470 String str = "rule R1 when \n" + @@ -105,7 +104,7 @@ public void test() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat( ksession.fireAllRules() ).isEqualTo(4); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InTest.java index 04cf9c53038..dafc5be0272 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InTest.java @@ -24,45 +24,45 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Child; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +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; public class InTest extends BaseModelTest { - public InTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testInWithNullFire() { + @ParameterizedTest + @MethodSource("parameters") + public void testInWithNullFire(RUN_TYPE runType) { String str = "import " + Child.class.getCanonicalName() + "; \n" + "rule R when \n" + " $c : Child(parent in (\"Gustav\", \"Alice\", null))\n" + "then \n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Child("Ben", 10)); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testInWithNullNoFire() { + @ParameterizedTest + @MethodSource("parameters") + public void testInWithNullNoFire(RUN_TYPE runType) { String str = "import " + Child.class.getCanonicalName() + "; \n" + "rule R when \n" + " $c : Child(parent in (\"Gustav\", \"Alice\"))\n" + "then \n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Child("Ben", 10)); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testInWithNullComments() { + @ParameterizedTest + @MethodSource("parameters") + public void testInWithNullComments(RUN_TYPE runType) { String str = "import " + Child.class.getCanonicalName() + "; \n" + "global java.util.List results; \n" + "global java.util.List results; \n" + @@ -75,7 +75,7 @@ public void testInWithNullComments() { " results.add($c);\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -88,16 +88,17 @@ public void testInWithNullComments() { assertThat(results).containsExactly(ben); } - @Test - public void testInWithJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testInWithJoin(RUN_TYPE runType) { String str = "import " + Address.class.getCanonicalName() + "; \n" + "rule R when \n" + " $a1: Address($street: street, city in (\"Brno\", \"Milan\", \"Bratislava\")) \n" + " $a2: Address(city in (\"Krakow\", \"Paris\", $a1.city)) \n" + "then \n" + - "end\n"; + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Address("Brno")); ksession.insert(new Address("Milan")); assertThat(ksession.fireAllRules()).isEqualTo(2); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IncrementalCompilationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IncrementalCompilationTest.java index 0908ce636fa..a060f4eef7b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IncrementalCompilationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IncrementalCompilationTest.java @@ -24,7 +24,8 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieModuleModel; @@ -36,9 +37,6 @@ public class IncrementalCompilationTest extends BaseModelTest { - public IncrementalCompilationTest( RUN_TYPE testRunType ) { - super( testRunType ); - } public class Message implements Serializable { private final String value; @@ -52,8 +50,9 @@ public String getValue() { } } - @Test - public void testKJarUpgradeSameAndDifferentSessions() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeSameAndDifferentSessions(RUN_TYPE runType) throws Exception { String drl1 = "package org.drools.incremental\n" + "import " + Message.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -80,7 +79,7 @@ public void testKJarUpgradeSameAndDifferentSessions() throws Exception { // Create an in-memory jar for version 1.0.0 ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-upgrade", "1.0.0" ); - createAndDeployJar( ks, releaseId1, drl1, drl2_1 ); + createAndDeployJar(runType, ks, releaseId1, drl1, drl2_1 ); // Create a session and fire rules KieContainer kc = ks.newKieContainer( releaseId1 ); @@ -90,7 +89,7 @@ public void testKJarUpgradeSameAndDifferentSessions() throws Exception { // Create a new jar for version 1.1.0 ReleaseId releaseId2 = ks.newReleaseId( "org.kie", "test-upgrade", "1.1.0" ); - createAndDeployJar( ks, releaseId2, drl1, drl2_2 ); + createAndDeployJar(runType, ks, releaseId2, drl1, drl2_2 ); // try to update the container to version 1.1.0 kc.updateToVersion( releaseId2 ); @@ -105,8 +104,9 @@ public void testKJarUpgradeSameAndDifferentSessions() throws Exception { assertThat(ksession2.fireAllRules()).isEqualTo(2); } - @Test - public void testKJarUpgradeWithDeclaredType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithDeclaredType(RUN_TYPE runType) throws Exception { String drl1 = "package org.drools.incremental\n" + "declare Message value : String end\n" + "rule Init when then insert(new Message( \"Hello World\" )); end\n" + @@ -141,10 +141,10 @@ public void testKJarUpgradeWithDeclaredType() throws Exception { ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-upgrade", "1.0.0" ); KieModuleModel kieModuleModel = ks.newKieModuleModel(); - if(this.testRunType.isAlphaNetworkCompiler()) { + if(runType.isAlphaNetworkCompiler()) { kieModuleModel.setConfigurationProperty("drools.alphaNetworkCompiler", AlphaNetworkCompilerOption.INMEMORY.toString()); } - createAndDeployJar( ks, kieModuleModel, releaseId1, drl1, drl2_1 ); + createAndDeployJar(runType, ks, kieModuleModel, releaseId1, drl1, drl2_1 ); KieContainer kc = ks.newKieContainer( releaseId1 ); @@ -154,7 +154,7 @@ public void testKJarUpgradeWithDeclaredType() throws Exception { // Create a new jar for version 1.1.0 ReleaseId releaseId2 = ks.newReleaseId( "org.kie", "test-upgrade", "1.1.0" ); - createAndDeployJar( ks, kieModuleModel, releaseId2, drl1, drl2_2 ); + createAndDeployJar(runType, ks, kieModuleModel, releaseId2, drl1, drl2_2 ); // try to update the container to version 1.1.0 kc.updateToVersion( releaseId2 ); @@ -165,7 +165,7 @@ public void testKJarUpgradeWithDeclaredType() throws Exception { // Create a new jar for version 1.2.0 ReleaseId releaseId3 = ks.newReleaseId( "org.kie", "test-upgrade", "1.2.0" ); - createAndDeployJar( ks, kieModuleModel, releaseId3, drl1, drl2_3 ); + createAndDeployJar(runType, ks, kieModuleModel, releaseId3, drl1, drl2_3 ); // try to update the container to version 1.2.0 kc.updateToVersion( releaseId3 ); @@ -178,8 +178,9 @@ public void testKJarUpgradeWithDeclaredType() throws Exception { assertThat(list.get(0)).isEqualTo("Hello World"); } - @Test - public void testKJarUpgradeWithChangedDeclaredType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedDeclaredType(RUN_TYPE runType) throws Exception { String drl1a = "package org.drools.incremental\n" + "declare Message value : String end\n" + "rule Init when then insert(new Message( \"Hello World\" )); end\n" + @@ -202,7 +203,7 @@ public void testKJarUpgradeWithChangedDeclaredType() throws Exception { // Create an in-memory jar for version 1.0.0 ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-upgrade", "1.0.0" ); - createAndDeployJar( ks, releaseId1, drl1a ); + createAndDeployJar(runType, ks, releaseId1, drl1a ); // Create a session and fire rules KieContainer kc = ks.newKieContainer( releaseId1 ); @@ -211,7 +212,7 @@ public void testKJarUpgradeWithChangedDeclaredType() throws Exception { // Create a new jar for version 1.1.0 ReleaseId releaseId2 = ks.newReleaseId( "org.kie", "test-upgrade", "1.1.0" ); - createAndDeployJar( ks, releaseId2, drl1b ); + createAndDeployJar(runType, ks, releaseId2, drl1b ); // try to update the container to version 1.1.0 kc.updateToVersion( releaseId2 ); @@ -224,8 +225,9 @@ public void testKJarUpgradeWithChangedDeclaredType() throws Exception { assertThat(ksession2.fireAllRules()).isEqualTo(2); } - @Test - public void testIdenticalConsequenceButImportChange() { + @ParameterizedTest + @MethodSource("parameters") + public void testIdenticalConsequenceButImportChange(RUN_TYPE runType) { final String drl1 = "package org.drools.test\n" + "import " + Person.class.getCanonicalName() + "\n" + "rule R\n" + @@ -249,7 +251,7 @@ public void testIdenticalConsequenceButImportChange() { final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); - createAndDeployJar(ks, releaseId1, drl1); + createAndDeployJar(runType, ks, releaseId1, drl1); final KieContainer kc = ks.newKieContainer(releaseId1); final KieSession kieSession = kc.newKieSession(); @@ -259,7 +261,7 @@ public void testIdenticalConsequenceButImportChange() { assertThat(kieSession.fireAllRules()).isEqualTo(1); final ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "2.0.0"); - createAndDeployJar(ks, releaseId2, drl2); + createAndDeployJar(runType, ks, releaseId2, drl2); kc.updateToVersion(releaseId2); @@ -270,8 +272,9 @@ public void testIdenticalConsequenceButImportChange() { assertThat(kieSession.fireAllRules()).isEqualTo(1); } - @Test - public void testIdenticalPredicateButImportChange() { + @ParameterizedTest + @MethodSource("parameters") + public void testIdenticalPredicateButImportChange(RUN_TYPE runType) { // This test also verifies LambdaExtractor final String drl1 = "package org.drools.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -296,7 +299,7 @@ public void testIdenticalPredicateButImportChange() { final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); - createAndDeployJar(ks, releaseId1, drl1); + createAndDeployJar(runType, ks, releaseId1, drl1); final KieContainer kc = ks.newKieContainer(releaseId1); final KieSession kieSession = kc.newKieSession(); @@ -306,7 +309,7 @@ public void testIdenticalPredicateButImportChange() { assertThat(kieSession.fireAllRules()).isEqualTo(0); final ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "2.0.0"); - createAndDeployJar(ks, releaseId2, drl2); + createAndDeployJar(runType, ks, releaseId2, drl2); kc.updateToVersion(releaseId2); @@ -317,8 +320,9 @@ public void testIdenticalPredicateButImportChange() { assertThat(kieSession.fireAllRules()).isEqualTo(1); } - @Test - public void testKJarUpgradeWithChangedFunctionForRHSWithoutExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedFunctionForRHSWithoutExternalizeLambda(RUN_TYPE runType) throws Exception { String drl1a = "package org.drools.incremental\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -346,7 +350,7 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithoutExternalizeLambda() t ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model1, releaseId1, drl1a); + createAndDeployJar(runType, ks, model1, releaseId1, drl1a); // Create a session and fire rules KieContainer kc = ks.newKieContainer(releaseId1); @@ -362,7 +366,7 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithoutExternalizeLambda() t ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model2, releaseId2, drl1b); + createAndDeployJar(runType, ks, model2, releaseId2, drl1b); // try to update the container to version 1.1.0 kc.updateToVersion(releaseId2); @@ -382,8 +386,9 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithoutExternalizeLambda() t assertThat(list2).containsExactlyInAnyOrder("Good bye George"); } - @Test - public void testKJarUpgradeWithChangedFunctionForRHSWithExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedFunctionForRHSWithExternalizeLambda(RUN_TYPE runType) throws Exception { String drl1a = "package org.drools.incremental\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -411,7 +416,7 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithExternalizeLambda() thro ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model1, releaseId1, drl1a); + createAndDeployJar(runType, ks, model1, releaseId1, drl1a); // Create a session and fire rules KieContainer kc = ks.newKieContainer(releaseId1); @@ -427,7 +432,7 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithExternalizeLambda() thro ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model2, releaseId2, drl1b); + createAndDeployJar(runType, ks, model2, releaseId2, drl1b); // try to update the container to version 1.1.0 kc.updateToVersion(releaseId2); @@ -447,8 +452,9 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithExternalizeLambda() thro assertThat(list2).containsExactlyInAnyOrder("Good bye George"); } - @Test - public void testKJarUpgradeWithChangedJavaFunctionForRHSWithoutExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedJavaFunctionForRHSWithoutExternalizeLambda(RUN_TYPE runType) throws Exception { String java1 = "package org.drools.test;\n" + "public class MyFunction {\n" + @@ -480,7 +486,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithoutExternalizeLambda ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model1, releaseId1, + createAndDeployJar(runType, ks, model1, releaseId1, new KieFile("src/main/java/org/drools/test/MyFunction.java", java1), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -498,7 +504,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithoutExternalizeLambda ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model2, releaseId2, + createAndDeployJar(runType, ks, model2, releaseId2, new KieFile("src/main/java/org/drools/test/MyFunction.java", java2), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); // try to update the container to version 1.1.0 @@ -519,8 +525,9 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithoutExternalizeLambda assertThat(list2).containsExactlyInAnyOrder("Good bye George"); } - @Test - public void testKJarUpgradeWithChangedJavaFunctionForRHSWithExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedJavaFunctionForRHSWithExternalizeLambda(RUN_TYPE runType) throws Exception { String java1 = "package org.drools.test;\n" + "public class MyFunction {\n" + @@ -552,7 +559,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithExternalizeLambda() ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model1, releaseId1, + createAndDeployJar(runType, ks, model1, releaseId1, new KieFile("src/main/java/org/drools/test/MyFunction.java", java1), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -570,7 +577,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithExternalizeLambda() ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model2, releaseId2, + createAndDeployJar(runType, ks, model2, releaseId2, new KieFile("src/main/java/org/drools/test/MyFunction.java", java2), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -592,8 +599,9 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithExternalizeLambda() assertThat(list2).containsExactlyInAnyOrder("Good bye George"); } - @Test - public void testKJarUpgradeWithChangedFunctionForLHSWithoutExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedFunctionForLHSWithoutExternalizeLambda(RUN_TYPE runType) throws Exception { String drl1a = "package org.drools.incremental\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -621,7 +629,7 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithoutExternalizeLambda() t ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model1, releaseId1, drl1a); + createAndDeployJar(runType, ks, model1, releaseId1, drl1a); // Create a session and fire rules KieContainer kc = ks.newKieContainer(releaseId1); @@ -638,7 +646,7 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithoutExternalizeLambda() t ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model2, releaseId2, drl1b); + createAndDeployJar(runType, ks, model2, releaseId2, drl1b); // try to update the container to version 1.1.0 System.out.println("=== updateToVersion ==="); @@ -660,8 +668,9 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithoutExternalizeLambda() t assertThat(list2).containsExactlyInAnyOrder("John"); } - @Test - public void testKJarUpgradeWithChangedFunctionForLHSWithExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedFunctionForLHSWithExternalizeLambda(RUN_TYPE runType) throws Exception { String drl1a = "package org.drools.incremental\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -689,7 +698,7 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithExternalizeLambda() thro ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model1, releaseId1, drl1a); + createAndDeployJar(runType, ks, model1, releaseId1, drl1a); // Create a session and fire rules KieContainer kc = ks.newKieContainer(releaseId1); @@ -706,7 +715,7 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithExternalizeLambda() thro ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model2, releaseId2, drl1b); + createAndDeployJar(runType, ks, model2, releaseId2, drl1b); // try to update the container to version 1.1.0 System.out.println("=== updateToVersion ==="); @@ -728,8 +737,9 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithExternalizeLambda() thro assertThat(list2).containsExactlyInAnyOrder("John"); } - @Test - public void testKJarUpgradeWithChangedJavaFunctionForLHSWithoutExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedJavaFunctionForLHSWithoutExternalizeLambda(RUN_TYPE runType) throws Exception { String java1 = "package org.drools.test;\n" + "public class MyFunction {\n" + @@ -763,7 +773,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForLHSWithoutExternalizeLambda ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model1, releaseId1, + createAndDeployJar(runType, ks, model1, releaseId1, new KieFile("src/main/java/org/drools/test/MyFunction.java", java1), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -782,7 +792,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForLHSWithoutExternalizeLambda ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model2, releaseId2, + createAndDeployJar(runType, ks, model2, releaseId2, new KieFile("src/main/java/org/drools/test/MyFunction.java", java2), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -806,8 +816,9 @@ public void testKJarUpgradeWithChangedJavaFunctionForLHSWithoutExternalizeLambda assertThat(list2).containsExactlyInAnyOrder("John"); } - @Test - public void testKJarUpgradeWithChangedJavaFunctionForLHSWithExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedJavaFunctionForLHSWithExternalizeLambda(RUN_TYPE runType) throws Exception { String java1 = "package org.drools.test;\n" + "public class MyFunction {\n" + @@ -841,7 +852,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForLHSWithExternalizeLambda() ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model1, releaseId1, + createAndDeployJar(runType, ks, model1, releaseId1, new KieFile("src/main/java/org/drools/test/MyFunction.java", java1), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -860,7 +871,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForLHSWithExternalizeLambda() ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model2, releaseId2, + createAndDeployJar(runType, ks, model2, releaseId2, new KieFile("src/main/java/org/drools/test/MyFunction.java", java2), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IndexTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IndexTest.java index 67b8177bd58..fb7e1e4edd3 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IndexTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IndexTest.java @@ -32,7 +32,8 @@ import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.util.DateUtils; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.rule.Rule; import org.kie.api.runtime.KieSession; @@ -41,12 +42,9 @@ public class IndexTest extends BaseModelTest { - public IndexTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testBetaIndexOnDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexOnDeclaration(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -55,7 +53,7 @@ public void testBetaIndexOnDeclaration() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass( ksession, Person.class ); BetaNode beta = (BetaNode) otn.getObjectSinkPropagator().getSinks()[0]; @@ -68,8 +66,9 @@ public void testBetaIndexOnDeclaration() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBetaIndexWithAccessor() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexWithAccessor(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -78,7 +77,7 @@ public void testBetaIndexWithAccessor() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "test" ); ksession.insert( new Person("Sofia", 4) ); @@ -110,8 +109,9 @@ public Integer getInteger() { } } - @Test - public void testBetaIndexWithImplicitDowncast() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexWithImplicitDowncast(RUN_TYPE runType) { // DROOLS-5614 String str = "import " + ObjectWrapper.class.getCanonicalName() + ";" + @@ -122,7 +122,7 @@ public void testBetaIndexWithImplicitDowncast() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ObjectWrapper( 42 ) ); ksession.insert( new IntegerWrapper( 42 ) ); @@ -130,8 +130,9 @@ public void testBetaIndexWithImplicitDowncast() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaIndexWithDateEqual() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexWithDateEqual(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -147,7 +148,7 @@ public void testAlphaIndexWithDateEqual() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertConstraintType(ksession.getKieBase(), Person.class, "R1", ConstraintTypeOperator.EQUAL); assertConstraintType(ksession.getKieBase(), Person.class, "R2", ConstraintTypeOperator.EQUAL); @@ -160,8 +161,9 @@ public void testAlphaIndexWithDateEqual() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaIndexWithDateRelation() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexWithDateRelation(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -177,7 +179,7 @@ public void testAlphaIndexWithDateRelation() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertConstraintType(ksession.getKieBase(), Person.class, "R1", ConstraintTypeOperator.GREATER_THAN); assertConstraintType(ksession.getKieBase(), Person.class, "R2", ConstraintTypeOperator.LESS_OR_EQUAL); @@ -207,8 +209,9 @@ private void assertConstraintType(KieBase kbase, Class factClass, String rule assertThat(asserted).isTrue(); } - @Test - public void testBetaIndexOn2ValuesOnLeftTuple() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexOn2ValuesOnLeftTuple(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -219,12 +222,12 @@ public void testBetaIndexOn2ValuesOnLeftTuple() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass( ksession, Person.class ); BetaNode beta = (BetaNode) otn.getObjectSinkPropagator().getSinks()[0]; // this beta index is only supported by executable model - assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(this.testRunType.isExecutableModel()); + assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(runType.isExecutableModel()); ksession.insert( 5 ); ksession.insert( "test" ); @@ -233,8 +236,9 @@ public void testBetaIndexOn2ValuesOnLeftTuple() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNoBetaIndexWithThisPropertyOnRight() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoBetaIndexWithThisPropertyOnRight(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -245,7 +249,7 @@ public void testNoBetaIndexWithThisPropertyOnRight() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 5 ); ksession.insert( "test" ); @@ -254,8 +258,9 @@ public void testNoBetaIndexWithThisPropertyOnRight() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNoBetaIndexWithThisOperationOnLeft() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoBetaIndexWithThisOperationOnLeft(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -266,7 +271,7 @@ public void testNoBetaIndexWithThisOperationOnLeft() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 5 ); ksession.insert( "test" ); @@ -275,8 +280,9 @@ public void testNoBetaIndexWithThisOperationOnLeft() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNoBetaIndexWithThisOperationOnLeft2() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoBetaIndexWithThisOperationOnLeft2(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -287,7 +293,7 @@ public void testNoBetaIndexWithThisOperationOnLeft2() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 5 ); ksession.insert( "test" ); @@ -296,8 +302,9 @@ public void testNoBetaIndexWithThisOperationOnLeft2() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNoBetaIndexWithThisMethodInvocationOnLeft() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoBetaIndexWithThisMethodInvocationOnLeft(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + List.class.getCanonicalName() + ";" + @@ -307,12 +314,13 @@ public void testNoBetaIndexWithThisMethodInvocationOnLeft() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBetaIndexOn3ValuesOnLeftTuple() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexOn3ValuesOnLeftTuple(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -324,12 +332,12 @@ public void testBetaIndexOn3ValuesOnLeftTuple() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass( ksession, Person.class ); BetaNode beta = (BetaNode) otn.getObjectSinkPropagator().getSinks()[0]; // this beta index is only supported by executable model - assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(this.testRunType.isExecutableModel()); + assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(runType.isExecutableModel()); ksession.insert( 2L ); ksession.insert( 3 ); @@ -339,8 +347,9 @@ public void testBetaIndexOn3ValuesOnLeftTuple() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBetaIndexOn4ValuesOnLeftTuple() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexOn4ValuesOnLeftTuple(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -353,12 +362,12 @@ public void testBetaIndexOn4ValuesOnLeftTuple() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass( ksession, Person.class ); BetaNode beta = (BetaNode) otn.getObjectSinkPropagator().getSinks()[0]; // this beta index is only supported by executable model - assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(this.testRunType.isExecutableModel()); + assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(runType.isExecutableModel()); ksession.insert( (short)1 ); ksession.insert( 1L ); @@ -369,8 +378,9 @@ public void testBetaIndexOn4ValuesOnLeftTuple() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaIndexHashed() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexHashed(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -386,13 +396,14 @@ public void testAlphaIndexHashed() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertHashIndex(ksession, Person.class, 3); } - @Test - public void testAlphaIndexHashedNonGetter() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexHashedNonGetter(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -408,7 +419,7 @@ public void testAlphaIndexHashedNonGetter() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertHashIndex(ksession, Person.class, 3); } @@ -422,8 +433,9 @@ private void assertHashIndex(KieSession ksession, Class factClass, int expect assertThat(compositeObjectSinkAdapter.getHashedSinkMap().size()).isEqualTo(expectedHashedSinkMapSize); } - @Test - public void testAlphaIndexHashedPrimitiveWrapper() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexHashedPrimitiveWrapper(RUN_TYPE runType) { String str = "import " + Integer.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -439,13 +451,14 @@ public void testAlphaIndexHashedPrimitiveWrapper() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertHashIndex(ksession, Integer.class, 3); } - @Test - public void testAlphaIndexHashedNumberInterface() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexHashedNumberInterface(RUN_TYPE runType) { String str = "import " + Integer.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -461,7 +474,7 @@ public void testAlphaIndexHashedNumberInterface() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertHashIndex(ksession, Number.class, 3); @@ -470,8 +483,9 @@ public void testAlphaIndexHashedNumberInterface() { assertThat(fired).isEqualTo(1); } - @Test - public void testAlphaIndexWithDeclarationInPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexWithDeclarationInPattern(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -481,7 +495,7 @@ public void testAlphaIndexWithDeclarationInPattern() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass(ksession, Person.class); ObjectSink sink = otn.getObjectSinkPropagator().getSinks()[0]; @@ -494,8 +508,9 @@ public void testAlphaIndexWithDeclarationInPattern() { assertThat(fired).isEqualTo(1); } - @Test - public void testAlphaIndexWithDeclarationInPatternWithSameNameProp() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexWithDeclarationInPatternWithSameNameProp(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -506,7 +521,7 @@ public void testAlphaIndexWithDeclarationInPatternWithSameNameProp() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass(ksession, Person.class); ObjectSink sink = otn.getObjectSinkPropagator().getSinks()[0]; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InternalMatchGroupTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InternalMatchGroupTest.java index 01e88262e71..defa110bc45 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InternalMatchGroupTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InternalMatchGroupTest.java @@ -22,7 +22,8 @@ import java.util.List; import org.drools.commands.runtime.rule.ClearActivationGroupCommand; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.command.BatchExecutionCommand; import org.kie.api.command.Command; @@ -39,12 +40,10 @@ public class InternalMatchGroupTest extends OnlyPatternTest { private static final String KIE_SESSION = "ksession1"; private static final String ACTIVATION_GROUP = "first-group"; - public InternalMatchGroupTest(RUN_TYPE testRunType) { - super(testRunType); - } - @Test - public void testClearActivationGroup() { + @ParameterizedTest + @MethodSource("parameters") + public void testClearActivationGroup(RUN_TYPE runType) { // DROOLS-5685 ClearActivationGroup command changed its behaviour String str = "import java.util.List;\n" + "\n" + @@ -75,7 +74,7 @@ public void testClearActivationGroup() { List> commands = new ArrayList>(); - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); KieCommands commandsFactory = KieServices.get().getCommands(); BatchExecutionCommand batchExecution = commandsFactory.newBatchExecution(commands, KIE_SESSION); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBaseBuilderTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBaseBuilderTest.java index eaea5f9930b..fe231cdac2a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBaseBuilderTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBaseBuilderTest.java @@ -22,14 +22,15 @@ import java.util.List; import java.util.UUID; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.drools.compiler.compiler.io.memory.MemoryFileSystem; import org.drools.compiler.kie.builder.impl.KieBuilderImpl; import org.drools.model.Model; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.KieServices; @@ -46,17 +47,13 @@ public class KieBaseBuilderTest extends BaseModelTest { // Only exec-model test - @Parameters(name = "{0}") - public static Object[] params() { - return new Object[]{RUN_TYPE.PATTERN_DSL}; + public static Stream parameters() { + return Stream.of(RUN_TYPE.PATTERN_DSL); } - public KieBaseBuilderTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void createKieBaseWithKnowledgeBuilderConfiguration() { + @ParameterizedTest + @MethodSource("parameters") + public void createKieBaseWithKnowledgeBuilderConfiguration(RUN_TYPE runType) { // DROOLS-7239 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -73,7 +70,7 @@ public void createKieBaseWithKnowledgeBuilderConfiguration() { ReleaseId releaseId = ks.newReleaseId("org.kie", "kjar-test-" + UUID.randomUUID(), "1.0"); KieModuleModel model = ks.newKieModuleModel(); model.setConfigurationProperty(option.getPropertyName(), option.name()); - KieBuilder kieBuilder = createKieBuilder(ks, model, releaseId, toKieFiles(new String[]{str})); + KieBuilder kieBuilder = createKieBuilder(runType, ks, model, releaseId, toKieFiles(new String[]{str})); // 2nd round: Create a kbase with generated classes and PropertySpecificOption.DISABLED KnowledgeBuilderConfiguration knowledgeBuilderConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBuilderTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBuilderTest.java index 6d766f53f52..e36dd7e6db9 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBuilderTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBuilderTest.java @@ -26,7 +26,7 @@ import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.model.codegen.ExecutableModelProject; import org.drools.modelcompiler.constraints.LambdaConstraint; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KjarBuildTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KjarBuildTest.java index 4d663ec33ff..49baf35bde9 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KjarBuildTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KjarBuildTest.java @@ -19,7 +19,7 @@ package org.drools.model.codegen.execmodel; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ListenersTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ListenersTest.java index 3c893c3deb9..6d87f35295c 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ListenersTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ListenersTest.java @@ -21,7 +21,8 @@ import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.event.rule.ObjectDeletedEvent; import org.kie.api.event.rule.ObjectInsertedEvent; import org.kie.api.event.rule.ObjectUpdatedEvent; @@ -32,12 +33,9 @@ public class ListenersTest extends BaseModelTest { - public ListenersTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testInsert() { + @ParameterizedTest + @MethodSource("parameters") + public void testInsert(RUN_TYPE runType) { String str = "rule R\n" + "when\n" + @@ -46,7 +44,7 @@ public void testInsert() { " insert(\"\" + $i);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MapInitializationDrools3800Test.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MapInitializationDrools3800Test.java index d760d2fd8b0..672dc20e7cf 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MapInitializationDrools3800Test.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MapInitializationDrools3800Test.java @@ -21,17 +21,14 @@ import java.util.Map; import java.util.Objects; -import org.junit.Test; +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; public class MapInitializationDrools3800Test extends BaseModelTest { - public MapInitializationDrools3800Test(BaseModelTest.RUN_TYPE testRunType) { - super(testRunType); - } - public static boolean calc(Map params) { return Objects.equals(params.get("src"), params.get("target")); } @@ -57,8 +54,9 @@ public void setResult(String result) { } } - @Test - public void testMapInitialization() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapInitialization(RUN_TYPE runType) { StringBuilder r = new StringBuilder(); r.append("package ").append(getClass().getPackage().getName()).append("\n"); r.append("\n"); @@ -76,7 +74,7 @@ public void testMapInitialization() { r.append(" }").append("\n"); r.append("end").append("\n"); - KieSession ksession = getKieSession(r.toString() ); + KieSession ksession = getKieSession(runType, r.toString()); Fact fact = new Fact(); @@ -88,8 +86,9 @@ public void testMapInitialization() { assertThat(fact.getResult()).isEqualTo("OK"); } - @Test - public void testPropertyReactivityHanging() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityHanging(RUN_TYPE runType) { // DROOLS-3849 String rule = "package " + getClass().getPackage().getName() + "\n" + @@ -107,7 +106,7 @@ public void testPropertyReactivityHanging() { " }\n" + "end"; - KieSession ksession = getKieSession(rule); + KieSession ksession = getKieSession(runType, rule); Fact fact = new Fact(); fact.setName("TEST"); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MaterializedLambdaTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MaterializedLambdaTest.java index eb807e427e5..eb756552f5a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MaterializedLambdaTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MaterializedLambdaTest.java @@ -22,19 +22,17 @@ import java.util.Date; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +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; public class MaterializedLambdaTest extends BaseModelTest { - public MaterializedLambdaTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testMaterializeLambda() { + @ParameterizedTest + @MethodSource("parameters") + public void testMaterializeLambda(RUN_TYPE runType) { String str = "import " + DataType.class.getCanonicalName() + ";\n" + @@ -57,7 +55,7 @@ public void testMaterializeLambda() { " result.setValue(0);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); DataType st = new DataType("FF", "BBB"); DataType st2 = new DataType("FF", "CCC"); @@ -81,8 +79,9 @@ public static void execute(Runnable r) { } // DROOLS-4858 - @Test - public void testMaterializeLambdaWithNested() { + @ParameterizedTest + @MethodSource("parameters") + public void testMaterializeLambdaWithNested(RUN_TYPE runType) { String str = "import " + Executor.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -97,7 +96,7 @@ public void testMaterializeLambdaWithNested() { " });" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(42); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelBuilderImplTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelBuilderImplTest.java index 76adb83215a..90d4bb047e4 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelBuilderImplTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelBuilderImplTest.java @@ -24,8 +24,8 @@ import org.drools.core.reteoo.CoreComponentFactory; import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.PackageDescr; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.kie.api.builder.ReleaseId; import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.util.maven.support.ReleaseIdImpl; @@ -42,7 +42,7 @@ public class ModelBuilderImplTest { private PackageRegistry packageRegistry; private ModelBuilderImpl modelBuilder; - @Before + @BeforeEach public void setup() { internalKnowledgePackage = CoreComponentFactory.get().createKnowledgePackage("apackage"); modelBuilder = new ModelBuilderImpl<>(PackageSources::dumpSources, CONFIGURATION, RELEASE_ID, false); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelSourceClassTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelSourceClassTest.java index 82189b9a4ce..e3438136f67 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelSourceClassTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelSourceClassTest.java @@ -24,15 +24,15 @@ import java.util.Map; import org.drools.compiler.kproject.models.KieBaseModelImpl; - -import static org.assertj.core.api.Assertions.assertThat; import org.drools.compiler.kproject.models.KieModuleModelImpl; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieBaseModel; import org.kie.api.builder.model.KieModuleModel; import org.kie.util.maven.support.ReleaseIdImpl; +import static org.assertj.core.api.Assertions.assertThat; + public class ModelSourceClassTest { diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MultiKieBaseTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MultiKieBaseTest.java index a59086ab697..4f02e0c197f 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MultiKieBaseTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MultiKieBaseTest.java @@ -18,7 +18,6 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieModuleModel; @@ -27,14 +26,14 @@ import static org.assertj.core.api.Assertions.assertThat; -public class MultiKieBaseTest extends BaseModelTest { +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - public MultiKieBaseTest( RUN_TYPE testRunType ) { - super( testRunType ); - } +public class MultiKieBaseTest extends BaseModelTest { - @Test - public void testHelloWorldWithPackagesAnd2KieBases() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testHelloWorldWithPackagesAnd2KieBases(RUN_TYPE runType) throws Exception { String drl1a = "package org.pkg1\n" + "rule R1 when\n" + " $m : String( this == \"Hello World\" )\n" + @@ -69,7 +68,7 @@ public void testHelloWorldWithPackagesAnd2KieBases() throws Exception { // Create an in-memory jar for version 1.0.0 ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-upgrade", "1.0.0" ); - createAndDeployJar( ks, createKieProjectWithPackagesAnd2KieBases(), releaseId1, + createAndDeployJar(runType, ks, createKieProjectWithPackagesAnd2KieBases(), releaseId1, new KieFile( "src/main/resources/org/pkg1/r1.drl", drl1a ), new KieFile( "src/main/resources/org/pkg2/r2.drl", drl2a ) ); @@ -97,7 +96,7 @@ public void testHelloWorldWithPackagesAnd2KieBases() throws Exception { assertThat(ksession2.fireAllRules()).isEqualTo(1); ReleaseId releaseId2 = ks.newReleaseId( "org.kie", "test-upgrade", "1.1.0" ); - createAndDeployJar( ks, createKieProjectWithPackagesAnd2KieBases(), releaseId2, + createAndDeployJar(runType, ks, createKieProjectWithPackagesAnd2KieBases(), releaseId2, new KieFile( "src/main/resources/org/pkg1/r1.drl", drl1a ), new KieFile( "src/main/resources/org/pkg2/r2.drl", drl2b ) ); @@ -122,8 +121,9 @@ private KieModuleModel createKieProjectWithPackagesAnd2KieBases() { return kproj; } - @Test - public void testFoldersVsPackages() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testFoldersVsPackages(RUN_TYPE runType) throws Exception { String drl1 = "//package org.commented1\n" + "package org.pkg1\n" + @@ -166,7 +166,7 @@ public void testFoldersVsPackages() throws Exception { .newKieSessionModel("KSession4"); ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-pkgs", "1.0.0" ); - createAndDeployJar( ks, kproj, releaseId1, + createAndDeployJar(runType, ks, kproj, releaseId1, new KieFile( "src/main/resources/org/pkg1/r1.drl", drl1 ), new KieFile( "src/main/resources/rules/r2.drl", drl2 ) ); @@ -190,8 +190,9 @@ public void testFoldersVsPackages() throws Exception { assertThat(ks4.fireAllRules()).isEqualTo(0); // there is no "rules" package and folder is not relevant } - @Test - public void testDotInKieBaseName() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDotInKieBaseName(RUN_TYPE runType) throws Exception { // DROOLS-5845 String drl1 = "package org.pkg1\n" + @@ -209,7 +210,7 @@ public void testDotInKieBaseName() throws Exception { .newKieSessionModel("Kie.Session"); ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-dor", "1.0.0" ); - createAndDeployJar( ks, kproj, releaseId1, + createAndDeployJar(runType, ks, kproj, releaseId1, new KieFile( "src/main/resources/org/pkg1/r1.drl", drl1 ) ); // Create a session and fire rules @@ -220,8 +221,9 @@ public void testDotInKieBaseName() throws Exception { assertThat(ks2.fireAllRules()).isEqualTo(1); // only rule in org.pkg1 should fire } - @Test - public void testHelloMultiKieBasesWithSharedDeclaredType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testHelloMultiKieBasesWithSharedDeclaredType(RUN_TYPE runType) throws Exception { // DROOLS-6331 String drlType = "package org.pkg.type\n" + @@ -270,7 +272,7 @@ public void testHelloMultiKieBasesWithSharedDeclaredType() throws Exception { // Create an in-memory jar for version 1.0.0 ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-types", "1.0.0" ); - createAndDeployJar( ks, kproj, releaseId1, + createAndDeployJar(runType, ks, kproj, releaseId1, new KieFile( "src/main/resources/org/pkg/type/r0.drl", drlType ), new KieFile( "src/main/resources/org/pkg1/r1.drl", drl1 ), new KieFile( "src/main/resources/org/pkg2/r2.drl", drl2 ), diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectMapTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectMapTest.java index b96dce0a1a4..fdcb919b12a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectMapTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectMapTest.java @@ -22,20 +22,17 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +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; public class MvelDialectMapTest extends BaseModelTest { - public MvelDialectMapTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - - - @Test - public void testMapAccessorWithBind() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessorWithBind(RUN_TYPE runType) { final String drl = "" + "import java.util.*;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -51,7 +48,7 @@ public void testMapAccessorWithBind() { " results.add($i.length());" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -67,8 +64,9 @@ public void testMapAccessorWithBind() { assertThat(results).containsExactly(5); // item1.length() } - @Test - public void testMapAccessorWithBindFieldAccessor() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessorWithBindFieldAccessor(RUN_TYPE runType) { final String drl = "" + "import java.util.*;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -84,7 +82,7 @@ public void testMapAccessorWithBindFieldAccessor() { " results.add($childName.length());" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectTest.java index 087dece997d..90308ac94a0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectTest.java @@ -36,7 +36,8 @@ import org.drools.model.codegen.execmodel.domain.InternationalAddress; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.ValueHolder; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Message; import org.kie.api.builder.Results; import org.kie.api.definition.rule.Rule; @@ -51,12 +52,9 @@ public class MvelDialectTest extends BaseModelTest { - public MvelDialectTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testMVELinsert() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELinsert(RUN_TYPE runType) { String str = "rule R\n" + "dialect \"mvel\"\n" + "when\n" + @@ -66,7 +64,7 @@ public void testMVELinsert() { " insert(\"Hello World\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_47 = ksession.insert(47); ksession.fireAllRules(); @@ -75,8 +73,9 @@ public void testMVELinsert() { assertThat(results.contains("Hello World")).isTrue(); } - @Test - public void testMVELMapSyntax() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELMapSyntax(RUN_TYPE runType) { final String drl = "" + "import java.util.*;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -102,7 +101,7 @@ public void testMVELMapSyntax() { " update(m);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person p = new Person("Luca"); @@ -115,8 +114,9 @@ public void testMVELMapSyntax() { assertThat(itemsString.keySet().size()).isEqualTo(4); } - @Test - public void testMVELmodify() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELmodify(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R\n" + "dialect \"mvel\"\n" + @@ -126,7 +126,7 @@ public void testMVELmodify() { " modify($p) { setAge(1); }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Matteo", 47)); ksession.fireAllRules(); @@ -136,8 +136,9 @@ public void testMVELmodify() { results.forEach(System.out::println); } - @Test - public void testMVELmultiple() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELmultiple(RUN_TYPE runType) { String str = "package mypackage;" + "dialect \"mvel\"\n" + // MVEL dialect defined at package level. "import " + Person.class.getCanonicalName() + ";\n" + @@ -164,7 +165,7 @@ public void testMVELmultiple() { " retract($s)" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_47 = ksession.insert(47); ksession.fireAllRules(); @@ -175,8 +176,9 @@ public void testMVELmultiple() { assertThat(results.contains("Modified person age to 1 for: Matteo")).isTrue(); } - @Test - public void testMVELmultipleStatements() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELmultipleStatements(RUN_TYPE runType) { String str = "import " + Person.class.getPackage().getName() + ".*;\n" + // keep the package.* in order for Address to be resolvable in the RHS. "rule R\n" + @@ -188,7 +190,7 @@ public void testMVELmultipleStatements() { " insert(a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Matteo", 47)); ksession.fireAllRules(); @@ -208,8 +210,9 @@ public static class TempDecl8 {} public static class TempDecl9 {} public static class TempDecl10 {} - @Test - public void testMVEL10declarations() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVEL10declarations(RUN_TYPE runType) { String str = "\n" + "import " + TempDecl1.class.getCanonicalName() + ";\n" + "import " + TempDecl2.class.getCanonicalName() + ";\n" + @@ -238,7 +241,7 @@ public void testMVEL10declarations() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new TempDecl1()); ksession.insert(new TempDecl2()); @@ -256,8 +259,9 @@ public void testMVEL10declarations() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testMVEL10declarationsBis() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVEL10declarationsBis(RUN_TYPE runType) { String str = "\n" + "import " + TempDecl1.class.getCanonicalName() + ";\n" + "import " + TempDecl2.class.getCanonicalName() + ";\n" + @@ -301,7 +305,7 @@ public void testMVEL10declarationsBis() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -309,8 +313,9 @@ public void testMVEL10declarationsBis() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testMvelFunctionWithClassArg() { + @ParameterizedTest + @MethodSource("parameters") + public void testMvelFunctionWithClassArg(RUN_TYPE runType) { final String drl = "package org.drools.compiler.integrationtests.drl; \n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -333,7 +338,7 @@ public void testMvelFunctionWithClassArg() { " value.append( getFieldValue($bean) ); \n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); try { final StringBuilder sb = new StringBuilder(); @@ -346,8 +351,9 @@ public void testMvelFunctionWithClassArg() { } } - @Test - public void testMvelFunctionWithDeclaredTypeArg() { + @ParameterizedTest + @MethodSource("parameters") + public void testMvelFunctionWithDeclaredTypeArg(RUN_TYPE runType) { final String drl = "package org.drools.compiler.integrationtests.drl; \n" + "dialect \"mvel\"\n" + @@ -372,7 +378,7 @@ public void testMvelFunctionWithDeclaredTypeArg() { " value.append( getFieldValue($bean) ); \n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); try { final StringBuilder sb = new StringBuilder(); @@ -385,8 +391,9 @@ public void testMvelFunctionWithDeclaredTypeArg() { } } - @Test - public void testMultiDrlWithSamePackageMvel() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiDrlWithSamePackageMvel(RUN_TYPE runType) throws Exception { // DROOLS-3508 String drl1 = "package org.pkg\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -402,7 +409,7 @@ public void testMultiDrlWithSamePackageMvel() throws Exception { " update($p);\n" + "end\n"; - KieSession ksession = getKieSession(drl1, drl2); + KieSession ksession = getKieSession(runType, drl1, drl2); Person john = new Person("John", 24); ksession.insert(john); @@ -410,8 +417,9 @@ public void testMultiDrlWithSamePackageMvel() throws Exception { assertThat(john.getAge()).isEqualTo(1); } - @Test - public void testMVELNonExistingMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELNonExistingMethod(RUN_TYPE runType) { // DROOLS-3559 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -423,12 +431,13 @@ public void testMVELNonExistingMethod() { " modify($p) {likes = nonExistingMethod()};\n" + "end"; - Results results = createKieBuilder( drl ).getResults(); + Results results = createKieBuilder(runType, drl).getResults(); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void testBinaryOperationOnBigDecimal() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBinaryOperationOnBigDecimal(RUN_TYPE runType) throws Exception { // RHDM-1421 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -440,7 +449,7 @@ public void testBinaryOperationOnBigDecimal() throws Exception { " $p.money = $p.money + 50000;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -450,8 +459,9 @@ public void testBinaryOperationOnBigDecimal() throws Exception { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 120000 )); } - @Test - public void testAdditionMultiplication() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAdditionMultiplication(RUN_TYPE runType) throws Exception { // DROOLS-6089 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -466,7 +476,7 @@ public void testAdditionMultiplication() throws Exception { " $p.money = $p.money + (bd1.multiply(bd2));" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -476,8 +486,9 @@ public void testAdditionMultiplication() throws Exception { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 70200 )); } - @Test - public void testBigDecimalModuloConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalModuloConsequence(RUN_TYPE runType) { // DROOLS-5959 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -493,7 +504,7 @@ public void testBigDecimalModuloConsequence() { " results.add(moduloPromotedToBigDecimal);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -507,8 +518,9 @@ public void testBigDecimalModuloConsequence() { assertThat(results).containsExactly(valueOf(1), valueOf(2)); } - @Test - public void testBigDecimalModulo() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalModulo(RUN_TYPE runType) { // DROOLS-5959 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -521,7 +533,7 @@ public void testBigDecimalModulo() { " results.add($m);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -539,8 +551,9 @@ public void testBigDecimalModulo() { assertThat(results.iterator().next()).isEqualTo(new BigDecimal( 70000 )); } - @Test - public void testBigDecimalModuloBetweenFields() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalModuloBetweenFields(RUN_TYPE runType) { // DROOLS-5959 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -553,7 +566,7 @@ public void testBigDecimalModuloBetweenFields() { " results.add($m);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -571,8 +584,9 @@ public void testBigDecimalModuloBetweenFields() { assertThat(results.iterator().next()).isEqualTo(new BigDecimal( 80 )); } - @Test - public void testBigDecimalPatternWithString() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalPatternWithString(RUN_TYPE runType) { // DROOLS-6356 // DROOLS-6361 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -593,7 +607,7 @@ public void testBigDecimalPatternWithString() { " $p.name = 144B;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -612,8 +626,9 @@ public void testBigDecimalPatternWithString() { assertThat(results.iterator().next().getName()).isEqualTo("144"); } - @Test - public void testBigDecimalAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalAccumulate(RUN_TYPE runType) { // DROOLS-6366 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -628,7 +643,7 @@ public void testBigDecimalAccumulate() { " results.add($john);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -646,8 +661,9 @@ public void testBigDecimalAccumulate() { assertThat(results).containsExactly(john); } - @Test - public void testBigDecimalAccumulateWithFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalAccumulateWithFrom(RUN_TYPE runType) { // DROOLS-6366 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -662,7 +678,7 @@ public void testBigDecimalAccumulateWithFrom() { " results.add($john);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -680,8 +696,9 @@ public void testBigDecimalAccumulateWithFrom() { assertThat(results).containsExactly(john); } - @Test - public void testCompoundOperatorBigDecimalConstant() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompoundOperatorBigDecimalConstant(RUN_TYPE runType) throws Exception { // DROOLS-5894 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -700,7 +717,7 @@ public void testCompoundOperatorBigDecimalConstant() throws Exception { " $p.money = result;" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -710,8 +727,9 @@ public void testCompoundOperatorBigDecimalConstant() throws Exception { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 400000 )); } - @Test - public void testCompoundOperatorBigDecimalConstantWithoutLiterals() { + @ParameterizedTest + @MethodSource("parameters") + public void testCompoundOperatorBigDecimalConstantWithoutLiterals(RUN_TYPE runType) { // DROOLS-5894 // DROOLS-5901 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -738,7 +756,7 @@ public void testCompoundOperatorBigDecimalConstantWithoutLiterals() { " $p.money = result;" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -748,8 +766,9 @@ public void testCompoundOperatorBigDecimalConstantWithoutLiterals() { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 0 )); } - @Test - public void testArithmeticOperationsOnBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testArithmeticOperationsOnBigDecimal(RUN_TYPE runType) { String drl = "import " + Person.class.getCanonicalName() + "\n" + "import " + BigDecimal.class.getCanonicalName() + "\n" + @@ -762,7 +781,7 @@ public void testArithmeticOperationsOnBigDecimal() { " $p.money = operation;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -773,8 +792,9 @@ public void testArithmeticOperationsOnBigDecimal() { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 7002 )); } - @Test - public void testCompoundOperatorOnfield() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompoundOperatorOnfield(RUN_TYPE runType) throws Exception { // DROOLS-5895 String drl = @@ -787,7 +807,7 @@ public void testCompoundOperatorOnfield() throws Exception { " $p.money += $p.money;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -797,8 +817,9 @@ public void testCompoundOperatorOnfield() throws Exception { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 140000 )); } - @Test - public void testModifyOnBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyOnBigDecimal(RUN_TYPE runType) { // DROOLS-5889 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -815,7 +836,7 @@ public void testModifyOnBigDecimal() { " list.add(\"after \" + $p + \", money = \" + $p.money);" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); ArrayList logMessages = new ArrayList<>(); ksession.setGlobal("list", logMessages); @@ -831,8 +852,9 @@ public void testModifyOnBigDecimal() { "after John, money = 30000"); } - @Test - public void testModifyOnBigDecimalWithLiteral() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyOnBigDecimalWithLiteral(RUN_TYPE runType) { // DROOLS-5891 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -846,7 +868,7 @@ public void testModifyOnBigDecimalWithLiteral() { " } " + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -860,8 +882,9 @@ public void testModifyOnBigDecimalWithLiteral() { assertThat(leonardo.getMoney()).isEqualTo(new BigDecimal( 500 )); } - @Test - public void testBinaryOperationOnInteger() { + @ParameterizedTest + @MethodSource("parameters") + public void testBinaryOperationOnInteger(RUN_TYPE runType) { // RHDM-1421 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -873,7 +896,7 @@ public void testBinaryOperationOnInteger() { " $p.salary = $p.salary + 50000;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setSalary( 70000 ); @@ -883,8 +906,9 @@ public void testBinaryOperationOnInteger() { assertThat((int) john.getSalary()).isEqualTo(120000); } - @Test - public void testSetOnInteger() { + @ParameterizedTest + @MethodSource("parameters") + public void testSetOnInteger(RUN_TYPE runType) { // RHDM-1421 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -896,7 +920,7 @@ public void testSetOnInteger() { " $p.salary = 50000;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setSalary( 70000 ); @@ -906,8 +930,9 @@ public void testSetOnInteger() { assertThat((int) john.getSalary()).isEqualTo(50000); } - @Test - public void testCollectSubtypeInConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testCollectSubtypeInConsequence(RUN_TYPE runType) { // DROOLS-5887 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -923,7 +948,7 @@ public void testCollectSubtypeInConsequence() { " }\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List names = new ArrayList<>(); ksession.setGlobal("names", names); @@ -938,8 +963,9 @@ public void testCollectSubtypeInConsequence() { assertThat(names).containsExactlyInAnyOrder("Mario", "Luca", "Leonardo"); } - @Test - public void testCollectSubtypeInConsequenceNested() { + @ParameterizedTest + @MethodSource("parameters") + public void testCollectSubtypeInConsequenceNested(RUN_TYPE runType) { // DROOLS-5887 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -961,7 +987,7 @@ public void testCollectSubtypeInConsequenceNested() { " }\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List names = new ArrayList<>(); ksession.setGlobal("names", names); @@ -984,8 +1010,9 @@ public void testCollectSubtypeInConsequenceNested() { assertThat(addresses).contains("Milan"); } - @Test - public void testSetOnMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testSetOnMvel(RUN_TYPE runType) { // RHDM-1550 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -998,7 +1025,7 @@ public void testSetOnMvel() { ");\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person mario = new Person(); ksession.insert( mario ); @@ -1008,8 +1035,9 @@ public void testSetOnMvel() { assertThat(mario.getAge()).isEqualTo(46); } - @Test - public void testCompoundOperator() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompoundOperator(RUN_TYPE runType) throws Exception { // DROOLS-5894 // DROOLS-5901 // DROOLS-5897 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -1040,7 +1068,7 @@ public void testCompoundOperator() throws Exception { " $p.money -= intVar;\n" + // 0 "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -1050,8 +1078,9 @@ public void testCompoundOperator() throws Exception { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 0 )); } - @Test - public void testKcontext() { + @ParameterizedTest + @MethodSource("parameters") + public void testKcontext(RUN_TYPE runType) { String str = "global java.util.List result;" + "rule R\n" + @@ -1062,7 +1091,7 @@ public void testKcontext() { " result.add(kcontext.getRule().getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1072,8 +1101,9 @@ public void testKcontext() { assertThat(result.contains("R")).isTrue(); } - @Test - public void testLineBreakAtTheEndOfStatementWithoutSemicolon() { + @ParameterizedTest + @MethodSource("parameters") + public void testLineBreakAtTheEndOfStatementWithoutSemicolon(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -1087,7 +1117,7 @@ public void testLineBreakAtTheEndOfStatementWithoutSemicolon() { " insert(p2);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -1096,8 +1126,9 @@ public void testLineBreakAtTheEndOfStatementWithoutSemicolon() { assertThat(fired).isEqualTo(1); } - @Test - public void testSetNullInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testSetNullInModify(RUN_TYPE runType) { // RHDM-1713 String str = "dialect \"mvel\"\n" + @@ -1112,15 +1143,16 @@ public void testSetNullInModify() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 47 ); ksession.insert( me ); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testSetSubclassInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testSetSubclassInModify(RUN_TYPE runType) { // RHDM-1713 String str = "dialect \"mvel\"\n" + @@ -1136,15 +1168,16 @@ public void testSetSubclassInModify() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 47 ); ksession.insert( me ); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testForEachAccessor() { + @ParameterizedTest + @MethodSource("parameters") + public void testForEachAccessor(RUN_TYPE runType) { // DROOLS-6298 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1160,7 +1193,7 @@ public void testForEachAccessor() { "}\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1175,8 +1208,9 @@ public void testForEachAccessor() { assertThat(results).containsOnly("Address"); } - @Test - public void testBigDecimalPromotionUsedAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalPromotionUsedAsArgument(RUN_TYPE runType) { // DROOLS-6362 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1219,7 +1253,7 @@ public void testBigDecimalPromotionUsedAsArgument() { "}\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1243,8 +1277,9 @@ public static BigDecimal bigDecimalFunc( BigDecimal bd){ return new BigDecimal(bd.toString()); } - @Test - public void testBigDecimalPromotionWithExternalFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalPromotionWithExternalFunction(RUN_TYPE runType) { // DROOLS-6410 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1266,7 +1301,7 @@ public void testBigDecimalPromotionWithExternalFunction() { "results.add(bigDecimalFunc($bd) * 100 + 12);\n" + // 101212 "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1281,8 +1316,9 @@ public void testBigDecimalPromotionWithExternalFunction() { assertThat(results).containsExactly(valueOf(1012), valueOf(1012), valueOf(1012), valueOf(101212)); } - @Test - public void testBigDecimalPromotionUsingDefinedFunctionAndDeclaredType() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalPromotionUsingDefinedFunctionAndDeclaredType(RUN_TYPE runType) { // DROOLS-6362 String str = "package com.sample\n" + "import " + Person.class.getName() + ";\n" + @@ -1316,7 +1352,7 @@ public void testBigDecimalPromotionUsingDefinedFunctionAndDeclaredType() { "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1332,8 +1368,9 @@ public void testBigDecimalPromotionUsingDefinedFunctionAndDeclaredType() { assertThat(results).containsExactly("John"); } - @Test - public void testMVELMapRHSGetAndAssign() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELMapRHSGetAndAssign(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1346,7 +1383,7 @@ public void testMVELMapRHSGetAndAssign() { " result.add(i);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1357,8 +1394,9 @@ public void testMVELMapRHSGetAndAssign() { assertThat(result).containsExactly(100); } - @Test - public void testRHSMapGetAsParam() { + @ParameterizedTest + @MethodSource("parameters") + public void testRHSMapGetAsParam(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1370,7 +1408,7 @@ public void testRHSMapGetAsParam() { " result.add($p.itemsString[$name]);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1381,8 +1419,9 @@ public void testRHSMapGetAsParam() { assertThat(result).containsExactly("OK"); } - @Test - public void testRHSMapNestedProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testRHSMapNestedProperty(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1394,7 +1433,7 @@ public void testRHSMapNestedProperty() { " result.add($p.childrenMap[$name].age);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1407,8 +1446,9 @@ public void testRHSMapNestedProperty() { assertThat(result).containsExactly(5); } - @Test - public void testRHSListNestedProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testRHSListNestedProperty(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1420,7 +1460,7 @@ public void testRHSListNestedProperty() { " result.add($p.addresses[$age].city);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1433,8 +1473,9 @@ public void testRHSListNestedProperty() { assertThat(result).containsExactly("London"); } - @Test - public void testRHSMapMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testRHSMapMethod(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1446,7 +1487,7 @@ public void testRHSMapMethod() { " result.add($p.itemsString.size);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1457,8 +1498,9 @@ public void testRHSMapMethod() { assertThat(result).containsExactly(1); } - @Test - public void testMVELBigIntegerLiteralRHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELBigIntegerLiteralRHS(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R\n" + @@ -1469,7 +1511,7 @@ public void testMVELBigIntegerLiteralRHS() { " $p.setAgeInSeconds(10000I);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person(); ksession.insert(p); @@ -1478,8 +1520,9 @@ public void testMVELBigIntegerLiteralRHS() { assertThat(p.getAgeInSeconds().equals(new BigInteger("10000"))).isTrue(); } - @Test - public void testMVELBigDecimalLiteralRHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELBigDecimalLiteralRHS(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R\n" + @@ -1490,7 +1533,7 @@ public void testMVELBigDecimalLiteralRHS() { " $p.setMoney(10000B);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person(); ksession.insert(p); @@ -1499,8 +1542,9 @@ public void testMVELBigDecimalLiteralRHS() { assertThat(p.getMoney().equals(new BigDecimal("10000"))).isTrue(); } - @Test - public void testMVELBigIntegerLiteralLHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELBigIntegerLiteralLHS(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R\n" + @@ -1510,7 +1554,7 @@ public void testMVELBigIntegerLiteralLHS() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person(); p.setAgeInSeconds(new BigInteger("10000")); @@ -1520,8 +1564,9 @@ public void testMVELBigIntegerLiteralLHS() { assertThat(fired).isEqualTo(1); } - @Test - public void testMVELModifyPropMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELModifyPropMethodCall(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R\n" + @@ -1535,7 +1580,7 @@ public void testMVELModifyPropMethodCall() { " }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John"); List
addresses = new ArrayList<>(); @@ -1549,8 +1594,9 @@ public void testMVELModifyPropMethodCall() { assertThat(fired).isEqualTo(1); } - @Test - public void assign_primitiveBooleanProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void assign_primitiveBooleanProperty(RUN_TYPE runType) { // DROOLS-7250 String str = "package com.example.reproducer\n" + "import " + ValueHolder.class.getCanonicalName() + ";\n" + @@ -1562,7 +1608,7 @@ public void assign_primitiveBooleanProperty() { " $holder.primitiveBooleanValue = true;\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ValueHolder holder = new ValueHolder(); holder.setPrimitiveBooleanValue(false); @@ -1572,8 +1618,9 @@ public void assign_primitiveBooleanProperty() { assertThat(holder.isPrimitiveBooleanValue()).isTrue(); } - @Test - public void assign_wrapperBooleanProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void assign_wrapperBooleanProperty(RUN_TYPE runType) { // DROOLS-7250 String str = "package com.example.reproducer\n" + "import " + ValueHolder.class.getCanonicalName() + ";\n" + @@ -1585,7 +1632,7 @@ public void assign_wrapperBooleanProperty() { " $holder.wrapperBooleanValue = true;\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ValueHolder holder = new ValueHolder(); holder.setWrapperBooleanValue(false); @@ -1595,7 +1642,7 @@ public void assign_wrapperBooleanProperty() { assertThat(holder.getWrapperBooleanValue()).isTrue(); } - public void assign_nestedProperty() { + public void assign_nestedProperty(RUN_TYPE runType) { // DROOLS-7195 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1607,7 +1654,7 @@ public void assign_nestedProperty() { " $p.address.city = \"Tokyo\";\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John"); p.setAddress(new Address("London")); @@ -1617,8 +1664,9 @@ public void assign_nestedProperty() { assertThat(p.getAddress().getCity()).isEqualTo("Tokyo"); } - @Test - public void assign_nestedPropertyInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void assign_nestedPropertyInModify(RUN_TYPE runType) { // DROOLS-7195 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1632,7 +1680,7 @@ public void assign_nestedPropertyInModify() { " }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John"); p.setAddress(new Address("London")); @@ -1642,8 +1690,9 @@ public void assign_nestedPropertyInModify() { assertThat(p.getAddress().getCity()).isEqualTo("Tokyo"); } - @Test - public void setter_nestedPropertyInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void setter_nestedPropertyInModify(RUN_TYPE runType) { // DROOLS-7195 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1657,7 +1706,7 @@ public void setter_nestedPropertyInModify() { " }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John"); p.setAddress(new Address("London")); @@ -1667,8 +1716,9 @@ public void setter_nestedPropertyInModify() { assertThat(p.getAddress().getCity()).isEqualTo("Tokyo"); } - @Test - public void assign_deepNestedPropertyInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void assign_deepNestedPropertyInModify(RUN_TYPE runType) { // DROOLS-7195 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1682,7 +1732,7 @@ public void assign_deepNestedPropertyInModify() { " }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person person = new Person("John"); Address address = new Address("London"); @@ -1696,8 +1746,9 @@ public void assign_deepNestedPropertyInModify() { assertThat(person.getAddress().getVisitorCounter().getValue()).isEqualTo(1); } - @Test - public void setter_deepNestedPropertyInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void setter_deepNestedPropertyInModify(RUN_TYPE runType) { // DROOLS-7195 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1711,7 +1762,7 @@ public void setter_deepNestedPropertyInModify() { " }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person person = new Person("John"); Address address = new Address("London"); @@ -1725,8 +1776,9 @@ public void setter_deepNestedPropertyInModify() { assertThat(person.getAddress().getVisitorCounter().getValue()).isEqualTo(1); } - @Test - public void drools_workingMemory_setGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void drools_workingMemory_setGlobal(RUN_TYPE runType) { // DROOLS-7338 String str = "package com.example.reproducer\n" + "import " + Logger.class.getCanonicalName() + ";\n" + @@ -1738,7 +1790,7 @@ public void drools_workingMemory_setGlobal() { " drools.workingMemory.setGlobal(\"logger\", org.slf4j.LoggerFactory.getLogger(getClass()));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -1746,8 +1798,9 @@ public void drools_workingMemory_setGlobal() { assertThat(logger).isInstanceOf(Logger.class); } - @Test - public void drools_fieldAccess() { + @ParameterizedTest + @MethodSource("parameters") + public void drools_fieldAccess(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "global java.util.Map results;\n" + "rule R\n" + @@ -1762,7 +1815,7 @@ public void drools_fieldAccess() { " results.put(\"kieRuntime\", drools.kieRuntime);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Map results = new HashMap<>(); ksession.setGlobal("results", results); @@ -1776,8 +1829,9 @@ public void drools_fieldAccess() { assertThat(results.get("kieRuntime")).isInstanceOf(KieRuntime.class); } - @Test - public void integerToBigDecimalBindVariableCoercion_shouldNotCoerceToInteger() { + @ParameterizedTest + @MethodSource("parameters") + public void integerToBigDecimalBindVariableCoercion_shouldNotCoerceToInteger(RUN_TYPE runType) { // DROOLS-7540 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1791,7 +1845,7 @@ public void integerToBigDecimalBindVariableCoercion_shouldNotCoerceToInteger() { " results.add($money);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1804,8 +1858,9 @@ public void integerToBigDecimalBindVariableCoercion_shouldNotCoerceToInteger() { assertThat(results).contains(new BigDecimal("5")); } - @Test - public void integerToBigDecimalVariableCoercionTwice_shouldNotCoerceToInteger() { + @ParameterizedTest + @MethodSource("parameters") + public void integerToBigDecimalVariableCoercionTwice_shouldNotCoerceToInteger(RUN_TYPE runType) { // DROOLS-7540 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1821,7 +1876,7 @@ public void integerToBigDecimalVariableCoercionTwice_shouldNotCoerceToInteger() " results.add($var1);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1834,8 +1889,9 @@ public void integerToBigDecimalVariableCoercionTwice_shouldNotCoerceToInteger() assertThat(results).contains(new BigDecimal("5")); } - @Test - public void integerToBigDecimalBindVariableCoercionAndAddition_shouldNotThrowClassCastException() { + @ParameterizedTest + @MethodSource("parameters") + public void integerToBigDecimalBindVariableCoercionAndAddition_shouldNotThrowClassCastException(RUN_TYPE runType) { // DROOLS-7540 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1850,7 +1906,7 @@ public void integerToBigDecimalBindVariableCoercionAndAddition_shouldNotThrowCla " results.add($total);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1863,8 +1919,9 @@ public void integerToBigDecimalBindVariableCoercionAndAddition_shouldNotThrowCla assertThat(results).contains(new BigDecimal("15")); } - @Test - public void integerToBigDecimalVaribleSetFromBindVariableCoercionAndAddition_shouldNotThrowClassCastException() { + @ParameterizedTest + @MethodSource("parameters") + public void integerToBigDecimalVaribleSetFromBindVariableCoercionAndAddition_shouldNotThrowClassCastException(RUN_TYPE runType) { // DROOLS-7540 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1882,7 +1939,7 @@ public void integerToBigDecimalVaribleSetFromBindVariableCoercionAndAddition_sho " results.add($total);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); 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 9aa6b4fb81c..9986cba4046 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,7 +24,8 @@ import java.util.Map; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Message; import org.kie.api.builder.Results; import org.kie.api.runtime.KieSession; @@ -34,47 +35,46 @@ public class MvelOperatorsTest extends BaseModelTest { - public MvelOperatorsTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testIn() { + @ParameterizedTest + @MethodSource("parameters") + public void testIn(RUN_TYPE runType) { String str = "rule R when\n" + " String(this in (\"a\", \"b\"))" + "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "b" ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStr() { + @ParameterizedTest + @MethodSource("parameters") + public void testStr(RUN_TYPE runType) { String str = "rule R when\n" + " String(this str[startsWith] \"M\")" + "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStrNot() { + @ParameterizedTest + @MethodSource("parameters") + public void testStrNot(RUN_TYPE runType) { String str = "rule R when\n" + " String(this not str[startsWith] \"M\")" + "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); ksession.insert( "Luca" ); @@ -82,15 +82,16 @@ public void testStrNot() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testStrHalf() { + @ParameterizedTest + @MethodSource("parameters") + public void testStrHalf(RUN_TYPE runType) { String str = "rule R when\n" + " String(this str[startsWith] \"M\" || str[endsWith] \"a\" || str[length] 10)"+ "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); ksession.insert( "Luca" ); @@ -99,15 +100,16 @@ public void testStrHalf() { assertThat(ksession.fireAllRules()).isEqualTo(3); } - @Test - public void testStrHalfOrAndAmpersand() { + @ParameterizedTest + @MethodSource("parameters") + public void testStrHalfOrAndAmpersand(RUN_TYPE runType) { String str = "rule R when\n" + " String(this str[startsWith] \"M\" || str[endsWith] \"a\" && str[length] 4)"+ "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); ksession.insert( "Luca" ); @@ -116,8 +118,9 @@ public void testStrHalfOrAndAmpersand() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testRange() { + @ParameterizedTest + @MethodSource("parameters") + public void testRange(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -127,7 +130,7 @@ public void testRange() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -142,8 +145,9 @@ public void testRange() { assertThat(list.containsAll(asList("Mark", "Edson"))).isTrue(); } - @Test - public void testExcludedRange() { + @ParameterizedTest + @MethodSource("parameters") + public void testExcludedRange(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -153,7 +157,7 @@ public void testExcludedRange() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -168,8 +172,9 @@ public void testExcludedRange() { assertThat(list.containsAll(asList("Luca", "Mario"))).isTrue(); } - @Test - public void testBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -179,7 +184,7 @@ public void testBinding() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -192,22 +197,24 @@ public void testBinding() { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testMatches() { + @ParameterizedTest + @MethodSource("parameters") + public void testMatches(RUN_TYPE runType) { String str = "rule R when\n" + " String(this matches \"\\\\w\")" + "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "b" ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testExcludes() { + @ParameterizedTest + @MethodSource("parameters") + public void testExcludes(RUN_TYPE runType) { String str = "import java.util.List\n" + "rule R when\n" + @@ -215,15 +222,16 @@ public void testExcludes() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( asList("ciao", "test") ); assertThat(ksession.fireAllRules()).isEqualTo(0); ksession.insert( asList("hello", "world") ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNotContains() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotContains(RUN_TYPE runType) { String str = "import java.util.List\n" + "rule R when\n" + @@ -231,15 +239,16 @@ public void testNotContains() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( asList("ciao", "test") ); assertThat(ksession.fireAllRules()).isEqualTo(0); ksession.insert( asList("hello", "world") ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStartsWithWithChar() { + @ParameterizedTest + @MethodSource("parameters") + public void testStartsWithWithChar(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -250,7 +259,7 @@ public void testStartsWithWithChar() { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -263,8 +272,9 @@ public void testStartsWithWithChar() { assertThat(list.get(0)).isEqualTo("Luca"); } - @Test - public void testNotIn() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotIn(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -274,7 +284,7 @@ public void testNotIn() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -288,8 +298,9 @@ public void testNotIn() { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testNotInUsingShort() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotInUsingShort(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -299,7 +310,7 @@ public void testNotInUsingShort() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -313,8 +324,9 @@ public void testNotInUsingShort() { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testMatchesWithFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testMatchesWithFunction(RUN_TYPE runType) { // DROOLS-4382 String str = "import " + Person.class.getCanonicalName() + "\n" + @@ -324,7 +336,7 @@ public void testMatchesWithFunction() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mark", 40); p.setLikes( "M." ); @@ -332,8 +344,9 @@ public void testMatchesWithFunction() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMatchesOnNullString() { + @ParameterizedTest + @MethodSource("parameters") + public void testMatchesOnNullString(RUN_TYPE runType) { // DROOLS-4525 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -346,7 +359,7 @@ public void testMatchesOnNullString() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person first = new Person("686878"); ksession.insert(first); @@ -377,8 +390,9 @@ public String toString() { } } - @Test - public void testInDouble() { + @ParameterizedTest + @MethodSource("parameters") + public void testInDouble(RUN_TYPE runType) { // DROOLS-4892 String str = "import " + DoubleFact.class.getCanonicalName() + ";" + @@ -406,10 +420,10 @@ public void testInDouble() { " System.out.println(\"Rule[\"+kcontext.getRule().getName()+\"] fires.\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); DoubleFact f = new DoubleFact(); - f.setDoubleVal(new Double(100)); + f.setDoubleVal(Double.valueOf(100.0)); f.setPrimitiveDoubleVal(200); ksession.insert(f); assertThat(ksession.fireAllRules()).isEqualTo(4); @@ -432,8 +446,9 @@ public List getIntList() { } } - @Test - public void testContainsOnNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testContainsOnNull(RUN_TYPE runType) { // DROOLS-5315 String str = "import " + ListContainer.class.getCanonicalName() + ";" + @@ -442,7 +457,7 @@ public void testContainsOnNull() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ListContainer() ); assertThat(ksession.fireAllRules()).isEqualTo(0); @@ -451,8 +466,9 @@ public void testContainsOnNull() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNumericStringsWithLeadingZero() { + @ParameterizedTest + @MethodSource("parameters") + public void testNumericStringsWithLeadingZero(RUN_TYPE runType) { // DROOLS-5926 String str = "rule R when\n" + @@ -460,14 +476,15 @@ public void testNumericStringsWithLeadingZero() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( 800 ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNumericHexadecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testNumericHexadecimal(RUN_TYPE runType) { // DROOLS-5926 String str = "rule R when\n" + @@ -475,14 +492,15 @@ public void testNumericHexadecimal() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( 2048 ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testListLiteralCreation() { + @ParameterizedTest + @MethodSource("parameters") + public void testListLiteralCreation(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;" + @@ -492,7 +510,7 @@ public void testListLiteralCreation() { " result.add($myList);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); ksession.insert( new Person() ); @@ -503,8 +521,9 @@ public void testListLiteralCreation() { assertThat((List)obj).containsExactlyInAnyOrder("aaa", "bbb", "ccc"); } - @Test - public void testMapLiteralCreation() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapLiteralCreation(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;" + @@ -514,7 +533,7 @@ public void testMapLiteralCreation() { " result.add($myMap);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); ksession.insert(new Person()); @@ -525,8 +544,9 @@ public void testMapLiteralCreation() { assertThat(((Map) obj).get("key")).isEqualTo("value"); } - @Test - public void testEmptySingleApexString() { + @ParameterizedTest + @MethodSource("parameters") + public void testEmptySingleApexString(RUN_TYPE runType) { // DROOLS-6057 String str = "import " + Person.class.getCanonicalName() + "\n" + @@ -537,7 +557,7 @@ public void testEmptySingleApexString() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -550,8 +570,9 @@ public void testEmptySingleApexString() { assertThat(list.get(0)).isEqualTo(""); } - @Test - public void testContainsOnString() { + @ParameterizedTest + @MethodSource("parameters") + public void testContainsOnString(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "rule R when\n" + @@ -559,7 +580,7 @@ public void testContainsOnString() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person person1 = new Person(""); ksession.insert(new Person("mario", 47)); @@ -567,8 +588,9 @@ public void testContainsOnString() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testContainsOnMapShouldntCompile() { + @ParameterizedTest + @MethodSource("parameters") + public void testContainsOnMapShouldntCompile(RUN_TYPE runType) { // BAPL-1957 String str = "import " + Person.class.getCanonicalName() + "\n" + @@ -577,12 +599,13 @@ public void testContainsOnMapShouldntCompile() { "then\n" + "end "; - Results results = createKieBuilder( str ).getResults(); + Results results = createKieBuilder(runType, str).getResults(); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void testContainsOnIntShouldntCompile() { + @ParameterizedTest + @MethodSource("parameters") + public void testContainsOnIntShouldntCompile(RUN_TYPE runType) { // BAPL-1957 String str = "import " + Person.class.getCanonicalName() + "\n" + @@ -591,7 +614,7 @@ public void testContainsOnIntShouldntCompile() { "then\n" + "end "; - Results results = createKieBuilder( str ).getResults(); + Results results = createKieBuilder(runType, str).getResults(); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NamedConsequencesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NamedConsequencesTest.java index 6a764ebcb07..80ec5862f25 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NamedConsequencesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NamedConsequencesTest.java @@ -26,7 +26,8 @@ import org.drools.model.codegen.execmodel.domain.Cheese; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Message.Level; import org.kie.api.builder.Results; import org.kie.api.runtime.KieSession; @@ -37,12 +38,9 @@ public class NamedConsequencesTest extends BaseModelTest { - public NamedConsequencesTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testNamedConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testNamedConsequence(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -57,7 +55,7 @@ public void testNamedConsequence() { " $r.addValue(\"Found \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -72,8 +70,9 @@ public void testNamedConsequence() { assertThat(results.containsAll(asList("Found Mark", "Mario is older than Mark"))).isTrue(); } - @Test - public void testBreakingNamedConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testBreakingNamedConsequence(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -94,7 +93,7 @@ public void testBreakingNamedConsequence() { " $r.addValue(\"Found \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -110,8 +109,9 @@ public void testBreakingNamedConsequence() { assertThat(results.iterator().next()).isEqualTo("Found Mark"); } - @Test - public void testNonBreakingNamedConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testNonBreakingNamedConsequence(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -132,7 +132,7 @@ public void testNonBreakingNamedConsequence() { " $r.addValue(\"Found \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -148,8 +148,9 @@ public void testNonBreakingNamedConsequence() { assertThat(results.containsAll(asList("Found Mark", "Mario is older than Mark"))).isTrue(); } - @Test - public void testIfAfterAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testIfAfterAccumulate(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -166,7 +167,7 @@ public void testIfAfterAccumulate() { " $r.addValue(\"greater\");\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -180,8 +181,9 @@ public void testIfAfterAccumulate() { assertThat(results.get(0)).isEqualTo("greater"); } - @Test - public void testNonCompilingIFAfterOR() { + @ParameterizedTest + @MethodSource("parameters") + public void testNonCompilingIFAfterOR(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -197,12 +199,13 @@ public void testNonCompilingIFAfterOR() { " results.add( $a.getType() );\n" + "end\n"; - Results results = createKieBuilder(str).getResults(); + Results results = createKieBuilder(runType, str).getResults(); assertThat(results.hasMessages(Level.ERROR)).isTrue(); } - @Test - public void testIfElseWithMvelAccessor() { + @ParameterizedTest + @MethodSource("parameters") + public void testIfElseWithMvelAccessor(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -218,7 +221,7 @@ public void testIfElseWithMvelAccessor() { " results.add( $a.getType().toUpperCase() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList(); ksession.setGlobal("results", results); @@ -237,8 +240,9 @@ public void testIfElseWithMvelAccessor() { assertThat(results.contains("STILTON")).isTrue(); } - @Test - public void testWrongConsequenceName() { + @ParameterizedTest + @MethodSource("parameters") + public void testWrongConsequenceName(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -252,12 +256,13 @@ public void testWrongConsequenceName() { " results.add( $a.getType().toUpperCase() );\n" + "end\n"; - Results results = createKieBuilder(str).getResults(); + Results results = createKieBuilder(runType, str).getResults(); assertThat(results.hasMessages(Level.ERROR)).isTrue(); } - @Test - public void testMvelInsertWithNamedConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testMvelInsertWithNamedConsequence(RUN_TYPE runType) { String drl = "package org.drools.compiler\n" + "global java.util.concurrent.atomic.AtomicInteger counter\n" + @@ -283,7 +288,7 @@ public void testMvelInsertWithNamedConsequence() { " counter.incrementAndGet();\n" + "end\n"; - KieSession kSession = getKieSession(drl); + KieSession kSession = getKieSession(runType, drl); AtomicInteger counter = new AtomicInteger(0); kSession.setGlobal("counter", counter); @@ -298,8 +303,9 @@ public void testMvelInsertWithNamedConsequence() { assertThat(counter.get()).isEqualTo(2); } - @Test - public void testMVELBreak() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELBreak(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -313,7 +319,7 @@ public void testMVELBreak() { " results.add( $a.type.toUpperCase() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList(); ksession.setGlobal("results", results); @@ -331,8 +337,9 @@ public void testMVELBreak() { assertThat(results.contains("STILTON")).isTrue(); } - @Test - public void testMVELNoBreak() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELNoBreak(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -346,7 +353,7 @@ public void testMVELNoBreak() { " results.add( $a.type.toUpperCase() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList(); ksession.setGlobal("results", results); @@ -365,8 +372,9 @@ public void testMVELNoBreak() { assertThat(results.contains("cheddar")).isTrue(); } - @Test - public void testMultipleIfElseInARow() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleIfElseInARow(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -394,7 +402,7 @@ public void testMultipleIfElseInARow() { " result.add(\"Age100\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -408,8 +416,9 @@ public void testMultipleIfElseInARow() { assertThat(result.containsAll(asList("Default", "Mark", "Edson", "Age35", "Age37"))).isTrue(); } - @Test - public void testMultipleIfElseInARowWithJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleIfElseInARowWithJoin(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -432,7 +441,7 @@ public void testMultipleIfElseInARowWithJoin() { " $r.addValue(\"Age37\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert(result); @@ -448,8 +457,9 @@ public void testMultipleIfElseInARowWithJoin() { assertThat(results.containsAll(asList("Default", "Mark", "Edson", "Age35", "Age37"))).isTrue(); } - @Test - public void testMultipleIfElseInARowWithJoin2() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleIfElseInARowWithJoin2(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -473,7 +483,7 @@ public void testMultipleIfElseInARowWithJoin2() { " $r.addValue(\"Age37\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert(result); @@ -490,7 +500,7 @@ public void testMultipleIfElseInARowWithJoin2() { assertThat(results.containsAll(asList("DefaultMario", "Mark", "Edson", "Age35", "Age37"))).isTrue(); } - public void testModifyInNamedConsequence() { + public void testModifyInNamedConsequence(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -504,7 +514,7 @@ public void testModifyInNamedConsequence() { " modify( $a ) { setPrice(15) };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList(); ksession.setGlobal("results", results); @@ -522,8 +532,9 @@ public void testModifyInNamedConsequence() { assertThat(results.contains("stilton")).isTrue(); } - @Test - public void test2ModifyBlocksInNamedConsequences() { + @ParameterizedTest + @MethodSource("parameters") + public void test2ModifyBlocksInNamedConsequences(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -538,7 +549,7 @@ public void test2ModifyBlocksInNamedConsequences() { " results.add( $a.getPrice() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -554,8 +565,9 @@ public void test2ModifyBlocksInNamedConsequences() { assertThat(results).containsExactlyInAnyOrder(10, 15); } - @Test - public void testMultipleIfAfterEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleIfAfterEval(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -573,7 +585,7 @@ public void testMultipleIfAfterEval() { " results.add( $a.getType() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -590,7 +602,7 @@ public void testMultipleIfAfterEval() { assertThat(results.contains("stilton")).isTrue(); } - public void testIfTrue() { + public void testIfTrue(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -603,7 +615,7 @@ public void testIfTrue() { " result.add(\"t1\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NativeCompilerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NativeCompilerTest.java index 12860f98815..3f9bd8d9376 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NativeCompilerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NativeCompilerTest.java @@ -20,7 +20,9 @@ import org.drools.compiler.compiler.JavaDialectConfiguration; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import org.kie.memorycompiler.JavaConfiguration; @@ -28,12 +30,10 @@ public class NativeCompilerTest extends BaseModelTest { - public NativeCompilerTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test(timeout = 5000) - public void testPropertyReactivity() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(5000) + public void testPropertyReactivity(RUN_TYPE runType) { // DROOLS-6580 // Since ecj is transitively imported by drools-compiler (we may want to review this with drools 8) // by default the executable model compiler always use it. This test also tries it with the native compiler. @@ -50,7 +50,7 @@ public void testPropertyReactivity() { " modify($p) { setAge($p.getAge()+1) }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person me = new Person("Mario", 40); ksession.insert(me); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NodeSharingTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NodeSharingTest.java index 65eef03f77f..2cf30843a3b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NodeSharingTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NodeSharingTest.java @@ -41,7 +41,8 @@ import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; import org.drools.model.codegen.execmodel.domain.StockTick; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.time.SessionPseudoClock; @@ -50,12 +51,9 @@ public class NodeSharingTest extends BaseModelTest { - public NodeSharingTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testShareAlpha() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAlpha(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -69,7 +67,7 @@ public void testShareAlpha() { " $r.add($p3);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Set result = new HashSet<>(); ksession.insert( result ); @@ -91,8 +89,9 @@ public void testShareAlpha() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(2); } - @Test - public void testShareAlphaInDifferentRules() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAlphaInDifferentRules(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -104,13 +103,14 @@ public void testShareAlphaInDifferentRules() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareAlphaInDifferentPackages() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAlphaInDifferentPackages(RUN_TYPE runType) { String str1 = "package org.drools.a\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -126,13 +126,14 @@ public void testShareAlphaInDifferentPackages() { "then\n" + "end"; - KieSession ksession = getKieSession( str1, str2 ); + KieSession ksession = getKieSession(runType, str1, str2); assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareBetaWithConstraintReordering() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareBetaWithConstraintReordering(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -146,7 +147,7 @@ public void testShareBetaWithConstraintReordering() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ReteDumper.collectNodes(ksession).stream().filter(BetaNode.class::isInstance).count()).isEqualTo(1); @@ -155,8 +156,9 @@ public void testShareBetaWithConstraintReordering() { assertThat(otn.getSinks().length).isEqualTo(1); } - @Test - public void testTrimmedConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testTrimmedConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + @@ -169,13 +171,14 @@ public void testTrimmedConstraint() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testOrWithTrimmedConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWithTrimmedConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list\n" + @@ -193,7 +196,7 @@ public void testOrWithTrimmedConstraint() { " list.add( $p + \" has \" + $age + \" years\");\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(2); @@ -212,8 +215,9 @@ public void testOrWithTrimmedConstraint() { assertThat(results.contains("Mario has 40 years")).isTrue(); } - @Test - public void testShareAlphaHashable() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAlphaHashable(RUN_TYPE runType) { String str = "import " + Factor.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -223,7 +227,7 @@ public void testShareAlphaHashable() { " Factor( factorAmt == 10.0 )\n" + "then end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Factor(10.0)); assertThat(ksession.fireAllRules()).isEqualTo(2); @@ -231,8 +235,9 @@ public void testShareAlphaHashable() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareAlphaRangeIndexable() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAlphaRangeIndexable(RUN_TYPE runType) { String str = "import " + Factor.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -242,7 +247,7 @@ public void testShareAlphaRangeIndexable() { " Factor( factorAmt > 10.0 )\n" + "then end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Factor(25.0)); assertThat(ksession.fireAllRules()).isEqualTo(2); @@ -263,8 +268,9 @@ public double getFactorAmt() { } } - @Test - public void testShareEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareEval(RUN_TYPE runType) { final String str = "package myPkg;\n" + "rule R1 when\n" + " i : Integer()\n" + @@ -278,7 +284,7 @@ public void testShareEval() { "end\n" + ""; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); EntryPointNode epn = ((InternalKnowledgeBase) kbase).getRete().getEntryPointNodes().values().iterator().next(); @@ -287,7 +293,7 @@ public void testShareEval() { assertThat(lian.getSinks().length).isEqualTo(1); } - public void testShareFrom() { + public void testShareFrom(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Address.class.getCanonicalName() + ";\n" + @@ -305,7 +311,7 @@ public void testShareFrom() { " list.add($a);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List
list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -322,8 +328,9 @@ public void testShareFrom() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(FromNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -342,7 +349,7 @@ public void testShareAccumulate() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -357,8 +364,9 @@ public void testShareAccumulate() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(AccumulateNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareFromAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareFromAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -377,7 +385,7 @@ public void testShareFromAccumulate() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -392,8 +400,9 @@ public void testShareFromAccumulate() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(AccumulateNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareExists(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -408,7 +417,7 @@ public void testShareExists() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person mario = new Person("Mario", 40); @@ -422,8 +431,9 @@ public void testShareExists() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(ExistsNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareNot() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareNot(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -438,7 +448,7 @@ public void testShareNot() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person mario = new Person("Mario", 40); @@ -452,8 +462,9 @@ public void testShareNot() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(NotNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareCombinedConstraintAnd() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testShareCombinedConstraintAnd(RUN_TYPE runType) throws Exception { // DROOLS-6330 // Note: if DROOLS-6329 is resolved, this test may not produce CombinedConstraint String str = @@ -471,7 +482,7 @@ public void testShareCombinedConstraintAnd() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(CepTest.getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, CepTest.getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); @@ -489,8 +500,9 @@ public void testShareCombinedConstraintAnd() throws Exception { assertThat(ReteDumper.collectNodes(ksession).stream().filter(JoinNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareCombinedConstraintOr() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testShareCombinedConstraintOr(RUN_TYPE runType) throws Exception { // DROOLS-6330 String str = "import " + StockTick.class.getCanonicalName() + ";" + @@ -507,7 +519,7 @@ public void testShareCombinedConstraintOr() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(CepTest.getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, CepTest.getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); 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 536af82f868..a442f36b28c 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,19 +26,17 @@ 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.Test; +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; public class NullSafeDereferencingTest extends BaseModelTest { - public NullSafeDereferencingTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testNullSafeDereferncing() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncing(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -49,7 +47,7 @@ public void testNullSafeDereferncing() { " $r.setValue(\"Found: \" + $p);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -115,8 +113,9 @@ public void setSomething(String something) { } } - @Test - public void testNullSafeMultiple() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeMultiple(RUN_TYPE runType) { String str = "import " + NullUnsafeA.class.getCanonicalName() + ";" + "import " + NullUnsafeB.class.getCanonicalName() + ";" + "import " + NullUnsafeD.class.getCanonicalName() + ";" + @@ -127,7 +126,7 @@ public void testNullSafeMultiple() { "end"; for (int i = 0; i <= 4; i++) { - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); NullUnsafeA a = new NullUnsafeA(); NullUnsafeB b = new NullUnsafeB(); @@ -162,8 +161,9 @@ public void testNullSafeMultiple() { } } - @Test - public void testNullSafeDereferncingOnFieldWithMethodInvocation() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingOnFieldWithMethodInvocation(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -173,7 +173,7 @@ public void testNullSafeDereferncingOnFieldWithMethodInvocation() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("John1", 41, (Address) null)); ksession.insert(new Person("John2", 42, new Address("Milan"))); @@ -184,8 +184,9 @@ public void testNullSafeDereferncingOnFieldWithMethodInvocation() { assertThat(results.get(0).getValue()).isEqualTo("John2"); } - @Test - public void testNullSafeDereferncingOnMethodInvocation() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingOnMethodInvocation(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -195,7 +196,7 @@ public void testNullSafeDereferncingOnMethodInvocation() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("John1", 41, new Address(null))); ksession.insert(new Person("John2", 42, new Address("Milan"))); @@ -206,8 +207,9 @@ public void testNullSafeDereferncingOnMethodInvocation() { assertThat(results.get(0).getValue()).isEqualTo("John2"); } - @Test - public void testNullSafeDereferncingOnFirstField() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingOnFirstField(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -217,7 +219,7 @@ public void testNullSafeDereferncingOnFirstField() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("John1", 41, (Address) null)); ksession.insert(new Person("John2", 42, new Address("Milan"))); @@ -228,8 +230,9 @@ public void testNullSafeDereferncingOnFirstField() { assertThat(results.get(0).getValue()).isEqualTo("John2"); } - @Test - public void testNullSafeDereferncingOnSecondField() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingOnSecondField(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -239,7 +242,7 @@ public void testNullSafeDereferncingOnSecondField() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("John1", 41, new Address(null))); ksession.insert(new Person("John2", 42, new Address("Milan"))); @@ -250,8 +253,9 @@ public void testNullSafeDereferncingOnSecondField() { assertThat(results.get(0).getValue()).isEqualTo("John2"); } - @Test - public void testNullSafeDereferncingWithOrHalfBinary() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingWithOrHalfBinary(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -262,7 +266,7 @@ public void testNullSafeDereferncingWithOrHalfBinary() { " result.add($p.getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -274,8 +278,9 @@ public void testNullSafeDereferncingWithOrHalfBinary() { assertThat(result).containsExactlyInAnyOrder("John", "George"); } - @Test - public void testNullSafeDereferencingNonPredicate() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferencingNonPredicate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -285,7 +290,7 @@ public void testNullSafeDereferencingNonPredicate() { " result.add($cityName);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -297,8 +302,9 @@ public void testNullSafeDereferencingNonPredicate() { assertThat(result).containsExactlyInAnyOrder("London", "Tokyo"); } - @Test - public void testMultipleNullSafeDereferencingNonPredicate() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleNullSafeDereferencingNonPredicate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -308,7 +314,7 @@ public void testMultipleNullSafeDereferencingNonPredicate() { " result.add($cityNameLength);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -320,8 +326,9 @@ public void testMultipleNullSafeDereferencingNonPredicate() { assertThat(result).containsExactlyInAnyOrder(6); } - @Test - public void testNullSafeDereferencingPredicateMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferencingPredicateMethod(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -331,7 +338,7 @@ public void testNullSafeDereferencingPredicateMethod() { " result.add($containsL);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -343,8 +350,9 @@ public void testNullSafeDereferencingPredicateMethod() { assertThat(result).containsExactlyInAnyOrder(true, false); } - @Test - public void testNullSafeIndex() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeIndex(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 when\n" + " $city : String()\n"+ @@ -352,7 +360,7 @@ public void testNullSafeIndex() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 38)); @@ -369,8 +377,9 @@ public void testNullSafeIndex() { ksession.dispose(); } - @Test - public void testNullSafeDereferncingWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingWithOr(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -381,7 +390,7 @@ public void testNullSafeDereferncingWithOr() { " result.add($p.getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -400,8 +409,9 @@ public void testNullSafeDereferncingWithOr() { assertThat(result).containsExactlyInAnyOrder("Bob", "Paul"); } - @Test - public void testNullSafeDereferncingWithInstanceof() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingWithInstanceof(RUN_TYPE runType) { // instanceof has to be evaluated before null check String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -414,7 +424,7 @@ public void testNullSafeDereferncingWithInstanceof() { " result.add($p.getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java index b92641ad932..10b5c36a39e 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java @@ -21,148 +21,162 @@ import java.math.BigDecimal; import org.drools.model.codegen.execmodel.domain.ValueHolder; -import org.junit.Test; +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; public class NumberAndStringArithmeticOperationCoercionTest extends BaseModelTest { - public NumberAndStringArithmeticOperationCoercionTest(RUN_TYPE testRunType) { - super(testRunType); - } // NOTE: For BigDecimal specific issues, use BigDecimalTest - @Test - public void testMultiplyStringInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringInt(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(100); holder.setStrValue("10"); - testValueHolder("ValueHolder( intValue == strValue * 10 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue * 10 )", holder); } - @Test - public void testMultiplyStringIntWithBindVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringIntWithBindVariable(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(100); holder.setStrValue("10"); - testValueHolder("ValueHolder( $strValue : strValue, intValue == $strValue * 10 )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, intValue == $strValue * 10 )", holder); } - @Test - public void testMultiplyIntStringWithBindVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyIntStringWithBindVariable(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(100); holder.setStrValue("10"); - testValueHolder("ValueHolder( $strValue : strValue, intValue == 10 * $strValue)", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, intValue == 10 * $strValue)", holder); } - @Test - public void testMultiplyStringIntWithBindVariableCompareToBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringIntWithBindVariableCompareToBigDecimal(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setStrValue("10"); holder.setBdValue(new BigDecimal("-10")); - testValueHolder("ValueHolder( $strValue : strValue, bdValue == $strValue * -1 )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, bdValue == $strValue * -1 )", holder); } - @Test - public void testMultiplyStringIntWithBindVariableCompareToObject() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringIntWithBindVariableCompareToObject(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setStrValue("20"); holder.setObjValue("200"); - testValueHolder("ValueHolder( $strValue : strValue, objValue == $strValue * 10 )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, objValue == $strValue * 10 )", holder); } - @Test - public void testMultiplyStringBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringBigDecimal(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(10); holder.setStrValue("20"); - testValueHolder("ValueHolder( intValue == strValue * 0.5B )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue * 0.5B )", holder); } - @Test - public void testMultiplyDecimalStringInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyDecimalStringInt(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(5); holder.setStrValue("0.5"); - testValueHolder("ValueHolder( intValue == strValue * 10 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue * 10 )", holder); } - @Test - public void testMultiplyDecimalStringBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyDecimalStringBigDecimal(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(5); holder.setStrValue("0.5"); - testValueHolder("ValueHolder( intValue == strValue * 10B )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue * 10B )", holder); } - @Test - public void testMultiplyIntDecimalString() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyIntDecimalString(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(5); holder.setStrValue("0.5"); - testValueHolder("ValueHolder( intValue == 10 * strValue )", holder); + testValueHolder(runType, "ValueHolder( intValue == 10 * strValue )", holder); } - @Test - public void testMultiplyStringDouble() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringDouble(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(101); holder.setStrValue("10"); - testValueHolder("ValueHolder( intValue == strValue * 10.1 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue * 10.1 )", holder); } - @Test - public void testAddStringIntWithBindVariableCompareToObject() { + @ParameterizedTest + @MethodSource("parameters") + public void testAddStringIntWithBindVariableCompareToObject(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setStrValue("20"); holder.setObjValue("2010"); // String concat - testValueHolder("ValueHolder( $strValue : strValue, objValue == $strValue + 10 )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, objValue == $strValue + 10 )", holder); } - @Test - public void testAddIntStringWithBindVariableCompareToObject() { + @ParameterizedTest + @MethodSource("parameters") + public void testAddIntStringWithBindVariableCompareToObject(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setStrValue("20"); holder.setObjValue("1020"); // String concat - testValueHolder("ValueHolder( $strValue : strValue, objValue == 10 + $strValue )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, objValue == 10 + $strValue )", holder); } - @Test - public void testAddStringIntWithBindVariableCompareToObjectNonNumeric() { + @ParameterizedTest + @MethodSource("parameters") + public void testAddStringIntWithBindVariableCompareToObjectNonNumeric(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setStrValue("ABC"); holder.setObjValue("ABC10"); // String concat - testValueHolder("ValueHolder( $strValue : strValue, objValue == $strValue + 10 )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, objValue == $strValue + 10 )", holder); } - @Test - public void testSubtractStringInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testSubtractStringInt(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(40); holder.setStrValue("50"); - testValueHolder("ValueHolder( intValue == strValue - 10 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue - 10 )", holder); } - @Test - public void testModStringInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testModStringInt(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(2); holder.setStrValue("12"); - testValueHolder("ValueHolder( intValue == strValue % 10 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue % 10 )", holder); } - @Test - public void testDivideStringInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testDivideStringInt(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(5); holder.setStrValue("50"); - testValueHolder("ValueHolder( intValue == strValue / 10 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue / 10 )", holder); } - private void testValueHolder(String pattern, ValueHolder holder) { + private void testValueHolder(RUN_TYPE runType, String pattern, ValueHolder holder) { String str = "import " + ValueHolder.class.getCanonicalName() + "\n" + "rule R dialect \"mvel\" when\n" + @@ -170,7 +184,7 @@ private void testValueHolder(String pattern, ValueHolder holder) { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(holder); int fired = ksession.fireAllRules(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OOPathTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OOPathTest.java index edba0258d31..037397677ad 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OOPathTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OOPathTest.java @@ -28,19 +28,17 @@ import org.drools.model.codegen.execmodel.domain.Man; import org.drools.model.codegen.execmodel.domain.Toy; import org.drools.model.codegen.execmodel.domain.Woman; -import org.junit.Test; +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; public class OOPathTest extends BaseModelTest { - public OOPathTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testOOPath() { + @ParameterizedTest + @MethodSource("parameters") + public void testOOPath(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -51,7 +49,7 @@ public void testOOPath() { " list.add( $man.getName() );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -73,8 +71,9 @@ public void testOOPath() { assertThat(list).containsExactlyInAnyOrder("Bob"); } - @Test - public void testOOPathBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testOOPathBinding(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -85,7 +84,7 @@ public void testOOPathBinding() { " list.add( $age );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -102,8 +101,9 @@ public void testOOPathBinding() { assertThat(list).containsExactlyInAnyOrder(38); } - @Test - public void testReactiveOOPath() { + @ParameterizedTest + @MethodSource("parameters") + public void testReactiveOOPath(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -114,7 +114,7 @@ public void testReactiveOOPath() { " list.add( $toy.getName() );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -145,8 +145,9 @@ public void testReactiveOOPath() { } - @Test - public void testBackReferenceConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testBackReferenceConstraint(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -157,7 +158,7 @@ public void testBackReferenceConstraint() { " list.add( $toy.getName() );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -182,8 +183,9 @@ public void testBackReferenceConstraint() { assertThat(list).containsExactlyInAnyOrder("ball", "guitar"); } - @Test - public void testSimpleOOPathCast1() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleOOPathCast1(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + "\n" + @@ -193,7 +195,7 @@ public void testSimpleOOPathCast1() { " list.add( $man.getName() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -206,8 +208,9 @@ public void testSimpleOOPathCast1() { assertThat(list).containsExactlyInAnyOrder("Bob"); } - @Test - public void testSimpleOOPathCast2() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleOOPathCast2(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + "\n" + @@ -217,7 +220,7 @@ public void testSimpleOOPathCast2() { " list.add( $name );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -230,8 +233,9 @@ public void testSimpleOOPathCast2() { assertThat(list).containsExactlyInAnyOrder("Bob"); } - @Test - public void testSimpleOOPathCast3() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleOOPathCast3(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + "\n" + @@ -241,7 +245,7 @@ public void testSimpleOOPathCast3() { " list.add( $name );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -254,8 +258,9 @@ public void testSimpleOOPathCast3() { assertThat(list).containsExactlyInAnyOrder("Bob"); } - @Test - public void testOOPathMultipleConditions() { + @ParameterizedTest + @MethodSource("parameters") + public void testOOPathMultipleConditions(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -267,7 +272,7 @@ public void testOOPathMultipleConditions() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -283,8 +288,9 @@ public void testOOPathMultipleConditions() { assertThat(results).containsExactlyInAnyOrder("Big City"); } - @Test - public void testOOPathMultipleConditionsWithBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testOOPathMultipleConditionsWithBinding(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -298,7 +304,7 @@ public void testOOPathMultipleConditionsWithBinding() { " list.add( $employee.getName() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -314,8 +320,9 @@ public void testOOPathMultipleConditionsWithBinding() { assertThat(results).containsExactlyInAnyOrder("Alice"); } - @Test - public void testOrConditionalElementNoBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConditionalElementNoBinding(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -331,7 +338,7 @@ public void testOrConditionalElementNoBinding() { " list.add( $employee.getName() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -347,8 +354,9 @@ public void testOrConditionalElementNoBinding() { assertThat(results).containsExactlyInAnyOrder("Bruno", "Alice"); } - @Test - public void testOrConditionalElement() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConditionalElement(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -362,7 +370,7 @@ public void testOrConditionalElement() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -378,8 +386,9 @@ public void testOrConditionalElement() { assertThat(results).containsExactlyInAnyOrder("Big City", "Small City"); } - @Test - public void testOrConstraintNoBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConstraintNoBinding(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -392,7 +401,7 @@ public void testOrConstraintNoBinding() { " list.add( $emp.getName() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -408,8 +417,9 @@ public void testOrConstraintNoBinding() { assertThat(results).containsExactlyInAnyOrder("Bruno", "Alice"); } - @Test - public void testOrConstraintWithJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConstraintWithJoin(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -422,7 +432,7 @@ public void testOrConstraintWithJoin() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -438,8 +448,9 @@ public void testOrConstraintWithJoin() { assertThat(results).containsExactlyInAnyOrder("Big City", "Small City"); } - @Test - public void testOrConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConstraint(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -452,7 +463,7 @@ public void testOrConstraint() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyExecModelTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyExecModelTest.java index 8c36c433a9e..99193325f11 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyExecModelTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyExecModelTest.java @@ -18,24 +18,14 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import java.util.stream.Stream; + import static org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE.PATTERN_DSL; -@RunWith(Parameterized.class) public abstract class OnlyExecModelTest extends BaseModelTest { - public OnlyExecModelTest(RUN_TYPE testRunType) { - super(testRunType); - } - - final static Object[] ONLY_EXEC_MODEL = { - PATTERN_DSL, - }; - - @Parameterized.Parameters(name = "{0}") - public static Object[] params() { - return ONLY_EXEC_MODEL; + public static Stream parameters() { + return Stream.of(PATTERN_DSL); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyPatternTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyPatternTest.java index 3c89f4d35ca..0f5e553b1ac 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyPatternTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyPatternTest.java @@ -18,25 +18,13 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - import static org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE.PATTERN_DSL; -@RunWith(Parameterized.class) -public abstract class OnlyPatternTest extends BaseModelTest { +import java.util.stream.Stream; - public OnlyPatternTest(RUN_TYPE testRunType) { - super(testRunType); - } - - final static Object[] EXCLUDE_FLOW = { - RUN_TYPE.STANDARD_FROM_DRL, - PATTERN_DSL, - }; +public abstract class OnlyPatternTest extends BaseModelTest { - @Parameterized.Parameters(name = "{0}") - public static Object[] params() { - return EXCLUDE_FLOW; + public static Stream parameters() { + return Stream.of(RUN_TYPE.STANDARD_FROM_DRL, PATTERN_DSL); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OrTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OrTest.java index 242e13f7ab8..c041a4f5f42 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OrTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OrTest.java @@ -21,7 +21,8 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Employee; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Results; import org.kie.api.runtime.KieSession; @@ -32,12 +33,9 @@ public class OrTest extends BaseModelTest { - public OrTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testOr(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -50,7 +48,7 @@ public void testOr() { " System.out.println(\"Found: \" + $s);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); ksession.insert( new Person( "Mark", 37 ) ); @@ -59,8 +57,9 @@ public void testOr() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testOrWhenStringFirst() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWhenStringFirst(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -74,7 +73,7 @@ public void testOrWhenStringFirst() { " System.out.println(\"Found: \" + $s.getClass());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Go" ); ksession.insert( new Person( "Mark", 37 ) ); @@ -84,8 +83,9 @@ public void testOrWhenStringFirst() { } - @Test - public void testOrWithBetaIndex() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWithBetaIndex(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -98,7 +98,7 @@ public void testOrWithBetaIndex() { " System.out.println(\"Found: \" + $s);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Mario"); ksession.insert(new Person("Mark", 37)); @@ -107,8 +107,9 @@ public void testOrWithBetaIndex() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testOrWithBetaIndexOffset() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWithBetaIndexOffset(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -122,7 +123,7 @@ public void testOrWithBetaIndexOffset() { " System.out.println(\"Found: \" + $s);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Mario"); ksession.insert(new Person("Mark", 37)); @@ -131,8 +132,9 @@ public void testOrWithBetaIndexOffset() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testOrConditional() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConditional(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -146,7 +148,7 @@ public void testOrConditional() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -162,8 +164,9 @@ public void testOrConditional() { assertThat(results).containsExactlyInAnyOrder("Big City", "Small City"); } - @Test - public void testOrConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConstraint(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -175,7 +178,7 @@ public void testOrConstraint() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -191,8 +194,9 @@ public void testOrConstraint() { assertThat(results).containsExactlyInAnyOrder("Big City", "Small City"); } - @Test - public void testOrWithDuplicatedVariables() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWithDuplicatedVariables(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list\n" + @@ -210,7 +214,7 @@ public void testOrWithDuplicatedVariables() { " list.add( $p + \" has \" + $age + \" years\");\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("list", results); @@ -227,8 +231,9 @@ public void testOrWithDuplicatedVariables() { assertThat(results.contains("Mario has 40 years")).isTrue(); } - @Test - public void generateErrorForEveryFieldInRHSNotDefinedInLHS() { + @ParameterizedTest + @MethodSource("parameters") + public void generateErrorForEveryFieldInRHSNotDefinedInLHS(RUN_TYPE runType) { // JBRULES-3390 final String drl1 = "package org.drools.compiler.integrationtests.operators; \n" + "declare B\n" + @@ -245,16 +250,17 @@ public void generateErrorForEveryFieldInRHSNotDefinedInLHS() { " System.out.println($bField);\n" + "end\n"; - Results results = getCompilationResults(drl1); + Results results = getCompilationResults(runType, drl1); assertThat(results.getMessages().isEmpty()).isFalse(); } - private Results getCompilationResults( String drl ) { - return createKieBuilder( drl ).getResults(); + private Results getCompilationResults( RUN_TYPE runType, String drl ) { + return createKieBuilder(runType, drl ).getResults(); } - @Test - public void testMultipleFiringWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleFiringWithOr(RUN_TYPE runType) { // DROOLS-7466 final String str = "rule R when\n" + @@ -264,7 +270,7 @@ public void testMultipleFiringWithOr() { "then\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(2); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PackagesIsolationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PackagesIsolationTest.java index 41c912e99a1..e1d99b0e546 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PackagesIsolationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PackagesIsolationTest.java @@ -20,21 +20,19 @@ import java.util.Arrays; -import org.junit.Test; +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; public class PackagesIsolationTest extends BaseModelTest { - public PackagesIsolationTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - public static class HashSet { } - @Test - public void testDoNotMixImports() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoNotMixImports(RUN_TYPE runType) { // DROOLS-5390 String str2 = "package mypkg2\n" + @@ -47,11 +45,12 @@ public void testDoNotMixImports() { " list.add(\"R2\");\n" + "end"; - check( str2 ); + check( runType, str2 ); } - @Test - public void testImportWildcard() { + @ParameterizedTest + @MethodSource("parameters") + public void testImportWildcard(RUN_TYPE runType) { String str2 = "package mypkg2\n" + "import mypkg1.*;\n" + @@ -62,11 +61,12 @@ public void testImportWildcard() { " list.add(\"R2\");\n" + "end"; - check( str2 ); + check( runType, str2 ); } - @Test - public void testImportType() { + @ParameterizedTest + @MethodSource("parameters") + public void testImportType(RUN_TYPE runType) { String str2 = "package mypkg2\n" + "import mypkg1.MyPojo;\n" + @@ -77,10 +77,10 @@ public void testImportType() { " list.add(\"R2\");\n" + "end"; - check( str2 ); + check( runType, str2 ); } - private void check( String str2 ) { + private void check( RUN_TYPE runType, String str2 ) { String str1 = "package mypkg1\n" + "global java.util.List list\n" + @@ -92,7 +92,7 @@ private void check( String str2 ) { " list.add(\"R1\");\n" + "end"; - KieSession ksession = getKieSession( str1, str2 ); + KieSession ksession = getKieSession(runType, str1, str2); java.util.List list = new java.util.ArrayList<>(); ksession.setGlobal( "list", list ); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrimitiveConversionErrorsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrimitiveConversionErrorsTest.java index 0b335efb372..52dacae6c6b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrimitiveConversionErrorsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrimitiveConversionErrorsTest.java @@ -20,14 +20,13 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; @@ -39,9 +38,9 @@ import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.arguments; // DROOLS-6506 -@RunWith(Parameterized.class) public class PrimitiveConversionErrorsTest { private static final String RULE_TEMPLATE = "" + @@ -66,63 +65,49 @@ public class PrimitiveConversionErrorsTest { " $values.add($value);\n" + "end"; - @Parameterized.Parameters(name = "value{0} != {2}: Method Returns {0}, test against {1}") - public static Collection data() { - Object[][] data = new Object[][]{ - {Float.class, Float.class, 4f, 5f, 6f}, - {Float.class, Double.class, 4d, 5f, 6f}, - {Float.class, Integer.class, 4, 5f, 6f}, - {Float.class, Short.class, (short) 4, 5f, 6f}, - {Float.class, Byte.class, (byte) 4, 5f, 6f}, - - {Double.class, Float.class, 4f, 5d, 6d}, - {Double.class, Double.class, 4d, 5d, 6d}, - {Double.class, Integer.class, 4, 5d, 6d}, - {Double.class, Short.class, (short) 4, 5d, 6d}, - {Double.class, Byte.class, (byte) 4, 5d, 6d}, - - {Integer.class, Float.class, 4f, 5, 6}, - {Integer.class, Double.class, 4d, 5, 6}, - {Integer.class, Integer.class, 4, 5, 6}, - {Integer.class, Short.class, (short) 4, 5, 6}, - {Integer.class, Byte.class, (byte) 4, 5, 6}, - - {Short.class, Float.class, 4f, (short) 5, (short) 6}, - {Short.class, Double.class, 4d, (short) 5, (short) 6}, - {Short.class, Integer.class, 4, (short) 5, (short) 6}, - {Short.class, Short.class, (short) 4, (short) 5, (short) 6}, - {Short.class, Byte.class, (byte) 4, (short) 5, (short) 6}, - - {Byte.class, Float.class, 4f, (byte) 5, (byte) 6}, - {Byte.class, Double.class, 4d, (byte) 5, (byte) 6}, - {Byte.class, Integer.class, 4, (byte) 5, (byte) 6}, - {Byte.class, Short.class, (short) 4, (byte) 5, (byte) 6}, - {Byte.class, Byte.class, (byte) 4, (byte) 5, (byte) 6}, - }; - return Arrays.asList(data); + public static Stream data() { + return Stream.of( + arguments(Float.class, Float.class, 4f, 5f, 6f), + arguments(Float.class, Double.class, 4d, 5f, 6f), + arguments(Float.class, Integer.class, 4, 5f, 6f), + arguments(Float.class, Short.class, (short) 4, 5f, 6f), + arguments(Float.class, Byte.class, (byte) 4, 5f, 6f), + + arguments(Double.class, Float.class, 4f, 5d, 6d), + arguments(Double.class, Double.class, 4d, 5d, 6d), + arguments(Double.class, Integer.class, 4, 5d, 6d), + arguments(Double.class, Short.class, (short) 4, 5d, 6d), + arguments(Double.class, Byte.class, (byte) 4, 5d, 6d), + + arguments(Integer.class, Float.class, 4f, 5, 6), + arguments(Integer.class, Double.class, 4d, 5, 6), + arguments(Integer.class, Integer.class, 4, 5, 6), + arguments(Integer.class, Short.class, (short) 4, 5, 6), + arguments(Integer.class, Byte.class, (byte) 4, 5, 6), + + arguments(Short.class, Float.class, 4f, (short) 5, (short) 6), + arguments(Short.class, Double.class, 4d, (short) 5, (short) 6), + arguments(Short.class, Integer.class, 4, (short) 5, (short) 6), + arguments(Short.class, Short.class, (short) 4, (short) 5, (short) 6), + arguments(Short.class, Byte.class, (byte) 4, (short) 5, (short) 6), + + arguments(Byte.class, Float.class, 4f, (byte) 5, (byte) 6), + arguments(Byte.class, Double.class, 4d, (byte) 5, (byte) 6), + arguments(Byte.class, Integer.class, 4, (byte) 5, (byte) 6), + arguments(Byte.class, Short.class, (short) 4, (byte) 5, (byte) 6), + arguments(Byte.class, Byte.class, (byte) 4, (byte) 5, (byte) 6)); } - private final Object valueCheck; - private final Class valueType; - private final Object valueA; - private final Object valueB; + @ParameterizedTest(name="value{0} != {2}: Method Returns {0}, test against {1}") + @MethodSource("data") + public void withExecutableModel(Class valueType, Class valueCheckType, Object valueCheck, Object valueA, Object valueB) throws IOException { - public PrimitiveConversionErrorsTest(Class valueType, Class valueCheckType, Object valueCheck, Object valueA, Object valueB) { - this.valueCheck = valueCheck; - this.valueType = valueType; - this.valueA = valueA; - this.valueB = valueB; - } - - @Test - public void withExecutableModel() throws IOException { - - KieBase kbase = loadRules(this.valueType, this.valueCheck, true); + KieBase kbase = loadRules(valueType, valueCheck, true); KieSession session = kbase.newKieSession(); List values = new ArrayList<>(); - ClassWithValue ca = makeClassWithValue(this.valueA); - ClassWithValue cb = makeClassWithValue(this.valueB); + ClassWithValue ca = makeClassWithValue(valueA); + ClassWithValue cb = makeClassWithValue(valueB); session.insert(values); session.insert(ca); @@ -131,19 +116,20 @@ public void withExecutableModel() throws IOException { session.fireAllRules(); assertThat(values.size()).isEqualTo(2); - assertThat(values.contains(this.valueA)).isTrue(); - assertThat(values.contains(this.valueB)).isTrue(); + assertThat(values.contains(valueA)).isTrue(); + assertThat(values.contains(valueB)).isTrue(); } - @Test - public void withoutExecutableModel() throws IOException { + @ParameterizedTest(name="value{0} != {2}: Method Returns {0}, test against {1}") + @MethodSource("data") + public void withoutExecutableModel(Class valueType, Class valueCheckType, Object valueCheck, Object valueA, Object valueB) throws IOException { - KieBase kbase = loadRules(this.valueType, this.valueCheck, false); + KieBase kbase = loadRules(valueType, valueCheck, false); KieSession session = kbase.newKieSession(); List values = new ArrayList<>(); - ClassWithValue ca = makeClassWithValue(this.valueA); - ClassWithValue cb = makeClassWithValue(this.valueB); + ClassWithValue ca = makeClassWithValue(valueA); + ClassWithValue cb = makeClassWithValue(valueB); session.insert(values); session.insert(ca); @@ -152,8 +138,8 @@ public void withoutExecutableModel() throws IOException { session.fireAllRules(); assertThat(values.size()).isEqualTo(2); - assertThat(values.contains(this.valueA)).isTrue(); - assertThat(values.contains(this.valueB)).isTrue(); + assertThat(values.contains(valueA)).isTrue(); + assertThat(values.contains(valueB)).isTrue(); } private static KieBase loadRules(Class valueType, Object value, boolean useExecutable) throws IOException { diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityMatrixTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityMatrixTest.java index d4742f74e93..070b929db58 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityMatrixTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityMatrixTest.java @@ -19,15 +19,19 @@ package org.drools.model.codegen.execmodel; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; +import org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE; import org.drools.util.StringUtils; -import org.junit.Test; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; +import static org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE.PATTERN_DSL; +import static org.junit.jupiter.params.provider.Arguments.arguments; public class PropertyReactivityMatrixTest extends BaseModelTest { @@ -36,23 +40,23 @@ enum Dialect { MVEL } - private Dialect dialect; - @Parameters(name = "{0} {1}") - public static Collection parameters() { - List parameterData = new ArrayList(); + final static Object[] PLAIN = { + RUN_TYPE.STANDARD_FROM_DRL, + PATTERN_DSL, + }; + + + public static Stream parametersData() { + List parameterData = new ArrayList(); for (Object runType : PLAIN) { for (Dialect dialect : Dialect.values()) { - parameterData.add(new Object[]{runType, dialect}); + parameterData.add(arguments(runType, dialect)); } } - return parameterData; + return Stream.of(parameterData.toArray(new Arguments[0])); } - public PropertyReactivityMatrixTest(RUN_TYPE testRunType, Dialect testDialect) { - super(testRunType); - this.dialect = testDialect; - } public static class Fact { @@ -85,7 +89,7 @@ public void setValue2(int value2) { } } - private String setValueStatement(String property, int value) { + private String setValueStatement(Dialect dialect, String property, int value) { if (dialect == Dialect.JAVA) { return "set" + StringUtils.ucFirst(property) + "(" + value + ");"; } else { @@ -93,123 +97,136 @@ private String setValueStatement(String property, int value) { } } - @Test - public void modifyInsideIfTrueBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" if (true) {\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideIfTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " if (true) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value1", 2) + "\n" + + " " + setValueStatement(dialect, "value1", 2) + "\n" + " }\n" + " }\n"); } - @Test - public void modifyInsideForBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" for (int i = 0; i < 1; i++) {\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideForBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " for (int i = 0; i < 1; i++) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value1", 2) + "\n" + + " " + setValueStatement(dialect, "value1", 2) + "\n" + " }\n" + " }\n"); } - @Test - public void modifyInsideCommentedIfTrueBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" // if (true) {\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideCommentedIfTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " // if (true) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value1", 2) + "\n" + + " " + setValueStatement(dialect, "value1", 2) + "\n" + " }\n" + " // }\n"); } - @Test - public void modifyInsideIfBlockInsideAndOutsideAssignment_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" $fact." + setValueStatement("value1", 2) + "\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideIfBlockInsideAndOutsideAssignment_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + " if (true) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value2", 2) + "\n" + + " " + setValueStatement(dialect, "value2", 2) + "\n" + " }\n" + " }"); } - @Test - public void updateInsideIfTrueBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" if (true) {\n" + - " $fact." + setValueStatement("value1", 2) + ";\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideIfTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " if (true) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + ";\n" + " update($fact);\n" + " }\n"); } - @Test - public void updateInsideForBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" for (int i = 0; i < 1; i++) {\n" + - " $fact." + setValueStatement("value1", 2) + "\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideForBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " for (int i = 0; i < 1; i++) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + " update($fact);\n" + " }\n"); } - @Test - public void updateInsideCommentedIfTrueBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" // if (true) {\n" + - " $fact." + setValueStatement("value1", 2) + "\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideCommentedIfTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " // if (true) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + " update($fact);\n" + " // }\n"); } - @Test - public void updateInsideIfBlockInsideAndOutsideAssignment_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" $fact." + setValueStatement("value1", 2) + "\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideIfBlockInsideAndOutsideAssignment_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + " if (true) {\n" + - " $fact." + setValueStatement("value2", 2) + "\n" + + " $fact." + setValueStatement(dialect, "value2", 2) + "\n" + " update($fact);\n" + " }"); } - @Test - public void assignmentAfterModify_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void assignmentAfterModify_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7497 - statementInsideBlock_shouldTriggerReactivity(" modify($fact) {\n" + - " " + setValueStatement("value2", 2) + "\n" + + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " modify($fact) {\n" + + " " + setValueStatement(dialect, "value2", 2) + "\n" + " }\n" + - " $fact." + setValueStatement("value1", 2) + "\n"); + " $fact." + setValueStatement(dialect, "value1", 2) + "\n"); } - @Test - public void assignmentBeforeAndAfterModify_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void assignmentBeforeAndAfterModify_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7497 - statementInsideBlock_shouldTriggerReactivity(" $fact." + setValueStatement("value2", 2) + "\n" + + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " $fact." + setValueStatement(dialect, "value2", 2) + "\n" + " modify($fact) {\n" + " }\n" + - " $fact." + setValueStatement("value1", 2) + "\n"); + " $fact." + setValueStatement(dialect, "value1", 2) + "\n"); } - @Test - public void assignmentAfterIfBlockModify_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void assignmentAfterIfBlockModify_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7497 - statementInsideBlock_shouldTriggerReactivity(" if (true) {\n" + + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " if (true) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value2", 2) + "\n" + + " " + setValueStatement(dialect, "value2", 2) + "\n" + " }\n" + " }\n" + - " $fact." + setValueStatement("value1", 2) + "\n"); + " $fact." + setValueStatement(dialect, "value1", 2) + "\n"); } - @Test - public void assignmentBeforeAndAfterUpdate_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void assignmentBeforeAndAfterUpdate_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7497 - statementInsideBlock_shouldTriggerReactivity(" $fact." + setValueStatement("value2", 2) + "\n" + + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " $fact." + setValueStatement(dialect, "value2", 2) + "\n" + " update($fact);\n" + - " $fact." + setValueStatement("value1", 2) + "\n"); + " $fact." + setValueStatement(dialect, "value1", 2) + "\n"); } - @Test - public void assignmentAfterIfBlockUpdate_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void assignmentAfterIfBlockUpdate_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7497 - statementInsideBlock_shouldTriggerReactivity(" if (true) {\n" + + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " if (true) {\n" + " update($fact);\n" + " }\n" + - " $fact." + setValueStatement("value1", 2) + "\n"); + " $fact." + setValueStatement(dialect, "value1", 2) + "\n"); } - private void statementInsideBlock_shouldTriggerReactivity(String rhs) { + private void statementInsideBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect, String rhs) { final String str = "import " + Fact.class.getCanonicalName() + ";\n" + "dialect \"" + dialect.name().toLowerCase() + "\"\n" + @@ -227,7 +244,7 @@ private void statementInsideBlock_shouldTriggerReactivity(String rhs) { " results.add(\"R2 fired\");\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -239,11 +256,12 @@ private void statementInsideBlock_shouldTriggerReactivity(String rhs) { .containsExactly("R2 fired"); } - @Test - public void modifyInsideIfFalseAndTrueBlock_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideIfFalseAndTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7493 - statementInsideBlock_shouldTriggerReactivityWithLoop(" if (false) {\n" + - " $fact." + setValueStatement("value1", 2) + "\n" + // this line is not executed, but analyzed as a property reactivity + statementInsideBlock_shouldTriggerReactivityWithLoop(runType, dialect, " if (false) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + // this line is not executed, but analyzed as a property reactivity " }\n" + " if (true) {\n" + " modify($fact) {\n" + @@ -251,17 +269,18 @@ public void modifyInsideIfFalseAndTrueBlock_shouldTriggerReactivity() { " }\n"); } - @Test - public void updateInsideIfFalseAndTrueBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivityWithLoop(" if (false) {\n" + - " $fact." + setValueStatement("value1", 2) + "\n" + // this line is not executed, but analyzed as a property reactivity + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideIfFalseAndTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivityWithLoop(runType, dialect, " if (false) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + // this line is not executed, but analyzed as a property reactivity " }\n" + " if (true) {\n" + " update($fact);\n" + " }\n"); } - private void statementInsideBlock_shouldTriggerReactivityWithLoop(String rhs) { + private void statementInsideBlock_shouldTriggerReactivityWithLoop(RUN_TYPE runType, Dialect dialect, String rhs) { final String str = "import " + Fact.class.getCanonicalName() + ";\n" + "dialect \"" + dialect.name().toLowerCase() + "\"\n" + @@ -273,7 +292,7 @@ private void statementInsideBlock_shouldTriggerReactivityWithLoop(String rhs) { rhs + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -285,25 +304,27 @@ private void statementInsideBlock_shouldTriggerReactivityWithLoop(String rhs) { .isEqualTo(10); } - @Test - public void modifyInsideIfFalseBlock_shouldNotTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideIfFalseBlock_shouldNotTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7493 - statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(" if (false) {\n" + + statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(runType, dialect, " if (false) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value1", 2) + "\n" + + " " + setValueStatement(dialect, "value1", 2) + "\n" + " }\n" + " }\n"); } - @Test - public void updateInsideIfFalseBlock_shouldNotTriggerReactivity() { - statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(" if (false) {\n" + - " $fact." + setValueStatement("value1", 2) + "\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideIfFalseBlock_shouldNotTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(runType, dialect, " if (false) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + " update($fact);\n" + " }\n"); } - private void statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(String rhs) { + private void statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(RUN_TYPE runType, Dialect dialect, String rhs) { final String str = "import " + Fact.class.getCanonicalName() + ";\n" + "dialect \"" + dialect.name().toLowerCase() + "\"\n" + @@ -321,7 +342,7 @@ private void statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(S " results.add(\"R2 fired\");\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityTest.java index 66b9b8549c4..8c16a9c5a51 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityTest.java @@ -30,8 +30,9 @@ import org.drools.model.codegen.execmodel.domain.Pet; import org.drools.model.codegen.execmodel.domain.Result; import org.drools.model.codegen.execmodel.domain.VariousCasePropFact; - -import org.junit.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.Message.Level; import org.kie.api.definition.type.Modifies; @@ -42,12 +43,9 @@ public class PropertyReactivityTest extends BaseModelTest { - public PropertyReactivityTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testPropertyReactivity() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivity(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -57,7 +55,7 @@ public void testPropertyReactivity() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -66,8 +64,9 @@ public void testPropertyReactivity() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testPropertyReactivityWithUpdate() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityWithUpdate(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -78,7 +77,7 @@ public void testPropertyReactivityWithUpdate() { " update($p);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -87,8 +86,9 @@ public void testPropertyReactivityWithUpdate() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testPropertyReactivityMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityMvel(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -98,7 +98,7 @@ public void testPropertyReactivityMvel() { " modify($p) { age = $p.age+1 };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -107,8 +107,9 @@ public void testPropertyReactivityMvel() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testPropertyReactivityMvelWithUpdate() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityMvelWithUpdate(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -119,7 +120,7 @@ public void testPropertyReactivityMvelWithUpdate() { " update($p);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -128,8 +129,9 @@ public void testPropertyReactivityMvelWithUpdate() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testWatch() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatch(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -139,7 +141,7 @@ public void testWatch() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -148,8 +150,9 @@ public void testWatch() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testWatchAll() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchAll(RUN_TYPE runType) { // DROOLS-4509 final String str = @@ -161,7 +164,7 @@ public void testWatchAll() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -170,8 +173,9 @@ public void testWatchAll() { assertThat(p.getAge()).isEqualTo(50); } - @Test - public void testWatchAllBeforeBeta() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchAllBeforeBeta(RUN_TYPE runType) { // DROOLS-4509 final String str = @@ -185,7 +189,7 @@ public void testWatchAllBeforeBeta() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -195,8 +199,9 @@ public void testWatchAllBeforeBeta() { assertThat(p.getAge()).isEqualTo(50); } - @Test - public void testWatchAllBeforeFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchAllBeforeFrom(RUN_TYPE runType) { // DROOLS-4509 final String str = @@ -210,7 +215,7 @@ public void testWatchAllBeforeFrom() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); p.addAddress( new Address( "Milan" ) ); @@ -221,8 +226,9 @@ public void testWatchAllBeforeFrom() { assertThat(p.getAge()).isEqualTo(50); } - @Test - public void testImplicitWatch() { + @ParameterizedTest + @MethodSource("parameters") + public void testImplicitWatch(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -234,7 +240,7 @@ public void testImplicitWatch() { " $r.setValue($p2.getName() + \" is older than \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert(result); @@ -262,8 +268,9 @@ public void testImplicitWatch() { assertThat(result.getValue()).isEqualTo("Edson is older than Mark"); } - @Test - public void testImplicitWatchWithDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testImplicitWatchWithDeclaration(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -275,7 +282,7 @@ public void testImplicitWatchWithDeclaration() { " $r.setValue($p2.getName() + \" is older than \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert(result); @@ -303,8 +310,9 @@ public void testImplicitWatchWithDeclaration() { assertThat(result.getValue()).isEqualTo("Edson is older than Mark"); } - @Test - public void testImmutableField() { + @ParameterizedTest + @MethodSource("parameters") + public void testImmutableField(RUN_TYPE runType) { final String str = "declare Integer @propertyReactive end\n" + "declare Long @propertyReactive end\n" + @@ -314,16 +322,17 @@ public void testImmutableField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 42 ); ksession.insert( 42L ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - - @Test(timeout = 5000L) - public void testPRAfterAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(5000) + public void testPRAfterAccumulate(RUN_TYPE runType) { // DROOLS-2427 final String str = "import " + Order.class.getCanonicalName() + "\n" + @@ -338,7 +347,7 @@ public void testPRAfterAccumulate() { " modify($o) { setPrice(10) }\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Order order = new Order( Arrays.asList(new OrderLine( 9 ), new OrderLine( 8 )), 12 ); ksession.insert( order ); @@ -396,8 +405,10 @@ public String getValue() { public void setValue(String value) {} } - @Test(timeout = 5000L) - public void testPRWithAddOnList() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(5000) + public void testPRWithAddOnList(RUN_TYPE runType) { final String str = "import " + Bean.class.getCanonicalName() + "\n" + "rule R when\n" + @@ -407,14 +418,15 @@ public void testPRWithAddOnList() { " update($b);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Bean() ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testPRWithUpdateOnList() { + @ParameterizedTest + @MethodSource("parameters") + public void testPRWithUpdateOnList(RUN_TYPE runType) { final String str = "import " + List.class.getCanonicalName() + "\n" + "rule R1 when\n" + @@ -428,14 +440,15 @@ public void testPRWithUpdateOnList() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ArrayList() ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testPROnAtomic() { + @ParameterizedTest + @MethodSource("parameters") + public void testPROnAtomic(RUN_TYPE runType) { final String str = "import " + AtomicInteger.class.getCanonicalName() + "\n" + "rule R2 when\n" + @@ -446,33 +459,41 @@ public void testPROnAtomic() { " update($i);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new AtomicInteger(0)); assertThat(ksession.fireAllRules()).isEqualTo(3); } - @Test(timeout = 10000L) - public void testPropertyReactivityWith2Rules() { - checkPropertyReactivityWith2Rules( "age == 41\n" ); + @ParameterizedTest + @MethodSource("parameters") + @Timeout(10000) + public void testPropertyReactivityWith2Rules(RUN_TYPE runType) { + checkPropertyReactivityWith2Rules(runType, "age == 41\n"); } - @Test(timeout = 10000L) - public void testPropertyReactivityWith2RulesUsingAccessor() { - checkPropertyReactivityWith2Rules( "getAge() == 41\n" ); + @ParameterizedTest + @MethodSource("parameters") + @Timeout(10000) + public void testPropertyReactivityWith2RulesUsingAccessor(RUN_TYPE runType) { + checkPropertyReactivityWith2Rules(runType, "getAge() == 41\n"); } - @Test(timeout = 10000L) - public void testPropertyReactivityWith2RulesLiteralFirst() { - checkPropertyReactivityWith2Rules( "41 == age\n" ); + @ParameterizedTest + @MethodSource("parameters") + @Timeout(10000) + public void testPropertyReactivityWith2RulesLiteralFirst(RUN_TYPE runType) { + checkPropertyReactivityWith2Rules(runType, "41 == age\n"); } - @Test(timeout = 10000L) - public void testPropertyReactivityWith2RulesLiteralFirstUsingAccessor() { - checkPropertyReactivityWith2Rules( "41 == getAge()\n" ); + @ParameterizedTest + @MethodSource("parameters") + @Timeout(10000) + public void testPropertyReactivityWith2RulesLiteralFirstUsingAccessor(RUN_TYPE runType) { + checkPropertyReactivityWith2Rules(runType, "41 == getAge()\n"); } - private void checkPropertyReactivityWith2Rules( String constraint ) { + private void checkPropertyReactivityWith2Rules(RUN_TYPE runType, String constraint) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -487,7 +508,7 @@ private void checkPropertyReactivityWith2Rules( String constraint ) { " modify($p) { setEmployed( true ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person( "Mario", 40 ); ksession.insert( p ); @@ -497,8 +518,9 @@ private void checkPropertyReactivityWith2Rules( String constraint ) { assertThat(p.getEmployed()).isTrue(); } - @Test - public void testReassignment() { + @ParameterizedTest + @MethodSource("parameters") + public void testReassignment(RUN_TYPE runType) { // DROOLS-4884 final String str = "package com.example\n" + @@ -523,13 +545,14 @@ public void testReassignment() { " update($c);\n" + "end\n\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules(5)).isEqualTo(5); } - @Test - public void testReassignment2() { + @ParameterizedTest + @MethodSource("parameters") + public void testReassignment2(RUN_TYPE runType) { // DROOLS-4884 final String str = "package com.example\n" + @@ -554,13 +577,14 @@ public void testReassignment2() { " update($c);\n" + "end\n\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules(5)).isEqualTo(2); } - @Test - public void testMultipleFieldUpdate() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleFieldUpdate(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -575,7 +599,7 @@ public void testMultipleFieldUpdate() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); p.setLikes("Beer"); @@ -585,8 +609,9 @@ public void testMultipleFieldUpdate() { assertThat(p.getAge()).isEqualTo(42); } - @Test - public void testComplexSetterArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexSetterArgument(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R \n" + @@ -596,7 +621,7 @@ public void testComplexSetterArgument() { " modify($p) { setLikes( String.valueOf(($p.getAddress().getStreet() + $p.getAddress().getCity()))) };\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); me.setAddress(new Address("street1", 2, "city1")); @@ -607,8 +632,9 @@ public void testComplexSetterArgument() { assertThat(me.getLikes()).isEqualTo("street1city1"); } - @Test - public void thisWithGetter() { + @ParameterizedTest + @MethodSource("parameters") + public void thisWithGetter(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R \n" + @@ -618,7 +644,7 @@ public void thisWithGetter() { " modify($p) { setLikes(\"Cheese\") };\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); me.setAddress(new Address("street1", 2, "city1")); @@ -627,8 +653,9 @@ public void thisWithGetter() { assertThat(ksession.fireAllRules(10)).as("should not loop").isEqualTo(1); } - @Test - public void nullSafeDereferencing() { + @ParameterizedTest + @MethodSource("parameters") + public void nullSafeDereferencing(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R \n" + @@ -638,7 +665,7 @@ public void nullSafeDereferencing() { " modify($p) { setLikes(\"Cheese\") };\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); me.setAddress(new Address("street1", 2, "city1")); @@ -647,8 +674,9 @@ public void nullSafeDereferencing() { assertThat(ksession.fireAllRules(10)).as("should not loop").isEqualTo(1); } - @Test - public void testNestedPropInRHS() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedPropInRHS(RUN_TYPE runType) throws Exception { // Property Reactivity for "owner" final String str = "package org.drools.test;\n" + @@ -665,7 +693,7 @@ public void testNestedPropInRHS() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Pet pet = new Pet(Pet.PetType.cat); Person person = new Person("John"); @@ -677,8 +705,9 @@ public void testNestedPropInRHS() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testDeeplyNestedPropInRHS() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeeplyNestedPropInRHS(RUN_TYPE runType) throws Exception { // Property Reactivity for "owner" final String str = "package org.drools.test;\n" + @@ -695,7 +724,7 @@ public void testDeeplyNestedPropInRHS() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Pet pet = new Pet(Pet.PetType.cat); Person person = new Person("John"); @@ -707,8 +736,9 @@ public void testDeeplyNestedPropInRHS() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testOutsideModifyBlockWithGetterAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testOutsideModifyBlockWithGetterAsArgument(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -719,7 +749,7 @@ public void testOutsideModifyBlockWithGetterAsArgument() { " modify($p) { setAge(41) };\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -729,8 +759,9 @@ public void testOutsideModifyBlockWithGetterAsArgument() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testOutsideModifyBlockWithNonGetterAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testOutsideModifyBlockWithNonGetterAsArgument(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -741,7 +772,7 @@ public void testOutsideModifyBlockWithNonGetterAsArgument() { " modify($p) { setAge(41) };\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -751,8 +782,9 @@ public void testOutsideModifyBlockWithNonGetterAsArgument() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testMultipleModifyBlocksWithNonGetterAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleModifyBlocksWithNonGetterAsArgument(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Address.class.getCanonicalName() + ";\n" + @@ -768,7 +800,7 @@ public void testMultipleModifyBlocksWithNonGetterAsArgument() { " modify($a) { setNumber(20) };\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -783,8 +815,9 @@ public void testMultipleModifyBlocksWithNonGetterAsArgument() { assertThat(a.getNumber()).isEqualTo(20); } - @Test - public void testUpdateWithGetterAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testUpdateWithGetterAsArgument(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -796,7 +829,7 @@ public void testUpdateWithGetterAsArgument() { " update($p);\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -806,8 +839,9 @@ public void testUpdateWithGetterAsArgument() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUpdateWithNonGetterAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testUpdateWithNonGetterAsArgument(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -819,7 +853,7 @@ public void testUpdateWithNonGetterAsArgument() { " update($p);\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -829,8 +863,9 @@ public void testUpdateWithNonGetterAsArgument() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUpdateWithNonGetterAsDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testUpdateWithNonGetterAsDeclaration(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -843,7 +878,7 @@ public void testUpdateWithNonGetterAsDeclaration() { " update($p);\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -853,8 +888,9 @@ public void testUpdateWithNonGetterAsDeclaration() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUpdateWithNonGetterIntentinalLoop() { + @ParameterizedTest + @MethodSource("parameters") + public void testUpdateWithNonGetterIntentinalLoop(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -866,7 +902,7 @@ public void testUpdateWithNonGetterIntentinalLoop() { " update($p);\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -879,8 +915,9 @@ public void testUpdateWithNonGetterIntentinalLoop() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testPropertyReactivityOnBoundVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityOnBoundVariable(RUN_TYPE runType) { // RHDM-1387 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -891,7 +928,7 @@ public void testPropertyReactivityOnBoundVariable() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -904,8 +941,9 @@ public static int dummy(int i) { return i; } - @Test - public void testWatchCallingExternalMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchCallingExternalMethod(RUN_TYPE runType) { // DROOLS-5514 final String str = "import static " + this.getClass().getCanonicalName() + ".dummy;\n" + @@ -917,7 +955,7 @@ public void testWatchCallingExternalMethod() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -926,8 +964,9 @@ public void testWatchCallingExternalMethod() { assertThat(p.getAge()).isEqualTo(50); } - @Test - public void testWatchCallingExternalMethod2() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchCallingExternalMethod2(RUN_TYPE runType) { // DROOLS-5514 final String str = "import static " + this.getClass().getCanonicalName() + ".dummy;\n" + @@ -939,7 +978,7 @@ public void testWatchCallingExternalMethod2() { " modify($p) { setName( $p.getName()+\"1\" ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -948,8 +987,9 @@ public void testWatchCallingExternalMethod2() { assertThat(p.getName()).isEqualTo("Mario111"); } - @Test - public void testWatchCallingExternalMethod3() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchCallingExternalMethod3(RUN_TYPE runType) { // DROOLS-5514 final String str = "import static " + this.getClass().getCanonicalName() + ".dummy;\n" + @@ -961,7 +1001,7 @@ public void testWatchCallingExternalMethod3() { " modify($p) { setName( $p.getName()+\"1\" ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -970,8 +1010,9 @@ public void testWatchCallingExternalMethod3() { assertThat(p.getName()).isEqualTo("Mario1"); } - @Test - public void test2PropertiesInOneExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void test2PropertiesInOneExpression(RUN_TYPE runType) { // DROOLS-5677 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -998,7 +1039,7 @@ public void test2PropertiesInOneExpression() { " modify($p) { setSalary( 100 ) };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John", 0); p.setSalary(0); @@ -1011,8 +1052,9 @@ public void test2PropertiesInOneExpression() { assertThat(p.getSalary().intValue()).isEqualTo(20); // R2 should be cancelled } - @Test - public void test3PropertiesInOneExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void test3PropertiesInOneExpression(RUN_TYPE runType) { // DROOLS-5677 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1046,7 +1088,7 @@ public void test3PropertiesInOneExpression() { " modify($p) { setSalary( 100 ) };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John", 0); p.setSalary(0); @@ -1109,8 +1151,9 @@ public static String convertToString(int num) { return "BIG"; } - @Test - public void testExternalFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalFunction(RUN_TYPE runType) { // BAPL-1773 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + @@ -1122,7 +1165,7 @@ public void testExternalFunction() { " modify($fact) { setResult(\"OK\") };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Fact fact = new Fact(); fact.setA(99999); @@ -1133,8 +1176,9 @@ public void testExternalFunction() { assertThat(fact.getResult()).isEqualTo("OK"); } - @Test - public void testExternalFunction2() { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalFunction2(RUN_TYPE runType) { // BAPL-1773 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + @@ -1146,7 +1190,7 @@ public void testExternalFunction2() { " modify($fact) { setA(99999) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Fact fact = new Fact(); fact.setA(99999); @@ -1156,8 +1200,9 @@ public void testExternalFunction2() { assertThat(ksession.fireAllRules(3)).isEqualTo(3); } - @Test - public void externalFunctionWithBindVariable_shouldNotCauseInfiniteLoop() { + @ParameterizedTest + @MethodSource("parameters") + public void externalFunctionWithBindVariable_shouldNotCauseInfiniteLoop(RUN_TYPE runType) { // DROOLS-7372 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + "import static " + PropertyReactivityTest.class.getCanonicalName() + ".*;\n" + @@ -1168,7 +1213,7 @@ public void externalFunctionWithBindVariable_shouldNotCauseInfiniteLoop() { " modify($fact) { setResult(\"OK\") };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Fact bigString = new Fact(); bigString.setA(99999); @@ -1181,8 +1226,9 @@ public void externalFunctionWithBindVariable_shouldNotCauseInfiniteLoop() { assertThat(bigString.getResult()).isEqualTo("OK"); } - @Test - public void externalFunctionWithBindVariableFromAnotherPatternOfSameType_shouldTriggerClassReactive() { + @ParameterizedTest + @MethodSource("parameters") + public void externalFunctionWithBindVariableFromAnotherPatternOfSameType_shouldTriggerClassReactive(RUN_TYPE runType) { // DROOLS-7398 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + @@ -1194,7 +1240,7 @@ public void externalFunctionWithBindVariableFromAnotherPatternOfSameType_shouldT " modify($fact2) { setResult(\"OK\") };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Fact bigStringFact = new Fact(); bigStringFact.setA(99999); @@ -1206,8 +1252,9 @@ public void externalFunctionWithBindVariableFromAnotherPatternOfSameType_shouldT .isEqualTo(10); } - @Test - public void multipleExternalFunctionsWithBindVariablesFromAnotherPatternOfSameType_shouldTriggerClassReactive() { + @ParameterizedTest + @MethodSource("parameters") + public void multipleExternalFunctionsWithBindVariablesFromAnotherPatternOfSameType_shouldTriggerClassReactive(RUN_TYPE runType) { // DROOLS-7398 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + @@ -1219,7 +1266,7 @@ public void multipleExternalFunctionsWithBindVariablesFromAnotherPatternOfSameTy " modify($fact2) { setResult(\"OK\") };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Fact bigStringFact = new Fact(); bigStringFact.setA(99999); @@ -1232,8 +1279,9 @@ public void multipleExternalFunctionsWithBindVariablesFromAnotherPatternOfSameTy .isEqualTo(10); } - @Test - public void externalFunctionWithBindVariableFromAnotherPatternOfDifferentType_shouldTriggerClassReactive() { + @ParameterizedTest + @MethodSource("parameters") + public void externalFunctionWithBindVariableFromAnotherPatternOfDifferentType_shouldTriggerClassReactive(RUN_TYPE runType) { // DROOLS-7390 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + @@ -1246,7 +1294,7 @@ public void externalFunctionWithBindVariableFromAnotherPatternOfDifferentType_sh " modify($fact2) { setResult(\"OK\") };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); AnotherFact bigStringAnotherFact = new AnotherFact(); bigStringAnotherFact.setA(99999); @@ -1262,8 +1310,9 @@ public void externalFunctionWithBindVariableFromAnotherPatternOfDifferentType_sh .isEqualTo(10); } - @Test - public void testUnwatch() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnwatch(RUN_TYPE runType) { // RHDM-1553 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1274,7 +1323,7 @@ public void testUnwatch() { " modify($p) { setAge( $p.getAge() + 1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1283,8 +1332,9 @@ public void testUnwatch() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUnwatchWithFieldBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnwatchWithFieldBinding(RUN_TYPE runType) { // RHDM-1553 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1295,7 +1345,7 @@ public void testUnwatchWithFieldBinding() { " modify($p) { setAge( $age + 1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1304,8 +1354,9 @@ public void testUnwatchWithFieldBinding() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUnwatchWithFieldBindingAndMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnwatchWithFieldBindingAndMvel(RUN_TYPE runType) { // RHDM-1553 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1316,7 +1367,7 @@ public void testUnwatchWithFieldBindingAndMvel() { " modify($p) { age = $age + 1 };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1325,8 +1376,9 @@ public void testUnwatchWithFieldBindingAndMvel() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUnwatchWithWatchedField() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnwatchWithWatchedField(RUN_TYPE runType) { // RHDM-1553 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1337,7 +1389,7 @@ public void testUnwatchWithWatchedField() { " modify($p) { setAge( $p.getAge() + 1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1346,8 +1398,9 @@ public void testUnwatchWithWatchedField() { assertThat(p.getAge()).isEqualTo(43); } - @Test - public void testNoConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoConstraint(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -1357,7 +1410,7 @@ public void testNoConstraint() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1366,8 +1419,9 @@ public void testNoConstraint() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testNoConstraintWithUpdate() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoConstraintWithUpdate(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -1378,7 +1432,7 @@ public void testNoConstraintWithUpdate() { " update($p);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1387,8 +1441,9 @@ public void testNoConstraintWithUpdate() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testModifiesAnnotation() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifiesAnnotation(RUN_TYPE runType) { final String str = "import " + Light.class.getCanonicalName() + ";\n" + "\n" + @@ -1398,7 +1453,7 @@ public void testModifiesAnnotation() { " modify($l) { turnOn() };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Light l = new Light("Alert"); ksession.insert( l ); @@ -1437,8 +1492,9 @@ public void setName(String name) { } } - @Test - public void testSettersInAndOutModifyBlock() { + @ParameterizedTest + @MethodSource("parameters") + public void testSettersInAndOutModifyBlock(RUN_TYPE runType) { // RHDM-1552 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1450,7 +1506,7 @@ public void testSettersInAndOutModifyBlock() { " modify($p) { setName( \"Mario\" ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1459,8 +1515,9 @@ public void testSettersInAndOutModifyBlock() { assertThat(p.getAge()).isEqualTo(43); } - @Test - public void testSettersInAndOutModifyBlockMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testSettersInAndOutModifyBlockMvel(RUN_TYPE runType) { // RHDM-1552 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1472,7 +1529,7 @@ public void testSettersInAndOutModifyBlockMvel() { " modify($p) { name = \"Mario\" };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1481,8 +1538,9 @@ public void testSettersInAndOutModifyBlockMvel() { assertThat(p.getAge()).isEqualTo(43); } - @Test - public void testMvelModifyBlockWithComma() { + @ParameterizedTest + @MethodSource("parameters") + public void testMvelModifyBlockWithComma(RUN_TYPE runType) { // RHDM-1552 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1493,7 +1551,7 @@ public void testMvelModifyBlockWithComma() { " modify($p) { setName(\"Mario\"), age = $p.age + 1 };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1542,8 +1600,9 @@ private static class StackFrame { } } - @Test - public void testUpdateNonPropertyInMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testUpdateNonPropertyInMvel(RUN_TYPE runType) { // DROOLS-6096 final String str = "import " + AssessmentContext.class.getCanonicalName() + ";\n" + @@ -1567,7 +1626,7 @@ public void testUpdateNonPropertyInMvel() { " update($ac);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); AssessmentContext ac1 = new AssessmentContext(); ac1.pushStackFrame(null); @@ -1578,8 +1637,9 @@ public void testUpdateNonPropertyInMvel() { assertThat(ksession.fireAllRules(2)).isEqualTo(2); } - @Test - public void testPropertyReactivityWithPublicField() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityWithPublicField(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -1596,7 +1656,7 @@ public void testPropertyReactivityWithPublicField() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John"); p.publicAge = 40; @@ -1607,8 +1667,9 @@ public void testPropertyReactivityWithPublicField() { assertThat(p.publicAge).isEqualTo(41); } - @Test - public void testUnknownPropertyNameInWatch() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testUnknownPropertyNameInWatch(RUN_TYPE runType) throws Exception { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -1624,12 +1685,13 @@ public void testUnknownPropertyNameInWatch() throws Exception { " modify($p) { setAge(20) }\n" + "end\n"; - KieBuilder kbuilder = createKieBuilder(str); + KieBuilder kbuilder = createKieBuilder(runType, str); assertThat(kbuilder.getResults().hasMessages(Level.ERROR)).isTrue(); } - @Test - public void testSetterWithoutGetter() { + @ParameterizedTest + @MethodSource("parameters") + public void testSetterWithoutGetter(RUN_TYPE runType) { // DROOLS-6523 final String str = "import " + ClassWithValue.class.getCanonicalName() + ";\n" + @@ -1640,7 +1702,7 @@ public void testSetterWithoutGetter() { " update($cwv);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ClassWithValue cwv = new ClassWithValue(); ksession.insert(cwv); @@ -1671,8 +1733,9 @@ public void addDoubleValue(double doubleValue) { } } - @Test - public void testPropertyReactivityOn2Properties() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityOn2Properties(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -1685,7 +1748,7 @@ public void testPropertyReactivityOn2Properties() { " };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1695,8 +1758,9 @@ public void testPropertyReactivityOn2Properties() { assertThat(p.getId()).isEqualTo(1); } - @Test - public void testPropertyReactivityOn2PropertiesWithWrongSeparator() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityOn2PropertiesWithWrongSeparator(RUN_TYPE runType) { // DROOLS-6480 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1710,12 +1774,13 @@ public void testPropertyReactivityOn2PropertiesWithWrongSeparator() { " };\n" + "end\n"; - KieBuilder kbuilder = createKieBuilder(str); + KieBuilder kbuilder = createKieBuilder(runType, str); assertThat(kbuilder.getResults().hasMessages(Level.ERROR)).isTrue(); } - @Test - public void testMvelModifyAfterSingleQuote() { + @ParameterizedTest + @MethodSource("parameters") + public void testMvelModifyAfterSingleQuote(RUN_TYPE runType) { // DROOLS-6542 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1733,7 +1798,7 @@ public void testMvelModifyAfterSingleQuote() { " insert(\"ok\");\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1743,38 +1808,43 @@ public void testMvelModifyAfterSingleQuote() { assertThat(ksession.getObjects((Object object) -> object.equals("ok")).size()).isEqualTo(1); } - @Test - public void testOnlyFirstLetterIsUpperCaseProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testOnlyFirstLetterIsUpperCaseProperty(RUN_TYPE runType) { // See JavaBeans 1.01 spec : 8.8 Capitalization of inferred names // “FooBah” becomes “fooBah” - testVariousCasePropFact("modify($f) { MyTarget = \"123\" };", "R1", "R2"); // Actually, this modifies "myTarget" property (backed by private "MyTarget" field). This shouldn't react R1 + testVariousCasePropFact(runType, "modify($f) { MyTarget = \"123\" };", "R1", "R2"); // Actually, this modifies "myTarget" property (backed by private "MyTarget" field). This shouldn't react R1 } - @Test - public void testTwoFirstLettersAreUpperCaseProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoFirstLettersAreUpperCaseProperty(RUN_TYPE runType) { // See JavaBeans 1.01 spec : 8.8 Capitalization of inferred names // “URL” becomes “URL” - testVariousCasePropFact("modify($f) { URL = \"123\" };", "R1", "R2"); // This shouldn't react R1 + testVariousCasePropFact(runType, "modify($f) { URL = \"123\" };", "R1", "R2"); // This shouldn't react R1 } - @Test - public void testFirstLetterIsMultibyteProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testFirstLetterIsMultibyteProperty(RUN_TYPE runType) { // Multibyte is not mentioned in JavaBeans spec - testVariousCasePropFact("modify($f) { 名前 = \"123\" };", "R1", "R2"); // This shouldn't react R1 + testVariousCasePropFact(runType, "modify($f) { 名前 = \"123\" };", "R1", "R2"); // This shouldn't react R1 } - @Test - public void testOnlyFirstLetterIsUpperCaseAndMultibyteProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testOnlyFirstLetterIsUpperCaseAndMultibyteProperty(RUN_TYPE runType) { // Multibyte is not mentioned in JavaBeans spec - testVariousCasePropFact("modify($f) { My名前 = \"123\" };", "R1", "R2"); // Actually, this modifies "my名前" property (backed by private "My名前" field). This shouldn't react R1 + testVariousCasePropFact(runType, "modify($f) { My名前 = \"123\" };", "R1", "R2"); // Actually, this modifies "my名前" property (backed by private "My名前" field). This shouldn't react R1 } - @Test - public void testOnlyFirstLetterIsUpperCasePublicFieldProperty() { - testVariousCasePropFact("modify($f) { MyPublicTarget = \"123\" };", "R1", "R2"); // this modifies "MyPublicTarget" public field directly. This shouldn't react R1 + @ParameterizedTest + @MethodSource("parameters") + public void testOnlyFirstLetterIsUpperCasePublicFieldProperty(RUN_TYPE runType) { + testVariousCasePropFact(runType, "modify($f) { MyPublicTarget = \"123\" };", "R1", "R2"); // this modifies "MyPublicTarget" public field directly. This shouldn't react R1 } - private void testVariousCasePropFact(String modifyStatement, String... expectedResults) { + private void testVariousCasePropFact(RUN_TYPE runType, String modifyStatement, String... expectedResults) { final String str = "import " + VariousCasePropFact.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1795,7 +1865,7 @@ private void testVariousCasePropFact(String modifyStatement, String... expectedR modifyStatement + "\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1807,8 +1877,9 @@ private void testVariousCasePropFact(String modifyStatement, String... expectedR assertThat(results).containsExactly(expectedResults); } - @Test - public void bindOnlyPropertyReacts() { + @ParameterizedTest + @MethodSource("parameters") + public void bindOnlyPropertyReacts(RUN_TYPE runType) { // DROOLS-7214 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1819,7 +1890,7 @@ public void bindOnlyPropertyReacts() { " modify($p) { age = $age + 1 };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -1828,8 +1899,9 @@ public void bindOnlyPropertyReacts() { assertThat(fired).isEqualTo(10); } - @Test - public void bindOnlyMapPropertyReacts() { + @ParameterizedTest + @MethodSource("parameters") + public void bindOnlyMapPropertyReacts(RUN_TYPE runType) { // DROOLS-7214 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1841,7 +1913,7 @@ public void bindOnlyMapPropertyReacts() { " modify($p) { itemsString = $p.itemsString };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); p.getItemsString().put("A", "itemA"); @@ -1851,8 +1923,9 @@ public void bindOnlyMapPropertyReacts() { assertThat(fired).isEqualTo(10); } - @Test - public void bindOnlyMapPropertyWithAccessOperatorReacts() { + @ParameterizedTest + @MethodSource("parameters") + public void bindOnlyMapPropertyWithAccessOperatorReacts(RUN_TYPE runType) { // DROOLS-7214 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1864,7 +1937,7 @@ public void bindOnlyMapPropertyWithAccessOperatorReacts() { " modify($p) { itemsString = $p.itemsString };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); p.getItemsString().put("A", "itemA"); @@ -1874,8 +1947,9 @@ public void bindOnlyMapPropertyWithAccessOperatorReacts() { assertThat(fired).isEqualTo(10); } - @Test - public void bindOnlyListPropertyWithAccessOperatorReacts() { + @ParameterizedTest + @MethodSource("parameters") + public void bindOnlyListPropertyWithAccessOperatorReacts(RUN_TYPE runType) { // DROOLS-7214 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1888,7 +1962,7 @@ public void bindOnlyListPropertyWithAccessOperatorReacts() { " modify($p) { addresses = $p.addresses };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); p.getAddresses().add(new Address("A")); @@ -1899,8 +1973,9 @@ public void bindOnlyListPropertyWithAccessOperatorReacts() { assertThat(fired).isEqualTo(10); } - @Test - public void testPropertyReactivityWithRedundantVariableDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityWithRedundantVariableDeclaration(RUN_TYPE runType) { // KIE-DROOLS-5943 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1912,7 +1987,7 @@ public void testPropertyReactivityWithRedundantVariableDeclaration() { " update($p);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypeTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypeTest.java index 7e3ccd1154d..05a4202a55a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypeTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypeTest.java @@ -49,7 +49,7 @@ import org.drools.model.prototype.PrototypeExpression; import org.drools.model.prototype.PrototypeVariable; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.conf.EventProcessingOption; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypesAllowedTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypesAllowedTest.java index 28c257ea97e..1eb18501903 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypesAllowedTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypesAllowedTest.java @@ -30,7 +30,7 @@ import org.drools.model.impl.ModelImpl; import org.drools.model.prototype.PrototypeVariable; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.conf.PrototypesOption; import org.kie.api.io.ResourceType; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/QueryTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/QueryTest.java index 65f5cc039af..e06419bf327 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/QueryTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/QueryTest.java @@ -31,7 +31,8 @@ import org.drools.model.codegen.execmodel.domain.Result; import org.drools.model.codegen.execmodel.oopathdtables.InternationalAddress; import org.drools.model.codegen.execmodel.util.TrackingAgendaEventListener; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.command.Command; import org.kie.api.definition.type.FactType; @@ -46,12 +47,9 @@ public class QueryTest extends BaseModelTest { - public QueryTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testQueryZeroArgs() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryZeroArgs(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.lang.Integer ageG;" + @@ -59,7 +57,7 @@ public void testQueryZeroArgs() { " $p : Person(age > ageG)\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("ageG", 40); @@ -75,15 +73,16 @@ public void testQueryZeroArgs() { } - @Test - public void testQueryOneArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryOneArgument(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query olderThan( int $age )\n" + " $p : Person(age > $age)\n" + "end "; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -95,15 +94,16 @@ public void testQueryOneArgument() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testQueryOneArgumentWithoutType() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryOneArgumentWithoutType(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query olderThan( $age )\n" + " $p : Person(age > (Integer)$age)\n" + "end "; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -115,8 +115,9 @@ public void testQueryOneArgumentWithoutType() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testQueryInRule() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryInRule(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -129,7 +130,7 @@ public void testQueryInRule() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -141,8 +142,9 @@ public void testQueryInRule() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testQueryInRuleWithDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryInRuleWithDeclaration(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -156,7 +158,7 @@ public void testQueryInRuleWithDeclaration() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -170,8 +172,9 @@ public void testQueryInRuleWithDeclaration() { } - @Test - public void testQueryInvokedWithGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryInvokedWithGlobal(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -186,7 +189,7 @@ public void testQueryInvokedWithGlobal() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("ageG", 40); @@ -201,8 +204,9 @@ public void testQueryInvokedWithGlobal() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testNonPositionalQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testNonPositionalQuery(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -210,7 +214,7 @@ public void testNonPositionalQuery() { " $p : Person(name == $n, age == $a)\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -222,15 +226,16 @@ public void testNonPositionalQuery() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testPositionalQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalQuery(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query findPerson( String $n, int $a )\n" + " $p : Person($n, $a;)\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -242,15 +247,16 @@ public void testPositionalQuery() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testUnificationParameterInPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnificationParameterInPattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query personsAges(int ages)\n" + "$p : Person(ages := age)\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -262,8 +268,9 @@ public void testUnificationParameterInPattern() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testQueryCallingQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryCallingQuery(RUN_TYPE runType) { String str = "import " + Relationship.class.getCanonicalName() + ";" + "query isRelatedTo(String x, String y)\n" + @@ -273,7 +280,7 @@ public void testQueryCallingQuery() { " Relationship(x, y;)\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Relationship( "A", "B" ) ); ksession.insert( new Relationship( "B", "C" ) ); @@ -286,8 +293,9 @@ public void testQueryCallingQuery() { } - @Test - public void testQueryWithOOPath() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithOOPath(RUN_TYPE runType) { String str = "import " + java.util.List.class.getCanonicalName() + ";" + "import " + org.drools.model.codegen.execmodel.oopathdtables.Person.class.getCanonicalName() + ";" + @@ -297,7 +305,7 @@ public void testQueryWithOOPath() { "$cities : List() from accumulate (Person ( $city: /address#InternationalAddress[state == \"Safecountry\"]/city), collectList($city))\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); org.drools.model.codegen.execmodel.oopathdtables.Person person = new org.drools.model.codegen.execmodel.oopathdtables.Person(); person.setAddress(new InternationalAddress("", 1, "Milan", "Safecountry")); @@ -314,8 +322,9 @@ public void testQueryWithOOPath() { assertThat(cities.get(0)).isEqualTo("Milan"); } - @Test - public void testQueryWithOOPathTransformedToFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithOOPathTransformedToFrom(RUN_TYPE runType) { String str = "import " + java.util.List.class.getCanonicalName() + ";" + "import " + org.drools.model.codegen.execmodel.oopathdtables.Person.class.getCanonicalName() + ";" + @@ -327,7 +336,7 @@ public void testQueryWithOOPathTransformedToFrom() { "$cities : List() from accumulate ($city : String() from $a.city, collectList($city))\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); org.drools.model.codegen.execmodel.oopathdtables.Person person = new org.drools.model.codegen.execmodel.oopathdtables.Person(); person.setAddress(new InternationalAddress("", 1, "Milan", "Safecountry")); @@ -344,8 +353,9 @@ public void testQueryWithOOPathTransformedToFrom() { assertThat(cities.get(0)).isEqualTo("Milan"); } - @Test - public void testQueryWithOOPathTransformedToFromInsideAcc() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithOOPathTransformedToFromInsideAcc(RUN_TYPE runType) { String str = "import " + java.util.List.class.getCanonicalName() + ";" + "import " + org.drools.model.codegen.execmodel.oopathdtables.Person.class.getCanonicalName() + ";" + @@ -358,7 +368,7 @@ public void testQueryWithOOPathTransformedToFromInsideAcc() { " $city : String() from $a.city, collectList($city))\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); org.drools.model.codegen.execmodel.oopathdtables.Person person2 = new org.drools.model.codegen.execmodel.oopathdtables.Person(); person2.setAddress(new InternationalAddress("", 1, "Rome", "Unsafecountry")); @@ -376,8 +386,9 @@ public void testQueryWithOOPathTransformedToFromInsideAcc() { assertThat(cities.get(0)).isEqualTo("Milan"); } - @Test - public void testPositionalRecursiveQueryWithUnification() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalRecursiveQueryWithUnification(RUN_TYPE runType) { String str = "import " + Relationship.class.getCanonicalName() + ";" + "query isRelatedTo(String x, String y)\n" + @@ -386,7 +397,7 @@ public void testPositionalRecursiveQueryWithUnification() { " ( Relationship (z, y;) and ?isRelatedTo(x, z;))\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Relationship( "A", "B" ) ); ksession.insert( new Relationship( "B", "C" ) ); @@ -400,8 +411,9 @@ public void testPositionalRecursiveQueryWithUnification() { assertThat("B".equals(resultDrlx)).isTrue(); } - @Test - public void testPositionalRecursiveQuery() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalRecursiveQuery(RUN_TYPE runType) throws Exception { String query = "query isContainedIn(String x, String y)\n" + " Location (x, y;)\n" + @@ -409,11 +421,12 @@ public void testPositionalRecursiveQuery() throws Exception { " ( Location (z, y;) and ?isContainedIn(x, z;))\n" + "end\n"; - checkRecursiveQuery( query ); + checkRecursiveQuery(runType, query); } - @Test - public void testUnificationRecursiveQuery() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testUnificationRecursiveQuery(RUN_TYPE runType) throws Exception { String query = "query isContainedIn(String x, String y)\n" + " Location( x := thing, y := location)\n" + @@ -421,10 +434,10 @@ public void testUnificationRecursiveQuery() throws Exception { " ( Location(z := thing, y := location) and ?isContainedIn( x := x, z := y ) )\n" + "end\n"; - checkRecursiveQuery( query ); + checkRecursiveQuery(runType, query); } - private void checkRecursiveQuery( String query ) throws InstantiationException, IllegalAccessException { + private void checkRecursiveQuery(RUN_TYPE runType , String query) throws InstantiationException, IllegalAccessException { String str = "package org.test;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -449,7 +462,7 @@ private void checkRecursiveQuery( String query ) throws InstantiationException, // "then\n" + // "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); FactType locationType = ksession.getKieBase().getFactType("org.test", "Location"); @@ -501,8 +514,9 @@ private void checkRecursiveQuery( String query ) throws InstantiationException, assertThat(listener.isRuleFired("testPushQueryRule")).isFalse(); } - @Test - public void testRecursiveQueryWithBatchCommand() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testRecursiveQueryWithBatchCommand(RUN_TYPE runType) throws Exception { String str = "package org.test;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -517,7 +531,7 @@ public void testRecursiveQueryWithBatchCommand() throws Exception { "end"; KieServices kieServices = KieServices.Factory.get(); - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); FactType locationType = ksession.getKieBase().getFactType("org.test", "Location"); @@ -576,8 +590,9 @@ public void testRecursiveQueryWithBatchCommand() throws Exception { assertThat(l.contains("key")).isTrue(); } - @Test - public void testQueryUnificationUnset() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryUnificationUnset(RUN_TYPE runType) { String str = "package drl;\n" + "declare Anon " + " cld : String @key " + @@ -618,12 +633,13 @@ public void testQueryUnificationUnset() { "then " + "end "; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); } - @Test - public void testQueryCalling2Queries() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryCalling2Queries(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query isPersonOlderThan(Person p, int ageFrom)\n" + @@ -639,7 +655,7 @@ public void testQueryCalling2Queries() { "end\n" + "\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -651,15 +667,16 @@ public void testQueryCalling2Queries() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testQueriesWithVariableUnification() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testQueriesWithVariableUnification(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "query peeps( String $name, int $age ) \n" + " $p : Person( $name := name, $age := age ) \n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p1 = new Person( "darth", 100 ); Person p2 = new Person( "yoda", 300 ); @@ -704,8 +721,9 @@ public void testQueriesWithVariableUnification() throws Exception { assertThat(names.contains("darth")).isTrue(); } - @Test - public void testQueryWithUpdateOnFactHandle() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithUpdateOnFactHandle(RUN_TYPE runType) throws Exception { String str = "global java.util.List list; " + "query foo( Integer $i ) " + @@ -727,7 +745,7 @@ public void testQueryWithUpdateOnFactHandle() throws Exception { "end\n" + "\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -742,8 +760,9 @@ public void testQueryWithUpdateOnFactHandle() throws Exception { assertThat((int) list.get(1)).isEqualTo(22); } - @Test - public void testQueryCallWithBindings() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryCallWithBindings(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -760,7 +779,7 @@ public void testQueryCallWithBindings() { " Person( $name := name, $age := age; ) \n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -772,8 +791,9 @@ public void testQueryCallWithBindings() { assertThat(list.get(0)).isEqualTo("Mario : 44"); } - @Test - public void testQueryCallWithJoinInputAndOutput() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryCallWithJoinInputAndOutput(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -790,7 +810,7 @@ public void testQueryCallWithJoinInputAndOutput() { " list.add( $name1 + \" : \" + $age1 );\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -802,8 +822,9 @@ public void testQueryCallWithJoinInputAndOutput() { assertThat(list.get(0)).isEqualTo("Mario : 44"); } - @Test - public void testQueryWithDyanmicInsert() throws IOException, ClassNotFoundException { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithDyanmicInsert(RUN_TYPE runType) throws IOException, ClassNotFoundException { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -820,7 +841,7 @@ public void testQueryWithDyanmicInsert() throws IOException, ClassNotFoundExcept " list.add( $p );\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); try { final List list = new ArrayList<>(); @@ -837,8 +858,9 @@ public void testQueryWithDyanmicInsert() throws IOException, ClassNotFoundExcept } } - @Test - public void testQuerySameNameBinding() throws IOException, ClassNotFoundException { + @ParameterizedTest + @MethodSource("parameters") + public void testQuerySameNameBinding(RUN_TYPE runType) throws IOException, ClassNotFoundException { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -847,7 +869,7 @@ public void testQuerySameNameBinding() throws IOException, ClassNotFoundExceptio " Person( name := name ) \n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person("Mario", 44) ); ksession.insert( new Person("Mark", 40) ); @@ -870,8 +892,9 @@ public void testQuerySameNameBinding() throws IOException, ClassNotFoundExceptio assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testQuery10Args() throws IOException, ClassNotFoundException { + @ParameterizedTest + @MethodSource("parameters") + public void testQuery10Args(RUN_TYPE runType) throws IOException, ClassNotFoundException { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -880,7 +903,7 @@ public void testQuery10Args() throws IOException, ClassNotFoundException { " Person( name := name, age := age, ageLong := ageLong, id := id, likes := likes ) \n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person("Mario", 44); mario.setAgeLong(44L); @@ -908,8 +931,9 @@ public void testQuery10Args() throws IOException, ClassNotFoundException { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testPositionalQueryWithAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalQueryWithAccumulate(RUN_TYPE runType) { // DROOLS-6128 String str = "import " + Result.class.getCanonicalName() + ";" + @@ -930,7 +954,7 @@ public void testPositionalQueryWithAccumulate() { " ) \n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); QueryResults results = ksession.getQueryResults( "accAge", "Mark" ); @@ -942,8 +966,9 @@ public void testPositionalQueryWithAccumulate() { assertThat(resultDrlx).isEqualTo(37); } - @Test - public void testPositionalQueryWithAmbigousName() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalQueryWithAmbigousName(RUN_TYPE runType) { // DROOLS-6128 String str = "import " + Result.class.getCanonicalName() + ";" + @@ -964,7 +989,7 @@ public void testPositionalQueryWithAmbigousName() { " ) \n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); QueryResults results = ksession.getQueryResults( "accAge", "Mark" ); @@ -976,8 +1001,9 @@ public void testPositionalQueryWithAmbigousName() { assertThat(resultDrlx).isEqualTo(37); } - @Test - public void testQueryWithAccumulateAndUnification() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithAccumulateAndUnification(RUN_TYPE runType) { // DROOLS-6105 String str = "import " + Result.class.getCanonicalName() + ";\n" + @@ -1005,7 +1031,7 @@ public void testQueryWithAccumulateAndUnification() { " result.add($sum);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal( "result", result ); @@ -1017,8 +1043,9 @@ public void testQueryWithAccumulateAndUnification() { assertThat((int) result.get(0)).isEqualTo(37); } - @Test - public void testQueryWithAccumulateInvokingQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithAccumulateInvokingQuery(RUN_TYPE runType) { // DROOLS-6105 String str = "import " + Result.class.getCanonicalName() + ";\n" + @@ -1049,7 +1076,7 @@ public void testQueryWithAccumulateInvokingQuery() { " result.add($sum);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal( "result", result ); @@ -1061,8 +1088,9 @@ public void testQueryWithAccumulateInvokingQuery() { assertThat((int) result.get(0)).isEqualTo(37); } - @Test - public void testQueryDoubleUnification() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryDoubleUnification(RUN_TYPE runType) { // DROOLS-6105 final String str = "" + "package org.drools.compiler.test \n" + @@ -1087,7 +1115,7 @@ public void testQueryDoubleUnification() { "end\n" + ""; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); QueryResults results = ksession.getQueryResults("whereFood", Variable.v, "kitchen"); @@ -1096,8 +1124,9 @@ public void testQueryDoubleUnification() { assertThat(row.get("x")).isEqualTo("crackers"); } - @Test - public void testQueryWithInheritance() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithInheritance(RUN_TYPE runType) { // DROOLS-6105 final String str = "" + "global java.util.List list;\n" + @@ -1124,7 +1153,7 @@ public void testQueryWithInheritance() { " list.addAll( $food ); \n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/RuleAttributesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/RuleAttributesTest.java index 02c73e43f83..a553aafed21 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/RuleAttributesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/RuleAttributesTest.java @@ -27,7 +27,9 @@ import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.event.rule.AfterMatchFiredEvent; import org.kie.api.event.rule.DefaultAgendaEventListener; import org.kie.api.runtime.KieSession; @@ -37,12 +39,10 @@ public class RuleAttributesTest extends BaseModelTest { - public RuleAttributesTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test(timeout = 5000) - public void testNoLoop() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(5000) + public void testNoLoop(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R no-loop when\n" + @@ -51,7 +51,7 @@ public void testNoLoop() { " modify($p) { setAge($p.getAge()+1) };\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); ksession.insert( me ); @@ -60,8 +60,9 @@ public void testNoLoop() { assertThat(me.getAge()).isEqualTo(41); } - @Test - public void testSalience() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testSalience(RUN_TYPE runType) throws Exception { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -79,7 +80,7 @@ public void testSalience() throws Exception { " delete($p);" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.fireAllRules(); @@ -89,8 +90,9 @@ public void testSalience() throws Exception { assertThat(results.contains("R2")).isTrue(); } - @Test - public void testSalienceExpressionAttribute() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testSalienceExpressionAttribute(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "\n" + "rule R1 salience -$p.getAge() when\n" + @@ -106,7 +108,7 @@ public void testSalienceExpressionAttribute() throws Exception { " delete($p);" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.fireAllRules(); @@ -116,8 +118,9 @@ public void testSalienceExpressionAttribute() throws Exception { assertThat(results.contains("R2")).isTrue(); } - @Test - public void testExpressionEnabledAttribute() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExpressionEnabledAttribute(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R1\n" + "enabled ($b)\n" + @@ -129,7 +132,7 @@ public void testExpressionEnabledAttribute() throws Exception { " delete($p);" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(Boolean.FALSE); Person mario = new Person("Mario", 40); @@ -142,8 +145,9 @@ public void testExpressionEnabledAttribute() throws Exception { assertThat(!results.contains("R1")).isTrue(); } - @Test - public void testCrossNoLoopWithNodeSharing() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCrossNoLoopWithNodeSharing(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler.loop " + "rule 'Rule 1' " + @@ -168,7 +172,7 @@ public void testCrossNoLoopWithNodeSharing() throws Exception { " update( $thing2 ); " + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "hello" ); ksession.insert( new Integer( 42 ) ); @@ -181,8 +185,9 @@ public void testCrossNoLoopWithNodeSharing() throws Exception { assertThat(x).isEqualTo(2); } - @Test - public void testCalendars() { + @ParameterizedTest + @MethodSource("parameters") + public void testCalendars(RUN_TYPE runType) { String str = "package org.drools.compiler.integrationtests;\n" + "\n" + @@ -204,7 +209,7 @@ public void testCalendars() { " list.add(\"weekday\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ArrayList list = new ArrayList(); @@ -243,8 +248,9 @@ public boolean isTimeIncluded(long timestamp) { } }; - @Test - public void testAutoFocus() { + @ParameterizedTest + @MethodSource("parameters") + public void testAutoFocus(RUN_TYPE runType) { String str = "package org.drools.testcoverage.functional;\n" + "//generated from Decision Table\n" + @@ -335,7 +341,7 @@ public void testAutoFocus() { "end\n" + "\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final OrderListener listener = new OrderListener(); ksession.addEventListener(listener); @@ -378,8 +384,9 @@ public String get(final int index) { } } - @Test - public void testMetadataBasics() { + @ParameterizedTest + @MethodSource("parameters") + public void testMetadataBasics(RUN_TYPE runType) { final String PACKAGE_NAME = "org.asd"; final String RULE_NAME = "hello world"; final String RULE_KEY = "output"; @@ -392,7 +399,7 @@ public void testMetadataBasics() { " System.out.println(\"Hello world!\");\n" + " end"; - KieSession ksession = getKieSession(rule); + KieSession ksession = getKieSession(runType, rule); final Map metadata = ksession.getKieBase().getRule(PACKAGE_NAME, RULE_NAME).getMetaData(); @@ -400,8 +407,9 @@ public void testMetadataBasics() { assertThat(metadata.get(RULE_KEY)).isEqualTo("\"" + RULE_VALUE + "\""); } - @Test - public void testMetadataValue() { + @ParameterizedTest + @MethodSource("parameters") + public void testMetadataValue(RUN_TYPE runType) { final String rule = " package org.test;\n" + " rule R1\n" + " @metaValueString(\"asd\")\n" + @@ -413,7 +421,7 @@ public void testMetadataValue() { " System.out.println(\"Hello world!\");\n" + " end"; - KieSession ksession = getKieSession(rule); + KieSession ksession = getKieSession(runType, rule); final Map metadata = ksession.getKieBase().getRule("org.test", "R1").getMetaData(); @@ -423,8 +431,9 @@ public void testMetadataValue() { assertThat(metadata.get("metaValueCheck3")).isSameAs(System.out); } - @Test - public void testDynamicSalience() { + @ParameterizedTest + @MethodSource("parameters") + public void testDynamicSalience(RUN_TYPE runType) { String str = "global java.util.List list;\n" + "rule R1 salience $s.length when\n" + @@ -438,7 +447,7 @@ public void testDynamicSalience() { " list.add($i);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -454,8 +463,9 @@ public void testDynamicSalience() { public static final int CONST_SALIENCE = 1; - @Test - public void testSalienceFromConstant() { + @ParameterizedTest + @MethodSource("parameters") + public void testSalienceFromConstant(RUN_TYPE runType) { // DROOLS-5550 String str = "import " + RuleAttributesTest.class.getCanonicalName() + "\n;" + @@ -471,7 +481,7 @@ public void testSalienceFromConstant() { " list.add($i);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/SegmentPrototypeExpressionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/SegmentPrototypeExpressionTest.java index 383a1a044f0..66ee1911396 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/SegmentPrototypeExpressionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/SegmentPrototypeExpressionTest.java @@ -19,7 +19,7 @@ package org.drools.model.codegen.execmodel; import org.drools.model.prototype.PrototypeExpression; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.prototype.PrototypeFact; import org.kie.api.prototype.PrototypeFactInstance; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TextBlockTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TextBlockTest.java index b0c237961d5..d3517a1124b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TextBlockTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TextBlockTest.java @@ -22,19 +22,17 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +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; public class TextBlockTest extends OnlyExecModelTest { - public TextBlockTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testMultiLineStrings() { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void testMultiLineStrings(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "global java.util.List list;\n" + @@ -53,7 +51,7 @@ public void testMultiLineStrings() { "end\n"; - KieSession ksession = getKieSession(str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ToStringTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ToStringTest.java index db49afe2372..1400bf32346 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ToStringTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ToStringTest.java @@ -31,7 +31,7 @@ import org.drools.model.functions.Predicate1; import org.drools.model.functions.Predicate2; import org.drools.model.view.ExprViewItem; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.runtime.rule.AccumulateFunction; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java index 67cd73f3bd3..b83c11cc216 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java @@ -28,19 +28,17 @@ import org.drools.model.codegen.execmodel.domain.DateTimeHolder; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +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; public class TypeCoercionTest extends BaseModelTest { - public TypeCoercionTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testEqualCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testEqualCoercion(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -50,7 +48,7 @@ public void testEqualCoercion() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -63,8 +61,9 @@ public void testEqualCoercion() { assertThat(list.get(0)).isEqualTo("40"); } - @Test - public void testComparisonCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testComparisonCoercion(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -74,7 +73,7 @@ public void testComparisonCoercion() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -87,8 +86,9 @@ public void testComparisonCoercion() { assertThat(list.get(0)).isEqualTo("40"); } - @Test - public void testComparisonCoercion2() { + @ParameterizedTest + @MethodSource("parameters") + public void testComparisonCoercion2(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -98,7 +98,7 @@ public void testComparisonCoercion2() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -111,8 +111,9 @@ public void testComparisonCoercion2() { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testPrimitiveCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testPrimitiveCoercion(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -122,7 +123,7 @@ public void testPrimitiveCoercion() { " list.add(\"\" + $n);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -147,8 +148,9 @@ public Long getValue() { } } - @Test - public void testDoubleToInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoubleToInt(RUN_TYPE runType) { final String drl1 = "import " + DoubleHolder.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -156,14 +158,15 @@ public void testDoubleToInt() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert(new DoubleHolder()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testLongToInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testLongToInt(RUN_TYPE runType) { final String drl1 = "import " + LongHolder.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -171,14 +174,15 @@ public void testLongToInt() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert(new LongHolder()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinLongToDouble() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinLongToDouble(RUN_TYPE runType) { final String drl1 = "import " + DoubleHolder.class.getCanonicalName() + ";\n" + "import " + LongHolder.class.getCanonicalName() + ";\n" + @@ -188,15 +192,16 @@ public void testJoinLongToDouble() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert(new LongHolder()); ksession.insert(new DoubleHolder()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinDoubleToLong() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinDoubleToLong(RUN_TYPE runType) { final String drl1 = "import " + DoubleHolder.class.getCanonicalName() + ";\n" + "import " + LongHolder.class.getCanonicalName() + ";\n" + @@ -206,15 +211,16 @@ public void testJoinDoubleToLong() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert(new LongHolder()); ksession.insert(new DoubleHolder()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStringToDateComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringToDateComparison(RUN_TYPE runType) { String str = "import " + Date.class.getCanonicalName() + ";\n" + "declare Flight departuretime : java.util.Date end\n" + @@ -224,13 +230,14 @@ public void testStringToDateComparison() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testBetaJoinShortInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaJoinShortInt(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -239,12 +246,13 @@ public void testBetaJoinShortInt() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBetaJoinShortIntBoxed() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaJoinShortIntBoxed(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -253,12 +261,13 @@ public void testBetaJoinShortIntBoxed() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testPrimitivePromotionInLHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testPrimitivePromotionInLHS(RUN_TYPE runType) { // DROOLS-4717 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -269,7 +278,7 @@ public void testPrimitivePromotionInLHS() { " insert(new Result($p));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final Person luca = new Person("Luca", 35); ksession.insert(luca); @@ -281,8 +290,9 @@ public void testPrimitivePromotionInLHS() { assertThat(results.stream().map(Result::getValue)).containsExactlyInAnyOrder(luca); } - @Test - public void testIntToObjectCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testIntToObjectCoercion(RUN_TYPE runType) { // DROOLS-5320 String str = "rule R when\n" + @@ -291,14 +301,15 @@ public void testIntToObjectCoercion() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( 3 ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testDoubleNaN() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoubleNaN(RUN_TYPE runType) { // DROOLS-5692 String str = "import " + DoubleNaNPojo.class.getCanonicalName() + ";\n" + @@ -312,7 +323,7 @@ public void testDoubleNaN() { " update($nanTest);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); DoubleNaNPojo nan = new DoubleNaNPojo(); nan.setTestBoolean(false); @@ -386,8 +397,9 @@ public Short getTestShort() { } } - @Test - public void testStringToIntCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringToIntCoercion(RUN_TYPE runType) { // DROOLS-5939 String str = "import " + ClassWithIntProperty.class.getCanonicalName() + ";\n" + @@ -399,7 +411,7 @@ public void testStringToIntCoercion() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ClassWithIntProperty( 10 ) ); ksession.insert( new ClassWithStringProperty( "10" ) ); @@ -407,8 +419,9 @@ public void testStringToIntCoercion() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testIntToStringCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testIntToStringCoercion(RUN_TYPE runType) { // DROOLS-5939 String str = "import " + ClassWithIntProperty.class.getCanonicalName() + ";\n" + @@ -420,7 +433,7 @@ public void testIntToStringCoercion() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ClassWithIntProperty( 10 ) ); ksession.insert( new ClassWithStringProperty( "10" ) ); @@ -428,8 +441,9 @@ public void testIntToStringCoercion() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testShortToIntCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testShortToIntCoercion(RUN_TYPE runType) { // DROOLS-5939 String str = "import " + ClassWithShortProperty.class.getCanonicalName() + ";\n" + @@ -441,7 +455,7 @@ public void testShortToIntCoercion() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ClassWithShortProperty( (short)10 ) ); ksession.insert( new ClassWithIntProperty( 10 ) ); @@ -449,8 +463,9 @@ public void testShortToIntCoercion() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testIntToShortCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testIntToShortCoercion(RUN_TYPE runType) { // DROOLS-5939 String str = "import " + ClassWithShortProperty.class.getCanonicalName() + ";\n" + @@ -462,7 +477,7 @@ public void testIntToShortCoercion() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ClassWithShortProperty( (short)10 ) ); ksession.insert( new ClassWithIntProperty( 10 ) ); @@ -470,8 +485,9 @@ public void testIntToShortCoercion() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCoercionOnBoundVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testCoercionOnBoundVariable(RUN_TYPE runType) { // DROOLS-5945 String str = "import " + ClassWithIntProperty.class.getCanonicalName() + ";\n" + @@ -481,15 +497,16 @@ public void testCoercionOnBoundVariable() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ClassWithIntProperty( 3 ) ); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testCompareDateLiteral() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareDateLiteral(RUN_TYPE runType) throws Exception { String str = "import " + DateTimeHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -497,15 +514,16 @@ public void testCompareDateLiteral() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new DateTimeHolder(ZonedDateTime.now())); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCompareLocalDateLiteral() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareLocalDateLiteral(RUN_TYPE runType) throws Exception { String str = "import " + DateTimeHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -513,15 +531,16 @@ public void testCompareLocalDateLiteral() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new DateTimeHolder(ZonedDateTime.now())); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCompareLocalDateTimeLiteral() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareLocalDateTimeLiteral(RUN_TYPE runType) throws Exception { String str = "import " + DateTimeHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -529,15 +548,16 @@ public void testCompareLocalDateTimeLiteral() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new DateTimeHolder(ZonedDateTime.now())); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCompareLocalDateTimeLiteral2() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareLocalDateTimeLiteral2(RUN_TYPE runType) throws Exception { String str = "import " + DateTimeHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -545,21 +565,22 @@ public void testCompareLocalDateTimeLiteral2() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new DateTimeHolder(ZonedDateTime.now())); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testPrimitiveDoubleToIntCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testPrimitiveDoubleToIntCoercion(RUN_TYPE runType) { // DROOLS-6491 - checkDoubleToIntCoercion(true); - checkDoubleToIntCoercion(false); + checkDoubleToIntCoercion(runType, true); + checkDoubleToIntCoercion(runType, false); } - private void checkDoubleToIntCoercion(boolean boxed) { + private void checkDoubleToIntCoercion(RUN_TYPE runType, boolean boxed) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -569,7 +590,7 @@ private void checkDoubleToIntCoercion(boolean boxed) { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -582,8 +603,9 @@ private void checkDoubleToIntCoercion(boolean boxed) { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testFloatOperation() { + @ParameterizedTest + @MethodSource("parameters") + public void testFloatOperation(RUN_TYPE runType) { // DROOLS-7334 String str = "import " + Person.class.getCanonicalName() + "\n" + @@ -594,7 +616,7 @@ public void testFloatOperation() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -613,8 +635,9 @@ public void testFloatOperation() { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testCoerceObjectToString() { + @ParameterizedTest + @MethodSource("parameters") + public void testCoerceObjectToString(RUN_TYPE runType) { String str = "package constraintexpression\n" + "\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -627,7 +650,7 @@ public void testCoerceObjectToString() { " System.out.println($p); \n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); try { Person person = new Person("someName"); ksession.insert(person); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeDeclarationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeDeclarationTest.java index e34aeb6ffed..a985ac0c156 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeDeclarationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeDeclarationTest.java @@ -18,14 +18,14 @@ */ package org.drools.model.codegen.execmodel; -import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; @@ -34,12 +34,9 @@ public class TypeDeclarationTest extends BaseModelTest { - public TypeDeclarationTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testRecursiveDeclaration() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testRecursiveDeclaration(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler\n" + "declare Node\n" + @@ -53,7 +50,7 @@ public void testRecursiveDeclaration() throws Exception { " System.out.println( $value );\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); FactType nodeType = kbase.getFactType( "org.drools.compiler", "Node" ); @@ -70,8 +67,9 @@ public void testRecursiveDeclaration() throws Exception { assertThat(rules).isEqualTo(1); } - @Test - public void testGenerics() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testGenerics(RUN_TYPE runType) throws Exception { // DROOLS-4939 String str = "package org.drools.compiler\n" + @@ -85,7 +83,7 @@ public void testGenerics() throws Exception { " System.out.println( $node );\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); FactType nodeType = kbase.getFactType( "org.drools.compiler", "Node" ); @@ -101,8 +99,9 @@ public interface ValuesProvider { Map getValues(); } - @Test - public void testGenericsMap() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testGenericsMap(RUN_TYPE runType) throws Exception { // DROOLS-4939 String str = "package org.drools.compiler\n" + @@ -117,7 +116,7 @@ public void testGenericsMap() throws Exception { " System.out.println( $node );\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); FactType nodeType = kbase.getFactType( "org.drools.compiler", "Node" ); @@ -131,8 +130,9 @@ public void testGenericsMap() throws Exception { assertThat(rules).isEqualTo(1); } - @Test - public void testSerialVersionUID() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testSerialVersionUID(RUN_TYPE runType) throws Exception { // DROOLS-5340 String str = "package org.drools.compiler\n" + @@ -150,13 +150,14 @@ public void testSerialVersionUID() throws Exception { " insert( new ServiceInformation(\"123456\", \"ServiceTest\", new ArrayList()) );\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); int rules = ksession.fireAllRules(); assertThat(rules).isEqualTo(1); } - @Test - public void testSerialVersionUIDWithAllkeys() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testSerialVersionUIDWithAllkeys(RUN_TYPE runType) throws Exception { // DROOLS-5400 String str = "package org.drools.compiler\n" + @@ -174,13 +175,14 @@ public void testSerialVersionUIDWithAllkeys() throws Exception { " insert( new ServiceInformation(\"123456\", \"ServiceTest\", new ArrayList()) );\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); int rules = ksession.fireAllRules(); assertThat(rules).isEqualTo(1); } - @Test - public void testPositionalWithLiteral() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalWithLiteral(RUN_TYPE runType) { // DROOLS-6128 String str = "import " + Result.class.getCanonicalName() + ";" + @@ -200,7 +202,7 @@ public void testPositionalWithLiteral() { " insert(new Result($age));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -209,8 +211,9 @@ public void testPositionalWithLiteral() { assertThat(results.iterator().next().getValue()).isEqualTo(37); } - @Test - public void testPositionalWithJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalWithJoin(RUN_TYPE runType) { // DROOLS-6128 String str = "import " + Result.class.getCanonicalName() + ";" + @@ -231,7 +234,7 @@ public void testPositionalWithJoin() { " insert(new Result($age));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mark" ); ksession.fireAllRules(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeObjectCoercionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeObjectCoercionTest.java index fdf022aa260..a70c563e22b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeObjectCoercionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeObjectCoercionTest.java @@ -23,7 +23,8 @@ import java.util.List; import java.util.Map; -import org.junit.Test; +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; @@ -31,11 +32,7 @@ public class TypeObjectCoercionTest extends BaseModelTest { - public TypeObjectCoercionTest(RUN_TYPE testRunType) { - super(testRunType); - } - - private KieSession getKieSessionForJoinObjectToString() { + private KieSession getKieSessionForJoinObjectToString(RUN_TYPE runType) { // NOTE: If we write a test with IntegerHolder instead of ObjectHolder, standard-drl fails with a compilation error // text=Unable to Analyse Expression value >= $i: @@ -51,13 +48,14 @@ private KieSession getKieSessionForJoinObjectToString() { "then\n" + "end\n"; - return getKieSession(drl1); + return getKieSession(runType, drl1); } - @Test - public void testJoinObjectToString1() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToString1(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "10" > Integer 5 ksession.insert(new ObjectHolder(Integer.valueOf(5))); @@ -65,10 +63,11 @@ public void testJoinObjectToString1() { assertThat(ksession.fireAllRules()).isEqualTo(1); // standard-drl : 10 > 5 (Number comparison) } - @Test - public void testJoinObjectToString2() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToString2(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "10" > String "5" ksession.insert(new ObjectHolder("5")); @@ -76,10 +75,11 @@ public void testJoinObjectToString2() { assertThat(ksession.fireAllRules()).isEqualTo(0); // standard-drl : "10" < "5" (String comparison) } - @Test - public void testJoinObjectToString3() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToString3(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "ABC" > Integer 5 ksession.insert(new ObjectHolder(Integer.valueOf(5))); @@ -88,10 +88,11 @@ public void testJoinObjectToString3() { assertThatThrownBy(()->ksession.fireAllRules()).isInstanceOf(RuntimeException.class); // standard-drl : ClassCastException: java.lang.Integer cannot be cast to java.lang.String } - @Test - public void testJoinObjectToString4() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToString4(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "10" > String "ABC" ksession.insert(new ObjectHolder("ABC")); @@ -100,10 +101,11 @@ public void testJoinObjectToString4() { ksession.dispose(); } - @Test - public void testJoinObjectToString5() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToString5(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "ABC" > String "DEF" ksession.insert(new ObjectHolder("DEF")); @@ -112,10 +114,11 @@ public void testJoinObjectToString5() { ksession.dispose(); } - @Test - public void testJoinObjectToStringNonComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToStringNonComparable(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "10" > Object ksession.insert(new ObjectHolder(new Object())); // not Comparable @@ -126,7 +129,7 @@ public void testJoinObjectToStringNonComparable() { } - private KieSession getKieSessionForJoinStringToObject() { + private KieSession getKieSessionForJoinStringToObject(RUN_TYPE runType) { final String drl1 = "import " + ObjectHolder.class.getCanonicalName() + ";\n" + @@ -137,13 +140,14 @@ private KieSession getKieSessionForJoinStringToObject() { "then\n" + "end\n"; - return getKieSession(drl1); + return getKieSession(runType, drl1); } - @Test - public void testJoinStringToObject1() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinStringToObject1(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinStringToObject(); + KieSession ksession = getKieSessionForJoinStringToObject(runType); // Integer 5 > String "10" ksession.insert(new StringHolder("10")); @@ -151,10 +155,11 @@ public void testJoinStringToObject1() { assertThat(ksession.fireAllRules()).isEqualTo(0); // standard-drl : 5 < 10 (Number comparison) } - @Test - public void testJoinStringToObject2() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinStringToObject2(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinStringToObject(); + KieSession ksession = getKieSessionForJoinStringToObject(runType); // String "5" > String "10" ksession.insert(new StringHolder("10")); @@ -162,10 +167,11 @@ public void testJoinStringToObject2() { assertThat(ksession.fireAllRules()).isEqualTo(1); // standard-drl : "5" > "10" (String comparison) } - @Test - public void testJoinStringToObject3() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinStringToObject3(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinStringToObject(); + KieSession ksession = getKieSessionForJoinStringToObject(runType); // Integer 5 > String "ABC" ksession.insert(new StringHolder("ABC")); @@ -176,10 +182,11 @@ public void testJoinStringToObject3() { } - @Test - public void testJoinStringToObject4() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinStringToObject4(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinStringToObject(); + KieSession ksession = getKieSessionForJoinStringToObject(runType); // String "ABC" > String "10" ksession.insert(new StringHolder("10")); @@ -188,10 +195,11 @@ public void testJoinStringToObject4() { ksession.dispose(); } - @Test - public void testJoinStringToObject5() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinStringToObject5(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinStringToObject(); + KieSession ksession = getKieSessionForJoinStringToObject(runType); // String "DEF" > String "ABC" ksession.insert(new StringHolder("ABC")); @@ -200,7 +208,7 @@ public void testJoinStringToObject5() { ksession.dispose(); } - private KieSession getKieSessionForJoinIntegerToObject() { + private KieSession getKieSessionForJoinIntegerToObject(RUN_TYPE runType) { final String drl1 = "import " + ObjectHolder.class.getCanonicalName() + ";\n" + @@ -211,13 +219,14 @@ private KieSession getKieSessionForJoinIntegerToObject() { "then\n" + "end\n"; - return getKieSession(drl1); + return getKieSession(runType, drl1); } - @Test - public void testJoinIntegerToObject1() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinIntegerToObject1(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinIntegerToObject(); + KieSession ksession = getKieSessionForJoinIntegerToObject(runType); // Integer 10 > Integer 5 ksession.insert(new IntegerHolder(Integer.valueOf(5))); @@ -225,10 +234,11 @@ public void testJoinIntegerToObject1() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinIntegerToObject2() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinIntegerToObject2(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinIntegerToObject(); + KieSession ksession = getKieSessionForJoinIntegerToObject(runType); // String "10" > Integer 5 ksession.insert(new IntegerHolder(Integer.valueOf(5))); @@ -236,10 +246,11 @@ public void testJoinIntegerToObject2() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinIntegerToObject3() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinIntegerToObject3(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinIntegerToObject(); + KieSession ksession = getKieSessionForJoinIntegerToObject(runType); // String "ABC" > Integer 5 ksession.insert(new IntegerHolder(Integer.valueOf(5))); @@ -248,10 +259,11 @@ public void testJoinIntegerToObject3() { assertThatThrownBy(()->ksession.fireAllRules()).isInstanceOf(RuntimeException.class); // standard-drl : Caused by ClassCastException: java.lang.String cannot be cast to java.lang.Integer } - @Test - public void testJoinIntegerToObjectNonComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinIntegerToObjectNonComparable(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinIntegerToObject(); + KieSession ksession = getKieSessionForJoinIntegerToObject(runType); // Object > Integer 5 ksession.insert(new IntegerHolder(Integer.valueOf(5))); @@ -259,7 +271,7 @@ public void testJoinIntegerToObjectNonComparable() { assertThat(ksession.fireAllRules()).isEqualTo(0); // in case of standard-drl, MathProcessor.doOperationNonNumeric() returns false when the left operand is not Comparable } - private KieSession getKieSessionForJoinObjectToInteger() { + private KieSession getKieSessionForJoinObjectToInteger(RUN_TYPE runType) { final String drl1 = "import " + ObjectHolder.class.getCanonicalName() + ";\n" + @@ -270,13 +282,14 @@ private KieSession getKieSessionForJoinObjectToInteger() { "then\n" + "end\n"; - return getKieSession(drl1); + return getKieSession(runType, drl1); } - @Test - public void testJoinObjectToInteger1() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToInteger1(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToInteger(); + KieSession ksession = getKieSessionForJoinObjectToInteger(runType); // Integer 10 > Integer 5 ksession.insert(new ObjectHolder(Integer.valueOf(5))); @@ -284,10 +297,11 @@ public void testJoinObjectToInteger1() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinObjectToInteger2() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToInteger2(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToInteger(); + KieSession ksession = getKieSessionForJoinObjectToInteger(runType); // Integer 10 > String "5" ksession.insert(new ObjectHolder(new String("5"))); @@ -295,10 +309,11 @@ public void testJoinObjectToInteger2() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinObjectToInteger3() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToInteger3(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToInteger(); + KieSession ksession = getKieSessionForJoinObjectToInteger(runType); // Integer 10 > String "ABC" ksession.insert(new ObjectHolder(new String("ABC"))); @@ -307,10 +322,11 @@ public void testJoinObjectToInteger3() { assertThatThrownBy(()->ksession.fireAllRules()).isInstanceOf(RuntimeException.class); // standard-drl : Caused by ClassCastException: java.lang.String cannot be cast to java.lang.Integer } - @Test - public void testJoinObjectToIntegerNonComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToIntegerNonComparable(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToInteger(); + KieSession ksession = getKieSessionForJoinObjectToInteger(runType); // Integer 10 > Object ksession.insert(new ObjectHolder(new Object())); // not Comparable @@ -359,8 +375,9 @@ public Integer getValue() { } } - @Test - public void testJoinObjectToStringWithMap() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToStringWithMap(RUN_TYPE runType) { // This rule mimics JittingTest#testJitMapCoercion() @@ -373,7 +390,7 @@ public void testJoinObjectToStringWithMap() { "then\n" + "end\n"; - KieSession ksession = getKieSession(drl1); + KieSession ksession = getKieSession(runType, drl1); Map map = new HashMap<>(); map.put("key", 5); @@ -382,8 +399,9 @@ public void testJoinObjectToStringWithMap() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCoercionStringVsObjectIntegerWithMap() { + @ParameterizedTest + @MethodSource("parameters") + public void testCoercionStringVsObjectIntegerWithMap(RUN_TYPE runType) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Map.class.getCanonicalName() + ";\n" + "import " + StringHolder.class.getCanonicalName() + ";\n" + @@ -398,7 +416,7 @@ public void testCoercionStringVsObjectIntegerWithMap() { // String is coerced to Integer (thus, Number comparison) - KieSession ksession = getKieSession(drl); + KieSession ksession =getKieSession(runType, drl); try { final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -424,8 +442,9 @@ public void testCoercionStringVsObjectIntegerWithMap() { } } - @Test - public void testCoercionStringVsExplicitIntegerWithMap() { + @ParameterizedTest + @MethodSource("parameters") + public void testCoercionStringVsExplicitIntegerWithMap(RUN_TYPE runType) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Map.class.getCanonicalName() + ";\n" + "import " + StringHolder.class.getCanonicalName() + ";\n" + @@ -440,7 +459,7 @@ public void testCoercionStringVsExplicitIntegerWithMap() { // String is coerced to Integer (thus, Number comparison) - KieSession ksession = getKieSession(drl); + KieSession ksession =getKieSession(runType, drl); try { final List list = new ArrayList<>(); ksession.setGlobal("list", list); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/UseClassFieldsInRulesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/UseClassFieldsInRulesTest.java index beec7efc349..3e1a920ea99 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/UseClassFieldsInRulesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/UseClassFieldsInRulesTest.java @@ -18,16 +18,14 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.Test; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -public class UseClassFieldsInRulesTest extends BaseModelTest { +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - public UseClassFieldsInRulesTest( BaseModelTest.RUN_TYPE testRunType ) { - super( testRunType ); - } +public class UseClassFieldsInRulesTest extends BaseModelTest { public static class ClassWithFields { public final int field = 3; @@ -38,54 +36,63 @@ public int getValue() { } } - @Test - public void testUseAccessor() { - doCheck(true, "value > 2"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccessor(RUN_TYPE runType) { + doCheck(runType, true, "value > 2"); } - @Test - public void testUseField() { - doCheck(true, "field > 2"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseField(RUN_TYPE runType) { + doCheck(runType, true, "field > 2"); } - @Test - public void testUseStaticField() { - doCheck(true, "STATIC_FIELD > 2"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseStaticField(RUN_TYPE runType) { + doCheck(runType, true, "STATIC_FIELD > 2"); } - @Test - public void testUseAccessorInFunction() { - doCheck(true, "greaterThan( value, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccessorInFunction(RUN_TYPE runType) { + doCheck(runType, true, "greaterThan( value, 2 )"); } - @Test - public void testUseFieldInFunction() { - doCheck(true, "greaterThan( field, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseFieldInFunction(RUN_TYPE runType) { + doCheck(runType, true, "greaterThan( field, 2 )"); } - @Test - public void testUseStaticFieldInFunction() { - doCheck(true, "greaterThan( STATIC_FIELD, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseStaticFieldInFunction(RUN_TYPE runType) { + doCheck(runType, true, "greaterThan( STATIC_FIELD, 2 )"); } public static boolean greaterThanMethod(int i1, int i2) { return i1 > i2; } - @Test - public void testUseAccessorInMethod() { - doCheck(false, "greaterThanMethod( value, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccessorInMethod(RUN_TYPE runType) { + doCheck(runType, false, "greaterThanMethod( value, 2 )"); } - @Test - public void testUseFieldInMethod() { - doCheck(false, "greaterThanMethod( field, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseFieldInMethod(RUN_TYPE runType) { + doCheck(runType, false, "greaterThanMethod( field, 2 )"); } - @Test - public void testUseStaticFieldInMethod() { - doCheck(false, "greaterThanMethod( STATIC_FIELD, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseStaticFieldInMethod(RUN_TYPE runType) { + doCheck(runType, false, "greaterThanMethod( STATIC_FIELD, 2 )"); } - private void doCheck(boolean useFunction, String pattern) { + private void doCheck(RUN_TYPE runType, boolean useFunction, String pattern) { String str = "import " + ClassWithFields.class.getCanonicalName() + "\n" + (useFunction ? @@ -96,14 +103,15 @@ private void doCheck(boolean useFunction, String pattern) { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new ClassWithFields()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMethodInFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testMethodInFrom(RUN_TYPE runType) { String str = "import " + ClassWithFields.class.getCanonicalName() + "\n" + "import static " + UseClassFieldsInRulesTest.class.getCanonicalName() + ".*\n" + @@ -112,12 +120,13 @@ public void testMethodInFrom() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMethodInEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testMethodInEval(RUN_TYPE runType) { String str = "import " + ClassWithFields.class.getCanonicalName() + "\n" + "import static " + UseClassFieldsInRulesTest.class.getCanonicalName() + ".*\n" + @@ -126,12 +135,13 @@ public void testMethodInEval() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testFunctionInFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunctionInFrom(RUN_TYPE runType) { String str = "import " + ClassWithFields.class.getCanonicalName() + "\n" + "function boolean greaterThan(int i1, int i2) { return i1 > i2; }\n" + @@ -140,12 +150,13 @@ public void testFunctionInFrom() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testFunctionWithEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunctionWithEval(RUN_TYPE runType) { String str = "import " + ClassWithFields.class.getCanonicalName() + "\n" + "function boolean greaterThan(int i1, int i2) { return i1 > i2; }\n" + @@ -154,7 +165,7 @@ public void testFunctionWithEval() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/alphaNetworkCompiler/ObjectTypeNodeCompilerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/alphaNetworkCompiler/ObjectTypeNodeCompilerTest.java index 682c060394c..8c4a9610d73 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/alphaNetworkCompiler/ObjectTypeNodeCompilerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/alphaNetworkCompiler/ObjectTypeNodeCompilerTest.java @@ -25,19 +25,17 @@ import org.drools.model.codegen.execmodel.domain.EnumFact1; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +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; public class ObjectTypeNodeCompilerTest extends BaseModelTest { - public ObjectTypeNodeCompilerTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testAlphaConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraint(RUN_TYPE runType) { String str = "rule \"Bind\"\n" + "when\n" + @@ -45,7 +43,7 @@ public void testAlphaConstraint() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Luca"); ksession.insert("Asdrubale"); @@ -53,8 +51,9 @@ public void testAlphaConstraint() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaConstraintsSwitchString() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintsSwitchString(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule \"Bind1\"\n" + @@ -73,7 +72,7 @@ public void testAlphaConstraintsSwitchString() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Luca")); ksession.insert(new Person("Asdrubale")); @@ -84,8 +83,9 @@ public void testAlphaConstraintsSwitchString() { /* This generates the switch but not the inlining */ - @Test - public void testAlphaConstraintsSwitchBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintsSwitchBigDecimal(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + BigDecimal.class.getCanonicalName() + ";" + @@ -105,7 +105,7 @@ public void testAlphaConstraintsSwitchBigDecimal() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Luca", new BigDecimal(0))); ksession.insert(new Person("Asdrubale", new BigDecimal(10))); @@ -113,8 +113,9 @@ public void testAlphaConstraintsSwitchBigDecimal() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaConstraintsSwitchPerson() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintsSwitchPerson(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule \"Bind1\"\n" + @@ -133,7 +134,7 @@ public void testAlphaConstraintsSwitchPerson() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Luca")); ksession.insert(new Person("Asdrubale")); @@ -141,8 +142,9 @@ public void testAlphaConstraintsSwitchPerson() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaConstraintsSwitchIntegers() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintsSwitchIntegers(RUN_TYPE runType) { String str = "rule \"Bind1\"\n" + "when\n" + @@ -160,7 +162,7 @@ public void testAlphaConstraintsSwitchIntegers() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Luca"); ksession.insert("Asdrubale"); @@ -168,8 +170,9 @@ public void testAlphaConstraintsSwitchIntegers() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testEnum(RUN_TYPE runType) { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + @@ -186,14 +189,15 @@ public void testEnum() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new ChildFactWithEnum1(1, 3, EnumFact1.FIRST)); ksession.insert(new ChildFactWithEnum1(1, 3, EnumFact1.SECOND)); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testAlphaConstraintWithModification() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintWithModification(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "rule \"Bind\"\n" + @@ -204,7 +208,7 @@ public void testAlphaConstraintWithModification() { " $r.setValue($s + \" is greater than 4 and smaller than 10\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Luca"); ksession.insert("Asdrubale"); @@ -218,8 +222,9 @@ public void testAlphaConstraintWithModification() { assertThat(result.getValue()).isEqualTo("Asdrubale is greater than 4 and smaller than 10"); } - @Test - public void testModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testModify(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule \"Modify\"\n" + @@ -229,7 +234,7 @@ public void testModify() { " modify($p) { setName($p.getName() + \"30\"); }" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final Person luca = new Person("Luca", 30); ksession.insert(luca); @@ -240,8 +245,9 @@ public void testModify() { assertThat(luca.getName()).isEqualTo("Luca30"); } - @Test - public void testModify2() { + @ParameterizedTest + @MethodSource("parameters") + public void testModify2(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule \"Modify\"\n" + @@ -251,7 +257,7 @@ public void testModify2() { " modify($p) { setAge($p.getAge() + 1); }" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final Person luca = new Person("Luca", 30); ksession.insert(luca); @@ -265,8 +271,9 @@ public void testModify2() { assertThat(luca.getAge() == 40).isTrue(); } - @Test - public void testAlphaConstraintNagate() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintNagate(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -274,7 +281,7 @@ public void testAlphaConstraintNagate() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); try { ksession.insert(new Person("Mario", 45)); assertThat(ksession.fireAllRules()).isEqualTo(0); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/assembler/AssemblerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/assembler/AssemblerTest.java index 244c35e90eb..5b29de0af4e 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/assembler/AssemblerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/assembler/AssemblerTest.java @@ -21,7 +21,7 @@ import java.util.List; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigdecimaltest/BigDecimalTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigdecimaltest/BigDecimalTest.java index 885b27cb026..038b4950442 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigdecimaltest/BigDecimalTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigdecimaltest/BigDecimalTest.java @@ -23,19 +23,17 @@ import java.util.List; import org.drools.model.codegen.execmodel.BaseModelTest; -import org.junit.Test; +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; public class BigDecimalTest extends BaseModelTest { - public BigDecimalTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testBigDecimalGreaterThan() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalGreaterThan(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -50,7 +48,7 @@ public void testBigDecimalGreaterThan() { "update($policy);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -67,8 +65,9 @@ public void testBigDecimalGreaterThan() { } - @Test - public void testBigDecimalCompare() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalCompare(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -83,7 +82,7 @@ public void testBigDecimalCompare() { "update($policy);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -100,8 +99,9 @@ public void testBigDecimalCompare() { } - @Test - public void testBigDecimalEqualsToNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalEqualsToNull(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -112,7 +112,7 @@ public void testBigDecimalEqualsToNull() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); @@ -120,8 +120,9 @@ public void testBigDecimalEqualsToNull() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalNotEqualsToNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalNotEqualsToNull(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -132,7 +133,7 @@ public void testBigDecimalNotEqualsToNull() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -142,8 +143,9 @@ public void testBigDecimalNotEqualsToNull() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalNotEqualsToLiteralNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalNotEqualsToLiteralNull(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -154,7 +156,7 @@ public void testBigDecimalNotEqualsToLiteralNull() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -164,8 +166,9 @@ public void testBigDecimalNotEqualsToLiteralNull() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalNotEqualsToLiteralValue() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalNotEqualsToLiteralValue(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -176,7 +179,7 @@ public void testBigDecimalNotEqualsToLiteralValue() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -186,8 +189,9 @@ public void testBigDecimalNotEqualsToLiteralValue() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalGreaterThanNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalGreaterThanNull(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -198,7 +202,7 @@ public void testBigDecimalGreaterThanNull() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -208,8 +212,9 @@ public void testBigDecimalGreaterThanNull() { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBigDecimalEquals() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalEquals(RUN_TYPE runType) { // DROOLS-3527 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -220,7 +225,7 @@ public void testBigDecimalEquals() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setRate(new BigDecimal("12.111")); @@ -231,8 +236,9 @@ public void testBigDecimalEquals() { } - @Test - public void testBigDecimalAdd() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalAdd(RUN_TYPE runType) { // RHDM-1635 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -243,7 +249,7 @@ public void testBigDecimalAdd() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer c1 = new Customer(); c1.setRate(new BigDecimal("10")); @@ -256,8 +262,9 @@ public void testBigDecimalAdd() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalRemainder() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalRemainder(RUN_TYPE runType) { // RHDM-1635 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -268,7 +275,7 @@ public void testBigDecimalRemainder() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer c1 = new Customer(); c1.setRate(new BigDecimal("20")); @@ -313,8 +320,9 @@ public String toString() { } } - @Test - public void testNonTerminatingDecimalExpansion() { + @ParameterizedTest + @MethodSource("parameters") + public void testNonTerminatingDecimalExpansion(RUN_TYPE runType) { // DROOLS-6804 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -325,7 +333,7 @@ public void testNonTerminatingDecimalExpansion() { " $o.setTax($price - ($price / ($taxRate + 1)));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Order order = new Order(); order.setPrice(new BigDecimal("100000000")); @@ -336,8 +344,9 @@ public void testNonTerminatingDecimalExpansion() { assertThat(order.getTax()).isEqualTo(new BigDecimal("9090909.09090909090909090909090909")); } - @Test - public void testBigDecimalAndStringComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalAndStringComparison(RUN_TYPE runType) { // DROOLS-6823 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -348,7 +357,7 @@ public void testBigDecimalAndStringComparison() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Order order = new Order(); order.setPrice(new BigDecimal(300)); @@ -358,8 +367,9 @@ public void testBigDecimalAndStringComparison() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStringAndBigDecimalComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringAndBigDecimalComparison(RUN_TYPE runType) { // DROOLS-6823 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -370,7 +380,7 @@ public void testStringAndBigDecimalComparison() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Order order = new Order(); order.setPrice(new BigDecimal(300)); @@ -412,62 +422,73 @@ public void setBd2(BigDecimal bd2) { } } - @Test - public void testMultiply() { - testBigDecimalArithmeticOperation("BdHolder(bd2 == bd1 * 10)", "10", "100"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiply(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder(bd2 == bd1 * 10)", "10", "100"); } - @Test - public void testMultiplyWithNegativeValue() { - testBigDecimalArithmeticOperation("BdHolder(bd2 == bd1 * -1)", "10", "-10"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithNegativeValue(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder(bd2 == bd1 * -1)", "10", "-10"); } - @Test - public void testMultiplyWithBindVariable() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 * 10)", "10", "100"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithBindVariable(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 * 10)", "10", "100"); } - @Test - public void testMultiplyWithBindVariableWithNegativeValue() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 * -1)", "10", "-10"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithBindVariableWithNegativeValue(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 * -1)", "10", "-10"); } - @Test - public void testMultiplyWithBindVariableWithNegativeValueEnclosed() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 * (-1))", "10", "-10"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithBindVariableWithNegativeValueEnclosed(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 * (-1))", "10", "-10"); } - @Test - public void testMultiplyWithBindVariableWithNegativeValueEnclosedBoth() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == ($bd1 * -1))", "10", "-10"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithBindVariableWithNegativeValueEnclosedBoth(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == ($bd1 * -1))", "10", "-10"); } - @Test - public void testMultiplyWithBindVariableWithNegativeValueEnclosedNest() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == ($bd1 * (-1)))", "10", "-10"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithBindVariableWithNegativeValueEnclosedNest(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == ($bd1 * (-1)))", "10", "-10"); } - @Test - public void testAddWithBindVariable() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 + 10)", "10", "20"); + @ParameterizedTest + @MethodSource("parameters") + public void testAddWithBindVariable(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 + 10)", "10", "20"); } - @Test - public void testSubtractWithBindVariable() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 - 10)", "10", "0"); + @ParameterizedTest + @MethodSource("parameters") + public void testSubtractWithBindVariable(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 - 10)", "10", "0"); } - @Test - public void testDivideWithBindVariable() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 / 10)", "10", "1"); + @ParameterizedTest + @MethodSource("parameters") + public void testDivideWithBindVariable(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 / 10)", "10", "1"); } - @Test - public void testModWithBindVariable() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 % 10)", "10", "0"); + @ParameterizedTest + @MethodSource("parameters") + public void testModWithBindVariable(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 % 10)", "10", "0"); } - private void testBigDecimalArithmeticOperation(String pattern, String bd1, String bd2) { + private void testBigDecimalArithmeticOperation(RUN_TYPE runType, String pattern, String bd1, String bd2) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + BdHolder.class.getCanonicalName() + ";\n" + @@ -476,7 +497,7 @@ private void testBigDecimalArithmeticOperation(String pattern, String bd1, Strin "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BdHolder holder = new BdHolder(new BigDecimal(bd1), new BigDecimal(bd2)); ksession.insert(holder); @@ -484,8 +505,9 @@ private void testBigDecimalArithmeticOperation(String pattern, String bd1, Strin assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalLiteralLhsNegative() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalLiteralLhsNegative(RUN_TYPE runType) { // DROOLS-6596 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -495,7 +517,7 @@ public void testBigDecimalLiteralLhsNegative() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BdHolder holder = new BdHolder(); holder.setBd1(new BigDecimal("10")); @@ -505,8 +527,9 @@ public void testBigDecimalLiteralLhsNegative() { assertThat(fired).isEqualTo(1); } - @Test - public void testBigDecimalLiteralRhsNegative() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalLiteralRhsNegative(RUN_TYPE runType) { // DROOLS-6596 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -517,7 +540,7 @@ public void testBigDecimalLiteralRhsNegative() { " $holder.bd1 = -10.5B;\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BdHolder holder = new BdHolder(); ksession.insert(holder); @@ -526,8 +549,9 @@ public void testBigDecimalLiteralRhsNegative() { assertThat(holder.getBd1()).isEqualTo(new BigDecimal("-10.5")); } - @Test - public void testBigDecimalLiteralWithBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalLiteralWithBinding(RUN_TYPE runType) { // DROOLS-6936 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -540,7 +564,7 @@ public void testBigDecimalLiteralWithBinding() { " result.add($zero);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -552,8 +576,9 @@ public void testBigDecimalLiteralWithBinding() { assertThat(result).containsExactly(new BigDecimal("0")); } - @Test - public void testModifyWithNegativeBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyWithNegativeBigDecimal(RUN_TYPE runType) { // DROOLS-7324 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -565,7 +590,7 @@ public void testModifyWithNegativeBigDecimal() { " modify($bd) { bd1 = -1 }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -577,8 +602,9 @@ public void testModifyWithNegativeBigDecimal() { assertThat(fires).isEqualTo(1); } - @Test - public void bigDecimalArithmeticInMethodCallScope() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalArithmeticInMethodCallScope(RUN_TYPE runType) { // DROOLS-7364 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -592,7 +618,7 @@ public void bigDecimalArithmeticInMethodCallScope() { " result.add($ans);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -604,8 +630,9 @@ public void bigDecimalArithmeticInMethodCallScope() { assertThat(result).contains(2000L); } - @Test - public void bigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalArithmeticInMethodCallScopeInMethodCallArgument(RUN_TYPE runType) { // DROOLS-7364 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -619,7 +646,7 @@ public void bigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { " result.add($ans);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -631,8 +658,9 @@ public void bigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { assertThat(result).contains("2,000"); } - @Test - public void nonBigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void nonBigDecimalArithmeticInMethodCallScopeInMethodCallArgument(RUN_TYPE runType) { // DROOLS-7364 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -646,7 +674,7 @@ public void nonBigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { " result.add($ans);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -658,8 +686,9 @@ public void nonBigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { assertThat(result).contains("2,000"); } - @Test - public void bigDecimalArithmeticInMethodCallArgumentWithoutEnclosedExpr() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalArithmeticInMethodCallArgumentWithoutEnclosedExpr(RUN_TYPE runType) { // DROOLS-7364 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -674,7 +703,7 @@ public void bigDecimalArithmeticInMethodCallArgumentWithoutEnclosedExpr() { " result.add($ans);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -693,8 +722,9 @@ public static String getString(String format, BigDecimal bd) { } } - @Test - public void bigDecimalEqualityWithDifferentScale_shouldBeEqual() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalEqualityWithDifferentScale_shouldBeEqual(RUN_TYPE runType) { // DROOLS-7414 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -708,7 +738,7 @@ public void bigDecimalEqualityWithDifferentScale_shouldBeEqual() { " result.add($rate);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -722,8 +752,9 @@ public void bigDecimalEqualityWithDifferentScale_shouldBeEqual() { assertThat(result).contains(new BigDecimal("1.00")); } - @Test - public void bigDecimalCoercionInMethodArgument_shouldNotFailToBuild() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalCoercionInMethodArgument_shouldNotFailToBuild(RUN_TYPE runType) { // KIE-748 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -735,7 +766,7 @@ public void bigDecimalCoercionInMethodArgument_shouldNotFailToBuild() { " then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BDFact bdFact = new BDFact(); bdFact.setValue2(new BigDecimal("3")); @@ -745,8 +776,9 @@ public void bigDecimalCoercionInMethodArgument_shouldNotFailToBuild() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void bigDecimalCoercionInNestedMethodArgument_shouldNotFailToBuild() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalCoercionInNestedMethodArgument_shouldNotFailToBuild(RUN_TYPE runType) { // KIE-748 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -758,7 +790,7 @@ public void bigDecimalCoercionInNestedMethodArgument_shouldNotFailToBuild() { " then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BDFact bdFact = new BDFact(); bdFact.setValue1(new BigDecimal("10")); @@ -773,22 +805,25 @@ public static String intToString(int value) { return Integer.toString(value); } - @Test - public void bindVariableToBigDecimalCoercion2Operands_shouldBindCorrectResult() { - bindVariableToBigDecimalCoercion("$var : (1000 * value1)"); + @ParameterizedTest + @MethodSource("parameters") + public void bindVariableToBigDecimalCoercion2Operands_shouldBindCorrectResult(RUN_TYPE runType) { + bindVariableToBigDecimalCoercion(runType, "$var : (1000 * value1)"); } - @Test - public void bindVariableToBigDecimalCoercion3Operands_shouldBindCorrectResult() { - bindVariableToBigDecimalCoercion("$var : (100000 * value1 / 100)"); + @ParameterizedTest + @MethodSource("parameters") + public void bindVariableToBigDecimalCoercion3Operands_shouldBindCorrectResult(RUN_TYPE runType) { + bindVariableToBigDecimalCoercion(runType, "$var : (100000 * value1 / 100)"); } - @Test - public void bindVariableToBigDecimalCoercion3OperandsWithParentheses_shouldBindCorrectResult() { - bindVariableToBigDecimalCoercion("$var : ((100000 * value1) / 100)"); + @ParameterizedTest + @MethodSource("parameters") + public void bindVariableToBigDecimalCoercion3OperandsWithParentheses_shouldBindCorrectResult(RUN_TYPE runType) { + bindVariableToBigDecimalCoercion(runType, "$var : ((100000 * value1) / 100)"); } - private void bindVariableToBigDecimalCoercion(String binding) { + private void bindVariableToBigDecimalCoercion(RUN_TYPE runType, String binding) { // KIE-775 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -801,7 +836,7 @@ private void bindVariableToBigDecimalCoercion(String binding) { " result.add($var);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -814,8 +849,9 @@ private void bindVariableToBigDecimalCoercion(String binding) { assertThat(result).contains(new BigDecimal("80000")); } - @Test - public void bigDecimalInWithInt_shouldNotFailToBuild() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalInWithInt_shouldNotFailToBuild(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + BDFact.class.getCanonicalName() + ";\n" + @@ -825,7 +861,7 @@ public void bigDecimalInWithInt_shouldNotFailToBuild() { " then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BDFact bdFact = new BDFact(); bdFact.setValue1(new BigDecimal("100")); @@ -835,8 +871,9 @@ public void bigDecimalInWithInt_shouldNotFailToBuild() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void bigDecimalInWithBD_shouldNotFailToBuild() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalInWithBD_shouldNotFailToBuild(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + BDFact.class.getCanonicalName() + ";\n" + @@ -846,7 +883,7 @@ public void bigDecimalInWithBD_shouldNotFailToBuild() { " then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BDFact bdFact = new BDFact(); bdFact.setValue1(new BigDecimal("100")); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigintegertest/BigIntegerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigintegertest/BigIntegerTest.java index abaf1ea4ab4..d1703048680 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigintegertest/BigIntegerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigintegertest/BigIntegerTest.java @@ -21,17 +21,14 @@ import java.math.BigInteger; import org.drools.model.codegen.execmodel.BaseModelTest; -import org.junit.Test; +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; public class BigIntegerTest extends BaseModelTest { - public BigIntegerTest(RUN_TYPE testRunType) { - super(testRunType); - } - public static class BiHolder { private BigInteger bi1; @@ -64,8 +61,9 @@ public void setBi2(BigInteger bi2) { } } - @Test - public void testBigIntegerLiteralLhsNegative() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigIntegerLiteralLhsNegative(RUN_TYPE runType) { // DROOLS-6596 String str = "package org.drools.modelcompiler.bigintegerss\n" + @@ -75,7 +73,7 @@ public void testBigIntegerLiteralLhsNegative() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BiHolder holder = new BiHolder(); holder.setBi1(new BigInteger("10")); @@ -85,8 +83,9 @@ public void testBigIntegerLiteralLhsNegative() { assertThat(fired).isEqualTo(1); } - @Test - public void testBigIntegerLiteralRhsNegative() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigIntegerLiteralRhsNegative(RUN_TYPE runType) { // DROOLS-6596 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -97,7 +96,7 @@ public void testBigIntegerLiteralRhsNegative() { " $holder.bi1 = -10I;\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BiHolder holder = new BiHolder(); ksession.insert(holder); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/constraints/ConstraintEvaluationExceptionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/constraints/ConstraintEvaluationExceptionTest.java index 896985761cd..07699c328ab 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/constraints/ConstraintEvaluationExceptionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/constraints/ConstraintEvaluationExceptionTest.java @@ -27,7 +27,8 @@ import org.drools.model.functions.PredicateInformation; import org.drools.modelcompiler.constraints.ConstraintEvaluationException; import org.drools.mvel.MVELConstraint; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.io.Resource; import java.util.Collections; @@ -40,58 +41,58 @@ public class ConstraintEvaluationExceptionTest extends BaseModelTest { private MVELConstraint mvelConstraint; // non-exec-model - public ConstraintEvaluationExceptionTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testMultipleRules() { - initConstraintTestField("age > 20", "R1", "sample.drl"); - addRuleToConstraintTestField("R2", "sample.drl"); - addRuleToConstraintTestField("R3", "sample.drl"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleRules(RUN_TYPE runType) { + initConstraintTestField(runType, "age > 20", "R1", "sample.drl"); + addRuleToConstraintTestField(runType, "R2", "sample.drl"); + addRuleToConstraintTestField(runType, "R3", "sample.drl"); - assertMessage("Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\", \"R3\" in sample.drl]"); + assertMessage(runType, "Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\", \"R3\" in sample.drl]"); } - @Test - public void testMultipleRuleFiles() { - initConstraintTestField("age > 20", "R1", "sample1.drl"); - addRuleToConstraintTestField("R2", "sample1.drl"); - addRuleToConstraintTestField("R3", "sample2.drl"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleRuleFiles(RUN_TYPE runType) { + initConstraintTestField(runType, "age > 20", "R1", "sample1.drl"); + addRuleToConstraintTestField(runType, "R2", "sample1.drl"); + addRuleToConstraintTestField(runType, "R3", "sample2.drl"); - assertMessage("Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\" in sample1.drl] [Rule \"R3\" in sample2.drl]"); + assertMessage(runType, "Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\" in sample1.drl] [Rule \"R3\" in sample2.drl]"); } - @Test - public void testNull() { - initConstraintTestField("age > 20", null, "sample1.drl"); - addRuleToConstraintTestField("R2", null); - addRuleToConstraintTestField(null, null); + @ParameterizedTest + @MethodSource("parameters") + public void testNull(RUN_TYPE runType) { + initConstraintTestField(runType, "age > 20", null, "sample1.drl"); + addRuleToConstraintTestField(runType, "R2", null); + addRuleToConstraintTestField(runType, null, null); // Irregular case. Not much useful info but doesn't throw NPE - assertMessage("Error evaluating constraint 'age > 20' in [Rule \"\", \"R2\" in ] [Rule \"\" in sample1.drl]"); + assertMessage(runType, "Error evaluating constraint 'age > 20' in [Rule \"\", \"R2\" in ] [Rule \"\" in sample1.drl]"); } - @Test - public void testExceedMaxRuleDefs() { - initConstraintTestField("age > 20", "R1", "sample1.drl"); - addRuleToConstraintTestField("R2", "sample1.drl"); - addRuleToConstraintTestField("R3", "sample1.drl"); - addRuleToConstraintTestField("R4", "sample1.drl"); - addRuleToConstraintTestField("R5", "sample1.drl"); - addRuleToConstraintTestField("R6", "sample1.drl"); - addRuleToConstraintTestField("R7", "sample2.drl"); - addRuleToConstraintTestField("R8", "sample2.drl"); - addRuleToConstraintTestField("R9", "sample2.drl"); - addRuleToConstraintTestField("R10", "sample3.drl"); - addRuleToConstraintTestField("R11", "sample3.drl"); - - assertMessage("Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\", \"R3\", \"R4\", \"R5\", \"R6\" in sample1.drl] [Rule \"R7\", \"R8\", \"R9\" in sample2.drl] [Rule \"R10\" in sample3.drl]" + + @ParameterizedTest + @MethodSource("parameters") + public void testExceedMaxRuleDefs(RUN_TYPE runType) { + initConstraintTestField(runType, "age > 20", "R1", "sample1.drl"); + addRuleToConstraintTestField(runType, "R2", "sample1.drl"); + addRuleToConstraintTestField(runType, "R3", "sample1.drl"); + addRuleToConstraintTestField(runType, "R4", "sample1.drl"); + addRuleToConstraintTestField(runType, "R5", "sample1.drl"); + addRuleToConstraintTestField(runType, "R6", "sample1.drl"); + addRuleToConstraintTestField(runType, "R7", "sample2.drl"); + addRuleToConstraintTestField(runType, "R8", "sample2.drl"); + addRuleToConstraintTestField(runType, "R9", "sample2.drl"); + addRuleToConstraintTestField(runType, "R10", "sample3.drl"); + addRuleToConstraintTestField(runType, "R11", "sample3.drl"); + + assertMessage(runType, "Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\", \"R3\", \"R4\", \"R5\", \"R6\" in sample1.drl] [Rule \"R7\", \"R8\", \"R9\" in sample2.drl] [Rule \"R10\" in sample3.drl]" + " and in more rules"); } - private void initConstraintTestField(String constraint, String ruleName, String ruleFileName) { - if (testRunType.isExecutableModel()) { + private void initConstraintTestField(RUN_TYPE runType, String constraint, String ruleName, String ruleFileName) { + if (runType.isExecutableModel()) { predicateInformation = new PredicateInformation(constraint, ruleName, ruleFileName); } else { mvelConstraint = new MVELConstraint("com.example", constraint, null, null, null, null, null); @@ -108,8 +109,8 @@ private void initConstraintTestField(String constraint, String ruleName, String } } - private void addRuleToConstraintTestField(String ruleName, String ruleFileName) { - if (testRunType.isExecutableModel()) { + private void addRuleToConstraintTestField(RUN_TYPE runType, String ruleName, String ruleFileName) { + if (runType.isExecutableModel()) { predicateInformation.addRuleNames(ruleName, ruleFileName); } else { // in non-exec-model, node sharing triggers merging @@ -128,9 +129,9 @@ private void addRuleToConstraintTestField(String ruleName, String ruleFileName) } } - private void assertMessage(String expected) { + private void assertMessage(RUN_TYPE runType, String expected) { Exception ex; - if (testRunType.isExecutableModel()) { + if (runType.isExecutableModel()) { ex = new ConstraintEvaluationException(predicateInformation, new RuntimeException("OriginalException")); } else { ex = new org.drools.mvel.ConstraintEvaluationException(mvelConstraint.getExpression(), mvelConstraint.getEvaluationContext(), new RuntimeException("OriginalException")); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/drlx/DrlxCompilerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/drlx/DrlxCompilerTest.java index 83687215e6d..12d250a8dd9 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/drlx/DrlxCompilerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/drlx/DrlxCompilerTest.java @@ -39,9 +39,9 @@ import org.drools.mvel.DrlDumper; import org.drools.mvel.parser.MvelParser; import org.drools.mvel.parser.ParseStart; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.drools.io.InputStreamResource; -import org.junit.Ignore; -import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; @@ -81,7 +81,7 @@ public void testSingleFileUnit() throws Exception { } @Test - @Ignore("Rule Unit compiler is not available in Drools 8 yet") + @Disabled("Rule Unit compiler is not available in Drools 8 yet") public void testCompileUnit() throws IOException { InputStream p = getClass().getClassLoader().getResourceAsStream("drlx1/Example.drlx"); InputStreamResource r = new InputStreamResource(p); @@ -114,7 +114,7 @@ public void testCompileUnit() throws IOException { } @Test - @Ignore("Rule Unit Executor is not available in Drools 8 yet") + @Disabled("Rule Unit Executor is not available in Drools 8 yet") public void testCompileUnitFull() throws IOException { String path = "drlx1/Example.drlx"; InputStream p = getClass().getClassLoader().getResourceAsStream(path); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/exchange/SendReceiveTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/exchange/SendReceiveTest.java index 93a63835411..a278ff378d1 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/exchange/SendReceiveTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/exchange/SendReceiveTest.java @@ -29,7 +29,7 @@ import org.drools.model.impl.Exchange; import org.drools.model.impl.ModelImpl; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/CompilerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/CompilerTest.java index 977d7ef186a..71a699e8268 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/CompilerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/CompilerTest.java @@ -22,21 +22,19 @@ import org.drools.model.codegen.execmodel.fireandalarm.model.Alarm; import org.drools.model.codegen.execmodel.fireandalarm.model.Fire; import org.drools.model.codegen.execmodel.fireandalarm.model.Room; -import org.drools.model.codegen.execmodel.fireandalarm.model.Sprinkler; -import org.junit.Test; +import org.drools.model.codegen.execmodel.fireandalarm.model.Sprinkler; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; +import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; public class CompilerTest extends BaseModelTest { - public CompilerTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testFireAndAlarm() { + @ParameterizedTest + @MethodSource("parameters") + public void testFireAndAlarm(RUN_TYPE runType) { String str = "import " + StringBuilder.class.getCanonicalName() + ";\n" + "import " + Alarm.class.getCanonicalName() + ";\n" + @@ -87,7 +85,7 @@ public void testFireAndAlarm() { " sb.append( \"Everything is ok\\n\" );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StringBuilder sb = new StringBuilder(); ksession.setGlobal( "sb", sb ); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmTest.java index 1c07380ae2d..7161da15f7e 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmTest.java @@ -27,7 +27,7 @@ import org.drools.model.codegen.execmodel.fireandalarm.model.Sprinkler; import org.drools.model.impl.ModelImpl; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmUsingDroolsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmUsingDroolsTest.java index 24de303265d..04cbc8cfaca 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmUsingDroolsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmUsingDroolsTest.java @@ -27,7 +27,7 @@ import org.drools.model.codegen.execmodel.fireandalarm.model.Sprinkler; import org.drools.model.impl.ModelImpl; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConsequenceTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConsequenceTest.java index e2c7c131dfc..56d31bd34a2 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConsequenceTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConsequenceTest.java @@ -18,7 +18,7 @@ */ package org.drools.model.codegen.execmodel.generator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.drools.model.codegen.execmodel.generator.Consequence.containsWord; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConstraintTestUtil.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConstraintTestUtil.java index 15819559b52..d09a5308380 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConstraintTestUtil.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConstraintTestUtil.java @@ -1,5 +1,5 @@ /** - * Licensed to the Apache Software Foundation (ASF) under one +e * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/DrlxParseUtilTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/DrlxParseUtilTest.java index d6c52b92838..0f2e568b92a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/DrlxParseUtilTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/DrlxParseUtilTest.java @@ -40,7 +40,7 @@ import org.drools.util.ClassTypeResolver; import org.drools.util.MethodUtils; import org.drools.util.TypeResolver; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static java.util.Optional.of; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ExpressionTyperTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ExpressionTyperTest.java index 619214eeec6..40c3e3885f8 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ExpressionTyperTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ExpressionTyperTest.java @@ -50,10 +50,11 @@ import org.drools.mvel.parser.printer.PrintUtil; import org.drools.util.ClassTypeResolver; import org.drools.util.TypeResolver; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.drools.model.codegen.execmodel.generator.DrlxParseUtil.THIS_PLACEHOLDER; public class ExpressionTyperTest { @@ -65,7 +66,7 @@ public class ExpressionTyperTest { private KnowledgeBuilderImpl knowledgeBuilder = new KnowledgeBuilderImpl(); private RuleDescr ruleDescr = new RuleDescr("testRule"); - @Before + @BeforeEach public void setUp() throws Exception { imports = new HashSet<>(); packageModel = new PackageModel("", "", null, null, new DRLIdGenerator()); @@ -242,9 +243,9 @@ public void halfBinaryOrAndAmpersand() { assertThat(toTypedExpression("age < 15 || > 20 && < 30", Person.class).getExpression().toString()).isEqualTo(expected); } - @Test(expected = CannotTypeExpressionException.class) + @Test public void invalidHalfBinary() { - toTypedExpression("> 20 && < 30", Person.class).getExpression(); + assertThatExceptionOfType(CannotTypeExpressionException.class).isThrownBy(() ->toTypedExpression("> 20 && < 30", Person.class).getExpression()); } @Test @@ -253,9 +254,9 @@ public void halfPointFreeOrAndAmpersand() { assertThat(toTypedExpression("name str[startsWith] \"M\" || str[endsWith] \"a\" && str[length] 4", Person.class).getExpression().toString()).isEqualTo(expected); } - @Test(expected = CannotTypeExpressionException.class) + @Test public void invalidHalfPointFree() { - toTypedExpression("str[endsWith] \"a\" && str[length] 4", Person.class).getExpression(); + assertThatExceptionOfType(CannotTypeExpressionException.class).isThrownBy(() -> toTypedExpression("str[endsWith] \"a\" && str[length] 4", Person.class).getExpression()); } @Test diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/FlattenScopeTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/FlattenScopeTest.java index e34e2ecd4db..3dcdd3b77c0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/FlattenScopeTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/FlattenScopeTest.java @@ -33,7 +33,7 @@ import com.github.javaparser.ast.expr.SimpleName; import com.github.javaparser.ast.expr.StringLiteralExpr; import org.drools.util.TypeResolver; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.github.javaparser.ast.NodeList.nodeList; import static java.util.Arrays.asList; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/GeneratedClassDeclarationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/GeneratedClassDeclarationTest.java index 84a50b8d325..1b8a3537c1c 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/GeneratedClassDeclarationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/GeneratedClassDeclarationTest.java @@ -26,7 +26,7 @@ import org.drools.model.codegen.execmodel.generator.declaredtype.api.MethodDefinition; import org.drools.model.codegen.execmodel.generator.declaredtype.api.TypeDefinition; import org.drools.model.codegen.execmodel.generator.declaredtype.generator.GeneratedClassDeclaration; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/StringUtilTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/StringUtilTest.java index 3d136d6baa1..8566f953ed2 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/StringUtilTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/StringUtilTest.java @@ -18,7 +18,7 @@ */ package org.drools.model.codegen.execmodel.generator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.drools.modelcompiler.util.StringUtil.toId; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/CoercedExpressionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/CoercedExpressionTest.java index 83e1a2c3a6d..0f2232b39e6 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/CoercedExpressionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/CoercedExpressionTest.java @@ -18,14 +18,12 @@ */ package org.drools.model.codegen.execmodel.generator.drlxparse; -import java.util.Map; - import com.github.javaparser.ast.expr.StringLiteralExpr; import org.drools.util.MethodUtils; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.drools.model.codegen.execmodel.generator.DrlxParseUtil; import org.drools.model.codegen.execmodel.generator.TypedExpression; -import org.junit.Ignore; -import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -193,7 +191,7 @@ private TypedExpression expr(String exprString, Class exprClass) { } @Test - @Ignore("should support bigDecimal coercion also?") + @Disabled("should support bigDecimal coercion also?") public void coerceBigDecimal() { final TypedExpression left = expr(THIS_PLACEHOLDER + ".getRate()", java.math.BigDecimal.class); final TypedExpression right = expr("0.0d", Double.class); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/ConstraintParserTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/ConstraintParserTest.java index cc62dedfdc3..6dd9391edae 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/ConstraintParserTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/ConstraintParserTest.java @@ -31,8 +31,8 @@ import org.drools.modelcompiler.util.EvaluationUtil; import org.drools.util.ClassTypeResolver; import org.drools.util.TypeResolver; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -40,7 +40,7 @@ public class ConstraintParserTest { private ConstraintParser parser; - @Before + @BeforeEach public void setup() { PackageModel packageModel = new PackageModel("org.kie.test:constraint-parser-test:1.0.0", "org.kie.test", null, null, new DRLIdGenerator()); Set imports = new HashSet<>(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/inlinecast/InlineCastTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/inlinecast/InlineCastTest.java index 1d7eb90b6c8..3c60fc5f311 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/inlinecast/InlineCastTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/inlinecast/InlineCastTest.java @@ -25,20 +25,18 @@ import org.drools.model.codegen.execmodel.domain.InternationalAddress; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +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; public class InlineCastTest extends BaseModelTest { - public InlineCastTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testInlineCastThis() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastThis(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -49,7 +47,7 @@ public void testInlineCastThis() { " $r.setValue(\"Found: \" + $o);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -62,8 +60,9 @@ public void testInlineCastThis() { assertThat(result.getValue()).isEqualTo("Found: Mark"); } - @Test - public void testInlineCastProjectionThis() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastProjectionThis(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -74,7 +73,7 @@ public void testInlineCastProjectionThis() { " $r.setValue(\"Found: \" + $name + \" $p class: \" + $p.getClass().getCanonicalName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -86,8 +85,9 @@ public void testInlineCastProjectionThis() { assertThat(result.getValue()).isEqualTo("Found: Mark $p class: " + Person.class.getCanonicalName()); } - @Test - public void testInlineCastProjectionThisExplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastProjectionThisExplicit(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -98,7 +98,7 @@ public void testInlineCastProjectionThisExplicit() { " $r.setValue(\"Found: \" + $name + \" $p class: \" + $p.getClass().getCanonicalName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -131,9 +131,10 @@ public interface DMNModelInstrumentedBase { DMNModelInstrumentedBase getParent(); } - @Ignore("This test is not testing anything") - @Test - public void testExplicitCast() { + @Disabled("This test is not testing anything") + @ParameterizedTest + @MethodSource("parameters") + public void testExplicitCast(RUN_TYPE runType) { String str = "import " + OutputClause.class.getCanonicalName() + "\n;" + "import " + DecisionTable.class.getCanonicalName() + "\n;" + @@ -143,13 +144,14 @@ public void testExplicitCast() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); } - @Ignore("This test is not testing anything") - @Test - public void testInlineCastParent() { + @Disabled("This test is not testing anything") + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastParent(RUN_TYPE runType) { String str = "import " + OutputClause.class.getCanonicalName() + "\n;" + "import " + DecisionTable.class.getCanonicalName() + "\n;" + @@ -159,12 +161,13 @@ public void testInlineCastParent() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); } - @Test - public void testInlineCastProjection() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastProjection(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + InternationalAddress.class.getCanonicalName() + ";" + "rule R when\n" + @@ -173,7 +176,7 @@ public void testInlineCastProjection() { " insert($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); InternationalAddress a = new InternationalAddress("address", "Italy"); @@ -186,8 +189,9 @@ public void testInlineCastProjection() { assertThat(results.iterator().next()).isEqualTo("Italy"); } - @Test - public void testInlineCastProjectionOnMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastProjectionOnMethod(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + InternationalAddress.class.getCanonicalName() + ";" + "rule R when\n" + @@ -196,7 +200,7 @@ public void testInlineCastProjectionOnMethod() { " insert($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); InternationalAddress a = new InternationalAddress("address", "Italy"); @@ -210,8 +214,9 @@ public void testInlineCastProjectionOnMethod() { } - @Test - public void testInlineCastForAField() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastForAField(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + InternationalAddress.class.getCanonicalName() + ";" + "rule R when\n" + @@ -220,7 +225,7 @@ public void testInlineCastForAField() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); InternationalAddress a = new InternationalAddress("address", "Italy"); @@ -233,8 +238,9 @@ public void testInlineCastForAField() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testInlineCastForAFieldWithFQN() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastForAFieldWithFQN(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $p : Person( address#" + InternationalAddress.class.getCanonicalName() + ".state.length == 5 )\n" + @@ -242,7 +248,7 @@ public void testInlineCastForAFieldWithFQN() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); InternationalAddress a = new InternationalAddress("address", "Italy"); @@ -255,8 +261,9 @@ public void testInlineCastForAFieldWithFQN() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testInlineCastForAFieldAndMixMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastForAFieldAndMixMethodCall(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + InternationalAddress.class.getCanonicalName() + ";" + "rule R when\n" + @@ -265,7 +272,7 @@ public void testInlineCastForAFieldAndMixMethodCall() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); InternationalAddress a = new InternationalAddress("address", "Italy"); @@ -278,8 +285,9 @@ public void testInlineCastForAFieldAndMixMethodCall() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testInlineCastSingle() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastSingle(RUN_TYPE runType) { String str = "import " + ICAbstractA.class.getCanonicalName() + ";" + "import " + ICAbstractB.class.getCanonicalName() + ";" + "import " + ICAbstractC.class.getCanonicalName() + ";" + @@ -292,7 +300,7 @@ public void testInlineCastSingle() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ICA a = new ICA(); ICB b = new ICB(); @@ -307,8 +315,9 @@ public void testInlineCastSingle() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testInlineCastMultiple() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastMultiple(RUN_TYPE runType) { String str = "import " + ICAbstractA.class.getCanonicalName() + ";" + "import " + ICAbstractB.class.getCanonicalName() + ";" + "import " + ICAbstractC.class.getCanonicalName() + ";" + @@ -321,7 +330,7 @@ public void testInlineCastMultiple() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ICA a = new ICA(); ICB b = new ICB(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/BaseOperatorsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/BaseOperatorsTest.java index e378e6f0a55..98e0fb4f970 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/BaseOperatorsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/BaseOperatorsTest.java @@ -26,7 +26,6 @@ import org.drools.compiler.kie.builder.impl.DrlProject; import org.drools.model.codegen.ExecutableModelProject; -import org.drools.model.codegen.execmodel.BaseModelTest; import org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE; import org.drools.model.codegen.execmodel.KJARUtils; import org.kie.api.KieServices; @@ -38,16 +37,16 @@ import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; public abstract class BaseOperatorsTest { - protected static final RUN_TYPE[] RUN_TYPES = new BaseModelTest.RUN_TYPE[]{RUN_TYPE.STANDARD_FROM_DRL, RUN_TYPE.PATTERN_DSL}; - protected static final Class[] TYPES = new Class[]{Integer.class, Long.class, Byte.class, Character.class, Short.class, Float.class, Double.class, BigInteger.class, BigDecimal.class}; - protected static final String[] EQUALITY_COMPARISON_OPERATORS = new String[]{"==", "!="}; - protected static final boolean[] NULL_PROPERTY_ON_LEFT = new boolean[]{true, false}; + protected static final RUN_TYPE[] RUN_TYPES = {RUN_TYPE.STANDARD_FROM_DRL, RUN_TYPE.PATTERN_DSL}; + protected static final Class[] TYPES = {Integer.class, Long.class, Byte.class, Character.class, Short.class, Float.class, Double.class, BigInteger.class, BigDecimal.class}; + protected static final String[] EQUALITY_COMPARISON_OPERATORS = {"==", "!="}; + protected static final boolean[] NULL_PROPERTY_ON_LEFT = {true, false}; - protected KieSession getKieSession(String drl, RUN_TYPE testRunType) { + protected KieSession getKieSession(String drl, RUN_TYPE runType) { KieServices ks = KieServices.get(); ReleaseId releaseId = ks.newReleaseId("org.kie", "kjar-test-" + UUID.randomUUID(), "1.0"); @@ -60,12 +59,12 @@ protected KieSession getKieSession(String drl, RUN_TYPE testRunType) { kfs.write("src/main/resources/com/sample/Sample1.drl", drl); KieBuilder kieBuilder; - if (testRunType.equals(RUN_TYPE.STANDARD_FROM_DRL)) { + if (runType.equals(RUN_TYPE.STANDARD_FROM_DRL)) { kieBuilder = ks.newKieBuilder(kfs).buildAll(DrlProject.class); - } else if (testRunType.equals(RUN_TYPE.PATTERN_DSL)) { + } else if (runType.equals(RUN_TYPE.PATTERN_DSL)) { kieBuilder = ks.newKieBuilder(kfs).buildAll(ExecutableModelProject.class); } else { - throw new UnsupportedOperationException(testRunType + " is not supported"); + throw new UnsupportedOperationException(runType + " is not supported"); } List messages = kieBuilder.getResults().getMessages(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/DateOperatorTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/DateOperatorTest.java index 482bf005670..588bbcef0ed 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/DateOperatorTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/DateOperatorTest.java @@ -22,22 +22,18 @@ import java.text.SimpleDateFormat; import org.drools.model.codegen.execmodel.BaseModelTest; -import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.SimpleDateHolder; -import org.junit.Ignore; -import org.junit.Test; +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; public class DateOperatorTest extends BaseModelTest { - public DateOperatorTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void dateBetweenGlobals() throws ParseException { + @ParameterizedTest + @MethodSource("parameters") + public void dateBetweenGlobals(RUN_TYPE runType) throws ParseException { String str = "import " + SimpleDateHolder.class.getCanonicalName() + ";" + "global java.util.Date $startDate;\n" + @@ -47,7 +43,7 @@ public void dateBetweenGlobals() throws ParseException { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); ksession.setGlobal("$startDate", sdf.parse("04/01/2019")); ksession.setGlobal("$endDate", sdf.parse("05/01/2019")); @@ -59,8 +55,9 @@ public void dateBetweenGlobals() throws ParseException { assertThat(fired).isEqualTo(1); } - @Test - public void dateBetweenVariables() throws ParseException { + @ParameterizedTest + @MethodSource("parameters") + public void dateBetweenVariables(RUN_TYPE runType) throws ParseException { String str = "import " + SimpleDateHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -70,7 +67,7 @@ public void dateBetweenVariables() throws ParseException { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateHolder holderA = new SimpleDateHolder("A", sdf.parse("04/01/2019")); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonTest.java index 60c5b548361..824bce2c014 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonTest.java @@ -19,64 +19,52 @@ package org.drools.model.codegen.execmodel.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) public class EqualityComparisonTest extends BaseOperatorsTest { - @Parameters(name = "{0} {1} {2} {3}") - public static Collection ruleParams() { - List parameterData = new ArrayList(); + public static Stream ruleParams() { + List parameterData = new ArrayList(); for (RUN_TYPE runType : RUN_TYPES) { for (Class type : TYPES) { for (String operator : EQUALITY_COMPARISON_OPERATORS) { for (boolean nullPropertyOnLeft : NULL_PROPERTY_ON_LEFT) - parameterData.add(new Object[]{runType, type, operator, nullPropertyOnLeft}); + parameterData.add(arguments(runType, type, operator, nullPropertyOnLeft)); } } } - return parameterData; + + return Stream.of(parameterData.toArray(new Arguments[0])); } - @Parameterized.Parameter(0) - public RUN_TYPE testRunType; - - @Parameterized.Parameter(1) - public Class type; - - @Parameterized.Parameter(2) - public String operator; - - @Parameterized.Parameter(3) - public boolean nullPropertyOnLeft; - - @Before + @BeforeEach public void setUp() { org.drools.compiler.rule.builder.util.ConstraintTestUtil.disableNormalizeConstraint(); org.drools.model.codegen.execmodel.generator.ConstraintTestUtil.disableNormalizeConstraint(); } - @After + @AfterEach public void tearDown() { org.drools.compiler.rule.builder.util.ConstraintTestUtil.enableNormalizeConstraint(); org.drools.model.codegen.execmodel.generator.ConstraintTestUtil.enableNormalizeConstraint(); } - @Test - public void compareWithNullProperty() throws Exception { + @ParameterizedTest(name = "{0} {1} {2} {3}") + @MethodSource("ruleParams") + public void compareWithNullProperty(RUN_TYPE testRunType, Class type, String operator, boolean nullPropertyOnLeft) throws Exception { String propertyName = BaseOperatorsTest.getPropertyName(type); String instanceValueString = BaseOperatorsTest.getInstanceValueString(type); String drl = "import " + type.getCanonicalName() + ";\n" + @@ -95,11 +83,7 @@ public void compareWithNullProperty() throws Exception { ksession.insert(new ValueHolder()); try { int fired = ksession.fireAllRules(); - if (operator.equals("==") && fired == 0 || operator.equals("!=") && fired == 1) { - assertTrue(true); - } else { - fail("Wrong result"); - } + assertThat(operator.equals("==") && fired == 0 || operator.equals("!=") && fired == 1).withFailMessage("Wrong result").isTrue(); } catch (org.drools.mvel.ConstraintEvaluationException | org.drools.modelcompiler.constraints.ConstraintEvaluationException e) { throw new RuntimeException("Unexpected Exception", e); } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonWith2PropertiesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonWith2PropertiesTest.java index 67439d0513f..93c5dc7e34f 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonWith2PropertiesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonWith2PropertiesTest.java @@ -19,64 +19,54 @@ package org.drools.model.codegen.execmodel.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.arguments; -@RunWith(Parameterized.class) public class EqualityComparisonWith2PropertiesTest extends BaseOperatorsTest { - @Parameters(name = "{0} {1} {2} {3}") - public static Collection ruleParams() { - List parameterData = new ArrayList(); + + + public static Stream ruleParams() { + List parameterData = new ArrayList(); for (RUN_TYPE runType : RUN_TYPES) { for (Class type : TYPES) { for (String operator : EQUALITY_COMPARISON_OPERATORS) { for (boolean nullPropertyOnLeft : NULL_PROPERTY_ON_LEFT) - parameterData.add(new Object[]{runType, type, operator, nullPropertyOnLeft}); + parameterData.add(arguments(runType, type, operator, nullPropertyOnLeft)); } } } - return parameterData; + + return Stream.of(parameterData.toArray(new Arguments[0])); } + - @Parameterized.Parameter(0) - public RUN_TYPE testRunType; - - @Parameterized.Parameter(1) - public Class type; - - @Parameterized.Parameter(2) - public String operator; - - @Parameterized.Parameter(3) - public boolean nullPropertyOnLeft; - - @Before + @BeforeEach public void setUp() { org.drools.compiler.rule.builder.util.ConstraintTestUtil.disableNormalizeConstraint(); org.drools.model.codegen.execmodel.generator.ConstraintTestUtil.disableNormalizeConstraint(); } - @After + @AfterEach public void tearDown() { org.drools.compiler.rule.builder.util.ConstraintTestUtil.enableNormalizeConstraint(); org.drools.model.codegen.execmodel.generator.ConstraintTestUtil.enableNormalizeConstraint(); } - @Test - public void compareWithNullProperty() throws Exception { + @ParameterizedTest(name = "{0} {1} {2} {3}") + @MethodSource("ruleParams") + public void compareWithNullProperty(RUN_TYPE testRunType, Class type, String operator, boolean nullPropertyOnLeft) throws Exception { String firstPropertyName = BaseOperatorsTest.getPropertyNameWithPrefix(type, "first"); String secondPropertyName = BaseOperatorsTest.getPropertyNameWithPrefix(type, "second"); String drl = "import " + type.getCanonicalName() + ";\n" + @@ -95,11 +85,7 @@ public void compareWithNullProperty() throws Exception { ksession.insert(new ValueHolderWith2Properties()); try { int fired = ksession.fireAllRules(); - if (operator.equals("==") && fired == 0 || operator.equals("!=") && fired == 1) { - assertTrue(true); - } else { - fail("Wrong result"); - } + assertThat(operator.equals("==") && fired == 0 || operator.equals("!=") && fired == 1).withFailMessage("Wrong result").isTrue(); } catch (org.drools.mvel.ConstraintEvaluationException | org.drools.modelcompiler.constraints.ConstraintEvaluationException e) { throw new RuntimeException("Unexpected Exception", e); } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/LambdaUtilTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/LambdaUtilTest.java index 115868333e5..63e3698eb08 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/LambdaUtilTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/LambdaUtilTest.java @@ -20,7 +20,8 @@ import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.LambdaExpr; -import org.junit.Test; + +import org.junit.jupiter.api.Test; import static com.github.javaparser.StaticJavaParser.parseExpression; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/ExecModelLambdaPostProcessorTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/ExecModelLambdaPostProcessorTest.java index 877ce72394c..8551686e008 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/ExecModelLambdaPostProcessorTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/ExecModelLambdaPostProcessorTest.java @@ -22,18 +22,19 @@ import java.util.ArrayList; import java.util.HashMap; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.MethodDeclaration; -import org.junit.Before; -import org.junit.Test; import static com.github.javaparser.StaticJavaParser.parseResource; import static org.drools.model.codegen.execmodel.util.lambdareplace.MaterializedLambdaTestUtils.verifyCreatedClass; public class ExecModelLambdaPostProcessorTest { - @Before + @BeforeEach public void configJP() { StaticJavaParser.getConfiguration().setCharacterEncoding(Charset.defaultCharset()); } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaConsequenceTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaConsequenceTest.java index 0505fb10a40..747aa5b188f 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaConsequenceTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaConsequenceTest.java @@ -23,7 +23,7 @@ import java.util.Collections; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.drools.model.codegen.execmodel.util.lambdareplace.MaterializedLambdaTestUtils.verifyCreatedClass; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaExtractorTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaExtractorTest.java index a238d833c71..bff83366078 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaExtractorTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaExtractorTest.java @@ -20,7 +20,7 @@ import java.util.ArrayList; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.drools.model.codegen.execmodel.generator.DrlxParseUtil.toClassOrInterfaceType; import static org.drools.model.codegen.execmodel.util.lambdareplace.MaterializedLambdaTestUtils.verifyCreatedClass; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaPredicateTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaPredicateTest.java index 643d4b976f6..678e63daa73 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaPredicateTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaPredicateTest.java @@ -21,7 +21,7 @@ import java.util.ArrayList; import org.drools.model.functions.PredicateInformation; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.drools.model.codegen.execmodel.util.lambdareplace.MaterializedLambdaTestUtils.verifyCreatedClass; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/variables/VariablesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/variables/VariablesTest.java index ea8744845ef..a9f229d0ce0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/variables/VariablesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/variables/VariablesTest.java @@ -21,19 +21,17 @@ import java.util.Collection; import org.drools.model.codegen.execmodel.BaseModelTest; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; import org.kie.api.runtime.KieSession; public class VariablesTest extends BaseModelTest { - - public VariablesTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testThreeVariables() { + + @ParameterizedTest + @MethodSource("parameters") + public void testThreeVariables(BaseModelTest.RUN_TYPE testRunType) { String str = "import " + SimpleObject.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -46,7 +44,7 @@ public void testThreeVariables() { "insert (new Result($id, $v1 + $v2));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(testRunType, str); SimpleObject m1 = new SimpleObject("id", 1); SimpleObject m2 = new SimpleObject("id", 2); @@ -60,8 +58,9 @@ public void testThreeVariables() { assertThat(results.iterator().next().getValue()).isEqualTo(3); } - @Test - public void testFourVariables() { + @ParameterizedTest + @MethodSource("parameters") + public void testFourVariables(BaseModelTest.RUN_TYPE testRunType) { String str = "import " + SimpleObject.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -75,7 +74,7 @@ public void testFourVariables() { "insert (new Result($id, $v1 + $v2 + $v3));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(testRunType, str); SimpleObject m1 = new SimpleObject("id", 1); SimpleObject m2 = new SimpleObject("id", 2); @@ -91,8 +90,9 @@ public void testFourVariables() { assertThat(results.iterator().next().getValue()).isEqualTo(6); } - @Test - public void testFiveVariables() { + @ParameterizedTest + @MethodSource("parameters") + public void testFiveVariables(BaseModelTest.RUN_TYPE testRunType) { String str = "import " + SimpleObject.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -107,7 +107,7 @@ public void testFiveVariables() { "insert (new Result($id, $v1 + $v2 + $v3 + $v4));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(testRunType, str); SimpleObject m1 = new SimpleObject("id", 1); SimpleObject m2 = new SimpleObject("id", 2); @@ -125,8 +125,9 @@ public void testFiveVariables() { assertThat(results.iterator().next().getValue()).isEqualTo(10); } - @Test - public void testSixVariables() { + @ParameterizedTest + @MethodSource("parameters") + public void testSixVariables(BaseModelTest.RUN_TYPE testRunType) { String str = "import " + SimpleObject.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -142,7 +143,7 @@ public void testSixVariables() { "insert (new Result($id, $v1 + $v2 + $v3 + $v4 + $v5));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(testRunType, str); SimpleObject m1 = new SimpleObject("id", 1); SimpleObject m2 = new SimpleObject("id", 2); diff --git a/drools-model/drools-model-compiler/pom.xml b/drools-model/drools-model-compiler/pom.xml index c7128d54f13..99d7f28ba6a 100644 --- a/drools-model/drools-model-compiler/pom.xml +++ b/drools-model/drools-model-compiler/pom.xml @@ -68,9 +68,9 @@ - junit - junit - test + org.junit.jupiter + junit-jupiter + test org.assertj diff --git a/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLTest.java b/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLTest.java index bb7f803825f..a9692d970b9 100644 --- a/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLTest.java +++ b/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLTest.java @@ -59,11 +59,10 @@ import org.drools.modelcompiler.domain.Woman; import org.drools.modelcompiler.dsl.pattern.D; import org.drools.modelcompiler.util.EvaluationUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.conf.EventProcessingOption; -import org.kie.api.runtime.ClassObjectFilter; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.KieSessionConfiguration; import org.kie.api.runtime.conf.ClockTypeOption; diff --git a/drools-model/drools-model-prototype/pom.xml b/drools-model/drools-model-prototype/pom.xml index 55892638c63..7d035e24bdd 100644 --- a/drools-model/drools-model-prototype/pom.xml +++ b/drools-model/drools-model-prototype/pom.xml @@ -56,9 +56,9 @@ - junit - junit - test + org.junit.jupiter + junit-jupiter + test org.assertj diff --git a/drools-model/drools-model-prototype/src/test/java/org/drools/model/prototype/PrototypeFieldExtractorTest.java b/drools-model/drools-model-prototype/src/test/java/org/drools/model/prototype/PrototypeFieldExtractorTest.java index 0b081f3c43c..9f9e0c5c1cd 100644 --- a/drools-model/drools-model-prototype/src/test/java/org/drools/model/prototype/PrototypeFieldExtractorTest.java +++ b/drools-model/drools-model-prototype/src/test/java/org/drools/model/prototype/PrototypeFieldExtractorTest.java @@ -23,7 +23,7 @@ import org.drools.base.rule.Declaration; import org.drools.base.rule.Pattern; import org.drools.base.rule.accessor.ReadAccessor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.prototype.PrototypeFact; import org.kie.api.prototype.PrototypeFactInstance; diff --git a/drools-model/drools-mvel-compiler/pom.xml b/drools-model/drools-mvel-compiler/pom.xml index 7bb56461fac..68e8e37d9a7 100644 --- a/drools-model/drools-mvel-compiler/pom.xml +++ b/drools-model/drools-mvel-compiler/pom.xml @@ -38,11 +38,6 @@ - - junit - junit - test - com.github.javaparser @@ -57,6 +52,11 @@ drools-core + + org.junit.jupiter + junit-jupiter + test + org.assertj assertj-core diff --git a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvel/ArithmeticTest.java b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvel/ArithmeticTest.java index d8b43dfb040..c4aa468b007 100644 --- a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvel/ArithmeticTest.java +++ b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvel/ArithmeticTest.java @@ -24,8 +24,8 @@ import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.within; @@ -43,7 +43,7 @@ public class ArithmeticTest { - @Ignore("DROOLS-6572 - Generates wrong code for promotion") + @Disabled("DROOLS-6572 - Generates wrong code for promotion") @Test public void testMath() { String expression = "pi * hour"; @@ -57,7 +57,7 @@ public void testMath2() { assertThat(executeExpressionWithDefaultVariables("foo.number-1")).isEqualTo(3); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath3() { String expression = "(10 * 5) * 2 / 3"; @@ -66,7 +66,7 @@ public void testMath3() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath4() { String expression = "(100 % 3) * 2 - 1 / 1 + 8 + (5 * 2)"; @@ -75,7 +75,7 @@ public void testMath4() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath4a() { String expression = "(100 % 90) * 20 - 15 / 16 + 80 + (50 * 21)"; @@ -100,7 +100,7 @@ public void testMath5a() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath6() { String expression = "(300 * five + 1) + (100 / 2 * 2)"; @@ -109,7 +109,7 @@ public void testMath6() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath7() { String expression = "(100 % 3) * 2 - 1 / 1 + 8 + (5 * 2)"; @@ -126,13 +126,13 @@ public void testMath8() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testPowerOf() { assertThat(executeExpressionWithDefaultVariables("5 ** 2")).isEqualTo(25); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testSignOperator() { String expr = "int x = 15; -x"; @@ -173,7 +173,7 @@ public void testMath17() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse multiple assignements") + @Disabled("DROOLS-6572 - Unable to parse multiple assignements") @Test public void testMath18() { String expression = "a = 100d; b = 50d; c = 20d; d = 30d; e = 2d; (a * b) * c / d * e"; @@ -182,7 +182,7 @@ public void testMath18() { assertThat(executeExpression(expression, Collections.emptyMap())).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse multiple assignments") + @Disabled("DROOLS-6572 - Unable to parse multiple assignments") @Test public void testMath19() { String expression = "a = 100; b = 500; c = 200; d = 150; e = 500; f = 800; g = 400; a-b*c*d + e*f-g"; @@ -190,7 +190,7 @@ public void testMath19() { assertThat(executeExpression(expression, Collections.emptyMap())).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testMath32() { String expression = "x = 20; y = 10; z = 5; x-y-z"; @@ -199,7 +199,7 @@ public void testMath32() { assertThat(executeExpression(expression, Collections.emptyMap())).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testMath33() { String expression = "x = 20; y = 2; z = 2; x/y/z"; @@ -224,7 +224,7 @@ public void testMath21() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(expected); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath22() { String expression = "(100-50)*70-30*(20-9)**3"; @@ -233,7 +233,7 @@ public void testMath22() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath22b() { String expression = "a = 100; b = 50; c = 70; d = 30; e = 20; f = 9; g = 3; (a-b)*c-d*(e-f)**g"; @@ -242,7 +242,7 @@ public void testMath22b() { assertThat(executeExpression(expression, Collections.emptyMap())).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath23() { String expression = "10 ** (3)*10**3"; @@ -251,7 +251,7 @@ public void testMath23() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath24() { String expression = "51 * 52 * 33 / 24 / 15 + 45 * 66 * 47 * 28 + 19"; @@ -260,7 +260,7 @@ public void testMath24() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Calculation error") + @Disabled("DROOLS-6572 - Calculation error") @Test public void testMath25() { String expression = "51 * (40 - 1000 * 50) + 100 + 50 * 20 / 10 + 11 + 12 - 80"; @@ -269,7 +269,7 @@ public void testMath25() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath26() { String expression = "5 + 3 * 8 * 2 ** 2"; @@ -278,7 +278,7 @@ public void testMath26() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath27() { String expression = "50 + 30 * 80 * 20 ** 3 * 51"; @@ -287,7 +287,7 @@ public void testMath27() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo((int) result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath28() { String expression = "50 + 30 + 80 + 11 ** 2 ** 2 * 51"; @@ -296,7 +296,7 @@ public void testMath28() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo((int) result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath29() { String expression = "10 + 20 / 4 / 4"; @@ -305,7 +305,7 @@ public void testMath29() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath30() { String expression = "40 / 20 + 10 + 60 / 21"; @@ -314,7 +314,7 @@ public void testMath30() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath31() { String expression = "40 / 20 + 5 - 4 + 8 / 2 * 2 * 6 ** 2 + 6 - 8"; @@ -323,7 +323,7 @@ public void testMath31() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath34() { String expression = "a+b-c*d*x/y-z+10"; @@ -341,7 +341,7 @@ public void testMath34() { assertThat(executeExpression(expression, map)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath34_Interpreted() { String expression = "a+b-c*x/y-z"; @@ -358,7 +358,7 @@ public void testMath34_Interpreted() { assertThat(executeExpression(expression, map)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath35() { String expression = "b/x/b/b*y+a"; @@ -376,7 +376,7 @@ public void testMath35() { } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath35_Interpreted() { String expression = "b/x/b/b*y+a"; @@ -393,7 +393,7 @@ public void testMath35_Interpreted() { assertThat(executeExpression(expression, map)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath36() { String expression = "b/x*z/a+x-b+x-b/z+y"; @@ -410,7 +410,7 @@ public void testMath36() { assertThat(executeExpression(expression, map)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath37() { String expression = "x+a*a*c/x*b*z+x/y-b"; @@ -427,7 +427,7 @@ public void testMath37() { assertThat(executeExpression(expression, map)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath38() { String expression = "100 + 200 - 300 + 400 - 500 + 105 / 205 - 405 + 305 * 206"; @@ -436,7 +436,7 @@ public void testMath38() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath39() { String expression = "147 + 60 / 167 % 448 + 36 * 23 / 166"; @@ -445,7 +445,7 @@ public void testMath39() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath40() { String expression = "228 - 338 % 375 - 103 + 260 + 412 * 177 + 121"; @@ -507,21 +507,21 @@ public void testMath44b() { assertThat(executeExpression(expression, vars)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testOperatorPrecedence() { String expression = "_x_001 = 500.2; _x_002 = 200.8; _r_001 = 701; _r_001 == _x_001 + _x_002 || _x_001 == 500 + 0.1"; assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(true); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testOperatorPrecedence2() { String expression = "_x_001 = 500.2; _x_002 = 200.8; _r_001 = 701; _r_001 == _x_001 + _x_002 && _x_001 == 500 + 0.2"; assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(true); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testOperatorPrecedence3() { String expression = "_x_001 = 500.2; _x_002 = 200.9; _r_001 = 701; _r_001 == _x_001 + _x_002 && _x_001 == 500 + 0.2"; @@ -529,7 +529,7 @@ public void testOperatorPrecedence3() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(false); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testOperatorPrecedence4() { String expression = "_x_001 = 500.2; _x_002 = 200.9; _r_001 = 701; _r_001 == _x_001 + _x_002 || _x_001 == 500 + 0.2"; @@ -558,13 +558,13 @@ public void testBitwiseOr1() { assertThat(executeExpressionWithDefaultVariables("2|4")).isEqualTo(6); } - @Ignore("DROOLS-6572 - Considers second element a boolean") + @Disabled("DROOLS-6572 - Considers second element a boolean") @Test public void testBitwiseOr2() { assertThat(executeExpressionWithDefaultVariables("(2 | 1) > 0")).isEqualTo(true); } - @Ignore("DROOLS-6572 - Considers second element a boolean") + @Disabled("DROOLS-6572 - Considers second element a boolean") @Test public void testBitwiseOr3() { assertThat(executeExpressionWithDefaultVariables("(2|1) == 3")).isEqualTo(true); @@ -595,7 +595,7 @@ public void testShiftLeft2() { assertThat(executeExpressionWithDefaultVariables("five << 1")).isEqualTo(5 << 1); } - @Ignore("DROOLS-6572 - Generates wrong code - unable to parse <<<") + @Disabled("DROOLS-6572 - Generates wrong code - unable to parse <<<") @Test public void testUnsignedShiftLeft() { assertThat(executeExpressionWithDefaultVariables("-2 <<< 0")).isEqualTo(2); @@ -631,7 +631,7 @@ public void testShiftLeftAssign() { assertThat(executeExpressionWithDefaultVariables("_yYy = 10; _yYy <<= 2")).isEqualTo(10 << 2); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testUnsignedShiftRightAssign() { String expression = "_xXx = -5; _xXx >>>= 2"; @@ -669,7 +669,7 @@ public void testDeepPropertyAdd() { assertThat(executeExpressionWithDefaultVariables("foo.countTest+ 10")).isEqualTo(10); } - @Ignore("DROOLS-6572 - Generates wrong code") + @Disabled("DROOLS-6572 - Generates wrong code") @Test public void testDeepAssignmentIncrement() { String expression = "foo.countTest += 5; if (foo.countTest == 5) { foo.countTest = 0; return true; }" + @@ -681,7 +681,7 @@ public void testDeepAssignmentIncrement() { " else { foo.countTest = 0; return false; }")).isEqualTo(true); } - @Ignore("DROOLS-6572 - Generates wrong code - check for statements") + @Disabled("DROOLS-6572 - Generates wrong code - check for statements") @Test public void testDeepAssignmentWithBlock() { String expression = "with (foo) { countTest += 5 }; if (foo.countTest == 5) { foo.countTest = 0; return true; }" + @@ -723,19 +723,19 @@ public void testOperativeAssignShift3() { assertThat(executeExpressionWithDefaultVariables("int val = -5; val >>>= 2; val")).isEqualTo(val >>>= 2); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testAssignPlus() { assertThat(executeExpressionWithDefaultVariables("xx0 = 5; xx0 += 4; xx0 + 1")).isEqualTo(10); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testAssignPlus2() { assertThat(executeExpressionWithDefaultVariables("xx0 = 5; xx0 =+ 4; xx0 + 1")).isEqualTo(10); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testAssignDiv() { assertThat(executeExpressionWithDefaultVariables("xx0 = 20; xx0 /= 10; xx0")).isEqualTo(2.0); @@ -750,7 +750,7 @@ public void testAssignSub() { assertThat(executeExpressionWithDefaultVariables("xx0 = 15; xx0 -= 4; xx0")).isEqualTo(11); } - @Ignore("DROOLS-6572 - Calculation error") + @Disabled("DROOLS-6572 - Calculation error") @Test public void testAssignSub2() { assertThat(executeExpressionWithDefaultVariables("xx0 = 5; xx0 =- 100")).isEqualTo(-95); @@ -762,7 +762,7 @@ public void testBooleanStrAppend() { } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testStringAppend() { String expression = "c + 'bar'"; @@ -784,7 +784,7 @@ public void testStrongTypingModeComparison() { } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testJIRA158() { String expression = "(float) (4/2 + Math.sin(1))"; @@ -822,7 +822,7 @@ public void testJIRA163() { assertThat(executeExpression(expression, vars)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164() { String expression = "1 / (var1 + var1) * var1"; @@ -837,7 +837,7 @@ public void testJIRA164() { } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164b() { String expression = "1 + 1 / (var1 + var1) * var1"; @@ -850,7 +850,7 @@ public void testJIRA164b() { assertThat(executeExpression(expression, vars)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164c() { double var1 = 1d; @@ -864,7 +864,7 @@ public void testJIRA164c() { assertThat(executeExpression(expression, vars)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164d() { double var1 = 1d; @@ -877,7 +877,7 @@ public void testJIRA164d() { assertThat(executeExpression(expression, vars)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164e() { String expression = "10 + 11 + 12 / (var1 + var1 + 51 + 71) * var1 + 13 + 14"; @@ -889,7 +889,7 @@ public void testJIRA164e() { assertThat(((Double) executeExpression(expression, vars)).floatValue()).isCloseTo((float) (10 + 11 + 12 / (var1 + var1 + 51 + 71) * var1 + 13 + 14), within(0.01f)); } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164f() { String expression = "10 + 11 + 12 / (var1 + 1 + var1 + 51 + 71) * var1 + 13 + 14"; @@ -995,7 +995,7 @@ public void testJIRA210() { } } - @Ignore("DROOLS-6572 - Generates wrong code - missing symbol") + @Disabled("DROOLS-6572 - Generates wrong code - missing symbol") @Test public void testMathDec30() { Map params = new HashMap<>(); @@ -1027,7 +1027,7 @@ public void testJIRA99_Compiled() { assertThat(executeExpression("x - y - z", map)).isEqualTo(20 - 10 - 5); } - @Ignore("DROOLS-6572 - Too many iterations - why") + @Disabled("DROOLS-6572 - Too many iterations - why") @Test public void testModExpr() { String str = "$y % 4 == 0 && $y % 100 != 0 || $y % 400 == 0 "; @@ -1054,7 +1054,7 @@ public void testIntsWithDivision() { assertThat(result).isTrue(); } - @Ignore("DROOLS-6572 - Wrong result") + @Disabled("DROOLS-6572 - Wrong result") @Test public void testMathCeil() { String expression = "Math.ceil( x/3 ) == 2"; @@ -1065,7 +1065,7 @@ public void testMathCeil() { assertThat(result).isTrue(); } - @Ignore("DROOLS-6572 - Generates wrong code") + @Disabled("DROOLS-6572 - Generates wrong code") @Test public void testStaticMathCeil() { int x = 4; @@ -1078,7 +1078,7 @@ public void testStaticMathCeil() { assertThat(executeExpression(expression, vars)).isEqualTo(Integer.valueOf(2)); } - @Ignore("DROOLS-6572 - Calculates wrong result") + @Disabled("DROOLS-6572 - Calculates wrong result") @Test public void testStaticMathCeilWithJavaClassStyleLiterals() { String expression = "java.lang.Math.ceil( x/3 )"; diff --git a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/ConstraintCompilerTest.java b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/ConstraintCompilerTest.java index a84d73bd9f0..0f6401d3710 100644 --- a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/ConstraintCompilerTest.java +++ b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/ConstraintCompilerTest.java @@ -27,8 +27,8 @@ import org.drools.Person; import org.drools.util.ClassTypeResolver; import org.drools.util.TypeResolver; +import org.junit.jupiter.api.Test; import org.drools.mvelcompiler.context.MvelCompilerContext; -import org.junit.Test; public class ConstraintCompilerTest implements CompilerTest { diff --git a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/MvelCompilerTest.java b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/MvelCompilerTest.java index 9604a497243..74bdd45d5b6 100644 --- a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/MvelCompilerTest.java +++ b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/MvelCompilerTest.java @@ -24,7 +24,7 @@ import org.drools.Person; import org.drools.util.MethodUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/PreprocessCompilerTest.java b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/PreprocessCompilerTest.java index c02fc88b30b..1296cee6214 100644 --- a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/PreprocessCompilerTest.java +++ b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/PreprocessCompilerTest.java @@ -23,7 +23,7 @@ import org.drools.Person; import org.drools.mvelcompiler.context.MvelCompilerContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/util/MethodResolutionUtilsTest.java b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/util/MethodResolutionUtilsTest.java index 7bef361efae..1d561331f0a 100644 --- a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/util/MethodResolutionUtilsTest.java +++ b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/util/MethodResolutionUtilsTest.java @@ -35,7 +35,7 @@ import org.drools.mvelcompiler.ast.StringLiteralExpressionT; import org.drools.mvelcompiler.ast.TypedExpression; import org.drools.mvelcompiler.context.MvelCompilerContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.util.ArrayList; diff --git a/drools-model/drools-mvel-parser/pom.xml b/drools-model/drools-mvel-parser/pom.xml index 00c721b6eca..5d0bf9a42cc 100644 --- a/drools-model/drools-mvel-parser/pom.xml +++ b/drools-model/drools-mvel-parser/pom.xml @@ -48,9 +48,9 @@ test - junit - junit - test + org.junit.jupiter + junit-jupiter + test org.assertj diff --git a/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DrlxParserTest.java b/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DrlxParserTest.java index 6bb61df814a..9c505d358f5 100644 --- a/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DrlxParserTest.java +++ b/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DrlxParserTest.java @@ -21,10 +21,11 @@ import java.io.IOException; import java.nio.file.Paths; +import org.junit.jupiter.api.Test; + import com.github.javaparser.ParseResult; import com.github.javaparser.ParserConfiguration; import com.github.javaparser.ast.CompilationUnit; -import org.junit.Test; import static org.assertj.core.api.Assertions.fail; import static org.drools.mvel.parser.Providers.provider; diff --git a/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java b/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java index 49910e35269..2092885874c 100644 --- a/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java +++ b/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java @@ -47,11 +47,12 @@ import org.drools.mvel.parser.ast.expr.TemporalLiteralChunkExpr; import org.drools.mvel.parser.ast.expr.TemporalLiteralExpr; import org.drools.mvel.parser.printer.PrintUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.drools.mvel.parser.DrlxParser.parseExpression; import static org.drools.mvel.parser.printer.PrintUtil.printNode; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class DroolsMvelParserTest { @@ -293,10 +294,10 @@ public void testHalfDotFreeExprWithFourTemporalArgs() { assertThat(printNode(expression)).isEqualTo(expr); } - @Test(expected = ParseProblemException.class) + @Test public void testInvalidTemporalArgs() { String expr = "this after[5ms,8f] $a"; - Expression expression = parseExpression( parser, expr ).getExpr(); + assertThatExceptionOfType(ParseProblemException.class).isThrownBy(() -> parseExpression( parser, expr ).getExpr()); } @Test @@ -797,10 +798,10 @@ public void testModifyStatement() { "}"); } - @Test(expected = ParseProblemException.class) + @Test public void testModifyFailing() { String expr = "{ modify { name = \"Luca\", age = \"35\" }; }"; - MvelParser.parseBlock(expr); + assertThatExceptionOfType(ParseProblemException.class).isThrownBy(() -> MvelParser.parseBlock(expr)); } @Test @@ -875,10 +876,10 @@ public void testWithStatement() { "}"); } - @Test(expected = ParseProblemException.class) + @Test public void testWithFailing() { String expr = "{ with { name = \"Luca\", age = \"35\" }; }"; - MvelParser.parseBlock(expr); + assertThatExceptionOfType(ParseProblemException.class).isThrownBy(() -> MvelParser.parseBlock(expr)); } @Test From 4569d0142244196211551d0c6ad1a6e5017a76ec Mon Sep 17 00:00:00 2001 From: Gabriele Cardosi Date: Fri, 18 Oct 2024 10:29:39 +0200 Subject: [PATCH 136/141] [incubator-kie-issues#1543] Add the "id" of executed rules to the AfterEvaluateDecisionTableEvent (#6127) * [incubator-kie-issues#1543] Add the "id" of executed rules to the AfterEvaluateDecisionTableEvent * [incubator-kie-issues#1543] Fix TODO * [incubator-kie-issues#1543] Fix license header * [incubator-kie-issues#1543] Minor refactoring on unrelated test * [incubator-kie-issues#1543] Fix as per PR review --------- Co-authored-by: Gabriele-Cardosi --- .../AfterEvaluateDecisionTableEvent.java | 4 + .../jsr223/JSR223DTExpressionEvaluator.java | 6 +- .../core/ast/DMNDTExpressionEvaluator.java | 10 +- .../core/compiler/DMNEvaluatorCompiler.java | 2 +- .../DMNAlphaNetworkEvaluatorImpl.java | 5 +- .../core/compiler/alphanetbased/Results.java | 49 +- .../AfterEvaluateDecisionTableEventImpl.java | 17 +- .../impl/DMNRuntimeEventManagerUtils.java | 4 +- .../org/kie/dmn/core/DMNInputRuntimeTest.java | 38 +- .../decisiontables/DTDecisionRule.java | 8 +- .../decisiontables/DecisionTableImpl.java | 14 +- .../runtime/decisiontables/HitPolicy.java | 482 +++++++++--------- .../DecisionTableRulesMatchedEvent.java | 9 +- .../DecisionTableRulesSelectedEvent.java | 9 +- .../functions/DecisionTableFunction.java | 2 +- .../ForIterationUtilsTest.java | 4 +- .../runtime/functions/DateFunctionTest.java | 2 +- 17 files changed, 369 insertions(+), 296 deletions(-) diff --git a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateDecisionTableEvent.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateDecisionTableEvent.java index 3fac12be823..6daa2958bd5 100644 --- a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateDecisionTableEvent.java +++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateDecisionTableEvent.java @@ -33,4 +33,8 @@ default String getDecisionTableId() { List getMatches(); List getSelected(); + + List getMatchesIds(); + + List getSelectedIds(); } diff --git a/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java b/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java index afa8009e4d7..93fe8a412e9 100644 --- a/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java @@ -106,7 +106,11 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager dmrem, DMNResult dmnr) { LOG.debug("failed evaluate", e); throw new RuntimeException(e); } finally { - DMNRuntimeEventManagerUtils.fireAfterEvaluateDecisionTable( dmrem, node.getName(), node.getName(), dt.getId(), result, (r != null ? r.matchedRules : null), (r != null ? r.fired : null) ); + DMNRuntimeEventManagerUtils.fireAfterEvaluateDecisionTable( dmrem, node.getName(), node.getName(), dt.getId(), result, + (r != null ? r.matchedRules : null), + (r != null ? r.fired : null), + (r != null ? r.matchedIds : null), + (r != null ? r.firedIds : null)); } } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java index 8293f82e672..4b1cc02daf3 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java @@ -103,7 +103,11 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager dmrem, DMNResult dmnr) { r = processEvents( events, dmrem, result, node ); return new EvaluatorResultImpl( dtr, r.hasErrors ? ResultType.FAILURE : ResultType.SUCCESS ); } finally { - DMNRuntimeEventManagerUtils.fireAfterEvaluateDecisionTable( dmrem, node.getName(), dt.getName(), dtNodeId, result, (r != null ? r.matchedRules : null), (r != null ? r.fired : null) ); + DMNRuntimeEventManagerUtils.fireAfterEvaluateDecisionTable( dmrem, node.getName(), dt.getName(), dtNodeId, result, + (r != null ? r.matchedRules : null), + (r != null ? r.fired : null), + (r != null ? r.matchedIds : null), + (r != null ? r.firedIds : null)); } } @@ -112,8 +116,10 @@ public static EventResults processEvents(List events, DMNRuntimeEvent for ( FEELEvent e : events ) { if ( e instanceof DecisionTableRulesMatchedEvent ) { r.matchedRules = ((DecisionTableRulesMatchedEvent) e).getMatches(); + r.matchedIds = ((DecisionTableRulesMatchedEvent) e).getMatchesIds(); } else if ( e instanceof DecisionTableRulesSelectedEvent ) { r.fired = ((DecisionTableRulesSelectedEvent) e).getFired(); + r.firedIds = ((DecisionTableRulesSelectedEvent) e).getFiredIds(); } else if ( e.getSeverity() == FEELEvent.Severity.ERROR ) { MsgUtil.reportMessage( logger, DMNMessage.Severity.ERROR, @@ -143,6 +149,8 @@ public static class EventResults { public boolean hasErrors = false; public List matchedRules; public List fired; + public List matchedIds; + public List firedIds; } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java index 57b4bc8f12c..a4e384da787 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java @@ -678,7 +678,7 @@ protected DMNExpressionEvaluator compileDecisionTable(DMNCompilerContext ctx, DM java.util.List rules = new ArrayList<>(); index = 0; for ( DecisionRule dr : dt.getRule() ) { - DTDecisionRule rule = new DTDecisionRule( index ); + DTDecisionRule rule = new DTDecisionRule( index, dr.getId() ); for ( int i = 0; i < dr.getInputEntry().size(); i++ ) { UnaryTests ut = dr.getInputEntry().get(i); final java.util.List tests; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java index cbffc8b5c8e..33342770490 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java @@ -111,7 +111,10 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager eventManager, DMNResult d } finally { evalCtx.exitFrame(); DMNRuntimeEventManagerUtils.fireAfterEvaluateDecisionTable(eventManager, node.getName(), decisionTableName, decisionTableId, dmnResult, - (eventResults != null ? eventResults.matchedRules : null), (eventResults != null ? eventResults.fired : null)); + (eventResults != null ? eventResults.matchedRules : null), + (eventResults != null ? eventResults.fired : null), + (eventResults != null ? eventResults.matchedIds : null), + (eventResults != null ? eventResults.firedIds : null)); } } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/Results.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/Results.java index ec7de3836cc..ca42e119aec 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/Results.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/Results.java @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -29,9 +29,9 @@ import org.drools.model.functions.Function1; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.feel.lang.EvaluationContext; +import org.kie.dmn.feel.runtime.decisiontables.DTDecisionRule; import org.kie.dmn.feel.runtime.decisiontables.DecisionTable; import org.kie.dmn.feel.runtime.decisiontables.HitPolicy; -import org.kie.dmn.feel.runtime.decisiontables.Indexed; import org.kie.dmn.feel.runtime.events.DecisionTableRulesMatchedEvent; import org.kie.dmn.feel.runtime.events.HitPolicyViolationEvent; @@ -49,7 +49,8 @@ static class Items { public void addResult(ResultObject resultObject) { resultGroupedByRow - .computeIfAbsent(resultObject.row, i -> new ArrayList<>(1)) // 10 (the default for Java) columns output are not that usual + .computeIfAbsent(resultObject.row, i -> new ArrayList<>(1)) // 10 (the default for Java) columns + // output are not that usual .add(resultObject); } @@ -57,8 +58,8 @@ public void clearResults() { resultGroupedByRow.clear(); } - List matches() { - return indexes().map(i -> (Indexed) () -> i).collect(toList()); + List matches() { + return indexes().map(i -> new DTDecisionRule(i, null)).collect(toList()); } private Stream indexes() { @@ -147,25 +148,39 @@ public Object applyHitPolicy(EvaluationContext evaluationContext, } events.add(new HitPolicyViolationEvent( FEELEvent.Severity.WARN, - String.format("No rule matched for decision table '%s' and no default values were defined. Setting result to null.", decisionTable.getName()), + String.format("No rule matched for decision table '%s' and no default values were defined. " + + "Setting result to null.", decisionTable.getName()), decisionTable.getName(), Collections.emptyList())); } - List matchIndexes = items.matches(); - evaluationContext.notifyEvt( () -> { - List matchedIndexes = matchIndexes.stream().map( dr -> dr.getIndex() + 1 ).collect(Collectors.toList() ); - return new DecisionTableRulesMatchedEvent(FEELEvent.Severity.INFO, - String.format("Rules matched for decision table '%s': %s", decisionTable.getName(), matchIndexes), - decisionTable.getName(), - decisionTable.getName(), - matchedIndexes ); - } + List matchingDecisionRules = items.matches(); + evaluationContext.notifyEvt(() -> { + List matches = new ArrayList<>(); + List matchesId = new ArrayList<>(); + matchingDecisionRules.forEach(dr -> { + matches.add(dr.getIndex() + 1); + if (dr.getId() != null && !dr.getId().isEmpty()) { + matchesId.add(dr.getId()); + } + }); + return new DecisionTableRulesMatchedEvent(FEELEvent.Severity.INFO, + String.format("Rules matched for " + + "decision " + + "table '%s': " + + "%s", + decisionTable.getName(), matchingDecisionRules), + decisionTable.getName(), + decisionTable.getName(), + matches, + matchesId); + } ); List resultObjects = items.evaluateResults(evaluationContext); - Map errorMessages = checkResults(decisionTable.getOutputs(), evaluationContext, matchIndexes, resultObjects ); + Map errorMessages = checkResults(decisionTable.getOutputs(), evaluationContext, matchingDecisionRules + , resultObjects); if (!errorMessages.isEmpty()) { List offending = new ArrayList<>(errorMessages.keySet()); events.add(new HitPolicyViolationEvent( @@ -178,6 +193,6 @@ public Object applyHitPolicy(EvaluationContext evaluationContext, return null; } - return hitPolicy.getDti().dti(evaluationContext, decisionTable, matchIndexes, resultObjects); + return hitPolicy.getDti().dti(evaluationContext, decisionTable, matchingDecisionRules, resultObjects); } } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateDecisionTableEventImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateDecisionTableEventImpl.java index edfb392bc06..76d80fccfbe 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateDecisionTableEventImpl.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateDecisionTableEventImpl.java @@ -33,14 +33,18 @@ public class AfterEvaluateDecisionTableEventImpl private final DMNResult result; private final List matches; private final List fired; + private final List matchesIds; + private final List firedIds; - public AfterEvaluateDecisionTableEventImpl(String nodeName, String dtName, String dtId, DMNResult result, List matches, List fired) { + public AfterEvaluateDecisionTableEventImpl(String nodeName, String dtName, String dtId, DMNResult result, List matches, List fired, List matchesIds, List firedIds) { this.nodeName = nodeName; this.dtName = dtName; this.dtId = dtId; this.result = result; this.matches = matches; this.fired = fired; + this.matchesIds = matchesIds; + this.firedIds = firedIds; } @Override @@ -73,9 +77,18 @@ public List getSelected() { return fired == null ? Collections.emptyList() : fired; } + @Override + public List getMatchesIds() { + return matchesIds == null ? Collections.emptyList() : matchesIds; + } + + @Override + public List getSelectedIds() {return firedIds == null ? Collections.emptyList() : firedIds; + } + @Override public String toString() { - return "AfterEvaluateDecisionTableEvent{ nodeName='"+nodeName+"' decisionTableName='" + dtName + "' matches=" + getMatches() + " fired=" + getSelected() + " }"; + return "AfterEvaluateDecisionTableEvent{ nodeName='"+nodeName+"' decisionTableName='" + dtName + "' matches=" + getMatches() + " fired=" + getSelected() + "' matchesIds=" + getMatchesIds() + " firedIds=" + getSelectedIds() + " }"; } } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java index d4a65088c76..6469590ca80 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java @@ -103,9 +103,9 @@ public static void fireBeforeEvaluateDecisionTable( DMNRuntimeEventManager event } } - public static void fireAfterEvaluateDecisionTable( DMNRuntimeEventManager eventManager, String nodeName, String dtName, String dtId, DMNResult result, List matches, List fired ) { + public static void fireAfterEvaluateDecisionTable( DMNRuntimeEventManager eventManager, String nodeName, String dtName, String dtId, DMNResult result, List matches, List fired, List matchedIds, List firedIds ) { if( eventManager.hasListeners() ) { - AfterEvaluateDecisionTableEvent event = new AfterEvaluateDecisionTableEventImpl(nodeName, dtName, dtId, result, matches, fired); + AfterEvaluateDecisionTableEvent event = new AfterEvaluateDecisionTableEventImpl(nodeName, dtName, dtId, result, matches, fired, matchedIds, firedIds); notifyListeners(eventManager, l -> l.afterEvaluateDecisionTable(event)); } } diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java index d89ff7ef4ca..5f245869683 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java @@ -42,6 +42,7 @@ import org.kie.dmn.api.core.ast.ItemDefNode; import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; +import org.kie.dmn.api.core.event.AfterEvaluateDecisionTableEvent; import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.core.api.DMNFactory; import org.kie.dmn.core.api.event.DefaultDMNRuntimeEventListener; @@ -384,26 +385,36 @@ void typeConstraintsChecks(boolean useExecModelCompiler) { @ParameterizedTest @MethodSource("params") - void conditionalIfCheck(boolean useExecModelCompiler) { + void evaluationHitIdsCheck(boolean useExecModelCompiler) { init(useExecModelCompiler); final String ifElementId = "_3C702CE4-E5A0-4B6F-905D-C2621FFFA387"; final String thenElementId = "_6481FF12-61B5-451C-B775-4143D9B6CD6B"; final String elseElementId = "_2CD02CB2-6B56-45C4-B461-405E89D45633"; + final String ruleId0 = "_1578BD9E-2BF9-4BFC-8956-1A736959C937"; + final String ruleId1 = "_31CD7AA3-A806-4E7E-B512-821F82043620"; + final String ruleId3 = "_2545E1A8-93D3-4C8A-A0ED-8AD8B10A58F9"; + final String ruleId4 = "_510A50DA-D5A4-4F06-B0BE-7F8F2AA83740"; final DMNRuntime runtime = DMNRuntimeUtil.createRuntime("valid_models/DMNv1_5/RiskScore_Simple.dmn", this.getClass() ); - final List afterEvaluateConditionalEvents = new ArrayList<>(); - final List afterConditionalEvaluationEvents = new ArrayList<>(); + final List evaluateConditionalIds = new ArrayList<>(); + final List conditionalEvaluationIds = new ArrayList<>(); + final List executedRuleIds = new ArrayList<>(); runtime.addListener(new DefaultDMNRuntimeEventListener() { + @Override + public void afterConditionalEvaluation(AfterConditionalEvaluationEvent event) { + conditionalEvaluationIds.add(event.getExecutedId()); + } + @Override public void afterEvaluateConditional(AfterEvaluateConditionalEvent event) { - afterEvaluateConditionalEvents.add(event); + evaluateConditionalIds.add(event.getExecutedId()); } @Override - public void afterConditionalEvaluation(AfterConditionalEvaluationEvent event) { - afterConditionalEvaluationEvents.add(event); + public void afterEvaluateDecisionTable(AfterEvaluateDecisionTableEvent event) { + executedRuleIds.addAll(event.getSelectedIds()); } }); @@ -419,20 +430,23 @@ public void afterConditionalEvaluation(AfterConditionalEvaluationEvent event) { final DMNResult dmnResult1 = runtime.evaluateAll( dmnModel, ctx1 ); assertThat(dmnResult1.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnResult1.getMessages())).isFalse(); assertThat( dmnResult1.getContext().get( "Risk Score" )).isEqualTo(BigDecimal.valueOf(50)); - assertThat(afterEvaluateConditionalEvents).hasSize(1).allMatch(event -> event.getExecutedId().equals(ifElementId)); - assertThat(afterConditionalEvaluationEvents).hasSize(1).allMatch(event -> event.getExecutedId().equals(elseElementId)); + assertThat(evaluateConditionalIds).hasSize(1).allMatch(id -> id.equals(ifElementId)); + assertThat(conditionalEvaluationIds).hasSize(1).allMatch(id -> id.equals(elseElementId)); + assertThat(executedRuleIds).hasSize(2).contains(ruleId0, ruleId3); // - afterEvaluateConditionalEvents.clear(); - afterConditionalEvaluationEvents.clear(); + evaluateConditionalIds.clear(); + conditionalEvaluationIds.clear(); + executedRuleIds.clear(); final DMNContext ctx2 = runtime.newContext(); ctx2.set("Credit Score", "Excellent"); ctx2.set("DTI", 10); final DMNResult dmnResult2 = runtime.evaluateAll( dmnModel, ctx2 ); assertThat(dmnResult2.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnResult1.getMessages())).isFalse(); assertThat( dmnResult2.getContext().get( "Risk Score" )).isEqualTo(BigDecimal.valueOf(20)); - assertThat(afterEvaluateConditionalEvents).hasSize(1).allMatch(event -> event.getExecutedId().equals(ifElementId)); - assertThat(afterConditionalEvaluationEvents).hasSize(1).allMatch(event -> event.getExecutedId().equals(thenElementId)); + assertThat(evaluateConditionalIds).hasSize(1).allMatch(id -> id.equals(ifElementId)); + assertThat(conditionalEvaluationIds).hasSize(1).allMatch(id -> id.equals(thenElementId)); + assertThat(executedRuleIds).hasSize(2).contains(ruleId1, ruleId4); } @ParameterizedTest diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DTDecisionRule.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DTDecisionRule.java index dd08d9f8314..1576c789153 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DTDecisionRule.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DTDecisionRule.java @@ -52,11 +52,13 @@ The class DecisionRule is used to model the rules in a decision table (see 8.2 N */ public class DTDecisionRule implements Indexed { private int index; + private String id; private List inputEntry; private List outputEntry; - public DTDecisionRule(int index) { + public DTDecisionRule(int index, String id) { this.index = index; + this.id = id; } /** @@ -86,4 +88,8 @@ public List getOutputEntry() { public int getIndex() { return index; } + + public String getId() { + return id; + } } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java index 362e1100873..27374bcb428 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java @@ -257,12 +257,20 @@ private List findMatches(EvaluationContext ctx, Object[] params) } } ctx.notifyEvt( () -> { - List matches = matchingDecisionRules.stream().map( dr -> dr.getIndex() + 1 ).collect( Collectors.toList() ); + List matches = new ArrayList<>(); + List matchesId = new ArrayList<>(); + matchingDecisionRules.forEach(dr -> { + matches.add( dr.getIndex() + 1 ); + if (dr.getId() != null && !dr.getId().isEmpty()) { + matchesId.add(dr.getId()); + } + }); return new DecisionTableRulesMatchedEvent(FEELEvent.Severity.INFO, - "Rules matched for decision table '" + getName() + "': " + matches.toString(), + "Rules matched for decision table '" + getName() + "': " + matches, getName(), getName(), - matches ); + matches, + matchesId); } ); return matchingDecisionRules; diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/HitPolicy.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/HitPolicy.java index 21acca05f1c..53e5f92c0f3 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/HitPolicy.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/HitPolicy.java @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -43,28 +43,29 @@ import static java.util.stream.IntStream.range; public enum HitPolicy { - UNIQUE( "U", "UNIQUE", HitPolicy::unique, null ), - FIRST( "F", "FIRST", HitPolicy::first, null ), - PRIORITY( "P", "PRIORITY", HitPolicy::priority, null ), - ANY( "A", "ANY", HitPolicy::any, null ), - COLLECT( "C", "COLLECT", HitPolicy::ruleOrder, Collections.EMPTY_LIST ), // Collect – return a list of the outputs in arbitrary order - COLLECT_SUM( "C+", "COLLECT SUM", HitPolicy::sumCollect, null ), - COLLECT_COUNT( "C#", "COLLECT COUNT", HitPolicy::countCollect, BigDecimal.ZERO ), - COLLECT_MIN( "C<", "COLLECT MIN", HitPolicy::minCollect, null ), - COLLECT_MAX( "C>", "COLLECT MAX", HitPolicy::maxCollect, null ), - RULE_ORDER( "R", "RULE ORDER", HitPolicy::ruleOrder, null ), - OUTPUT_ORDER( "O", "OUTPUT ORDER", HitPolicy::outputOrder, null ); - - private final String shortName; - private final String longName; + UNIQUE("U", "UNIQUE", HitPolicy::unique, null), + FIRST("F", "FIRST", HitPolicy::first, null), + PRIORITY("P", "PRIORITY", HitPolicy::priority, null), + ANY("A", "ANY", HitPolicy::any, null), + COLLECT("C", "COLLECT", HitPolicy::ruleOrder, Collections.EMPTY_LIST), // Collect – return a list of the + // outputs in arbitrary order + COLLECT_SUM("C+", "COLLECT SUM", HitPolicy::sumCollect, null), + COLLECT_COUNT("C#", "COLLECT COUNT", HitPolicy::countCollect, BigDecimal.ZERO), + COLLECT_MIN("C<", "COLLECT MIN", HitPolicy::minCollect, null), + COLLECT_MAX("C>", "COLLECT MAX", HitPolicy::maxCollect, null), + RULE_ORDER("R", "RULE ORDER", HitPolicy::ruleOrder, null), + OUTPUT_ORDER("O", "OUTPUT ORDER", HitPolicy::outputOrder, null); + + private final String shortName; + private final String longName; private final HitPolicyDTI dti; - private final Object defaultValue; + private final Object defaultValue; HitPolicy(final String shortName, final String longName) { - this( shortName, longName, HitPolicy::notImplemented, null ); + this(shortName, longName, HitPolicy::notImplemented, null); } - HitPolicy(final String shortName, final String longName, final HitPolicyDTI dti, Object defaultValue ) { + HitPolicy(final String shortName, final String longName, final HitPolicyDTI dti, Object defaultValue) { this.shortName = shortName; this.longName = longName; this.dti = dti; @@ -83,16 +84,18 @@ public HitPolicyDTI getDti() { return dti; } - public Object getDefaultValue() { return defaultValue; } + public Object getDefaultValue() { + return defaultValue; + } public static HitPolicy fromString(String policy) { policy = policy.toUpperCase(); - for ( HitPolicy c : HitPolicy.values() ) { - if ( c.shortName.equals( policy ) || c.longName.equals( policy ) ) { + for (HitPolicy c : HitPolicy.values()) { + if (c.shortName.equals(policy) || c.longName.equals(policy)) { return c; } } - throw new IllegalArgumentException( "Unknown hit policy: " + policy ); + throw new IllegalArgumentException("Unknown hit policy: " + policy); } /* --------------------------------------- @@ -100,19 +103,20 @@ public static HitPolicy fromString(String policy) { --------------------------------------- */ @FunctionalInterface public interface HitPolicyDTI { + Object dti( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results); } public static Object notImplemented( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - throw new RuntimeException( "Not implemented" ); + throw new RuntimeException("Not implemented"); } /** @@ -121,57 +125,40 @@ public static Object notImplemented( public static Object unique( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - if ( matches.size() > 1 ) { - ctx.notifyEvt( () -> { - List ruleMatches = matches.stream().map( m -> m.getIndex() + 1 ).collect( toList() ); - return new HitPolicyViolationEvent( - FEELEvent.Severity.ERROR, - "UNIQUE hit policy decision tables can only have one matching rule. " + - "Multiple matches found for decision table '" + dt.getName() + "'. Matched rules: " + ruleMatches, - dt.getName(), - ruleMatches ); - } + if (matches.size() > 1) { + ctx.notifyEvt(() -> { + List ruleMatches = matches.stream().map(m -> m.getIndex() + 1).collect(toList()); + return new HitPolicyViolationEvent( + FEELEvent.Severity.ERROR, + "UNIQUE hit policy decision tables can only have one matching rule. " + + "Multiple matches found for decision table '" + dt.getName() + "'. " + + "Matched rules: " + ruleMatches, + dt.getName(), + ruleMatches); + } ); return null; } - if ( matches.size() == 1 ) { - ctx.notifyEvt( () -> { - int index = matches.get( 0 ).getIndex() + 1; - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rule fired for decision table '" + dt.getName() + "': " + index, - dt.getName(), - dt.getName(), - Collections.singletonList( index ) ); - } - ); - return results.get( 0 ); + if (matches.size() == 1) { + notifyDecisionTableRulesSelectedEvent(ctx, dt, matches); + return results.get(0); } return null; } /** - * First – return the first match in rule order + * First – return the first match in rule order */ public static Object first( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - if ( matches.size() >= 1 ) { - ctx.notifyEvt( () -> { - int index = matches.get( 0 ).getIndex() + 1; - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rule fired for decision table '" + dt.getName() + "': " + index, - dt.getName(), - dt.getName(), - Collections.singletonList( index ) ); - } - ); - return results.get( 0 ); + if (!matches.isEmpty()) { + notifyDecisionTableRulesSelectedEvent(ctx, dt, matches); + return results.get(0); } return null; } @@ -182,174 +169,87 @@ public static Object first( public static Object any( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - if ( matches.size() >= 1 ) { + if (!matches.isEmpty()) { long distinctOutputEntry = results.stream() .distinct() .count(); - if ( distinctOutputEntry > 1 ) { - ctx.notifyEvt( () -> { - List ruleMatches = matches.stream().map( m -> m.getIndex() + 1 ).collect( toList() ); - return new HitPolicyViolationEvent( - FEELEvent.Severity.ERROR, - "'Multiple rules can match, but they [must] all have the same output '" + dt.getName() + "'. Matched rules: " + ruleMatches, - dt.getName(), - ruleMatches ); - } + if (distinctOutputEntry > 1) { + ctx.notifyEvt(() -> { + List ruleMatches = + matches.stream().map(m -> m.getIndex() + 1).collect(toList()); + return new HitPolicyViolationEvent( + FEELEvent.Severity.ERROR, + "'Multiple rules can match, but they [must] all have the same output '" + dt.getName() + "'. Matched rules: " + ruleMatches, + dt.getName(), + ruleMatches); + } ); return null; } - - ctx.notifyEvt( () -> { - int index = matches.get( 0 ).getIndex() + 1; - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rule fired for decision table '" + dt.getName() + "': " + index, - dt.getName(), - dt.getName(), - Collections.singletonList( index ) ); - } - ); - return results.get( 0 ); + notifyDecisionTableRulesSelectedEvent(ctx, dt, matches); + return results.get(0); } return null; } /** - * Priority – multiple rules can match, with different outputs. The output that comes first in the supplied output values list is returned + * Priority – multiple rules can match, with different outputs. The output that comes first in the supplied + * output values list is returned */ public static Object priority( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - if ( matches.isEmpty() ) { + if (matches.isEmpty()) { return null; } - List> pairs = sortPairs( ctx, dt, matches, results ); - ctx.notifyEvt( () -> { - List indexes = Collections.singletonList( pairs.get( 0 ).getLeft().getIndex() + 1 ); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); - - return pairs.get( 0 ).getRight(); + List> pairs = sortPairs(ctx, dt, matches, results); + int index = pairs.get(0).getLeft().getIndex() + 1; + String id = pairs.get(0).getLeft().getId(); + notifyDecisionTableRulesSelectedEvent(ctx, dt, index, id); + return pairs.get(0).getRight(); } /** - * Output order – return a list of outputs in the order of the output values list + * Output order – return a list of outputs in the order of the output values list */ public static Object outputOrder( EvaluationContext ctx, DecisionTable dt, - List matches, - List results ) { - if ( matches.isEmpty() ) { + List matches, + List results) { + if (matches.isEmpty()) { return null; } - List> pairs = sortPairs( ctx, dt, matches, results ); - ctx.notifyEvt( () -> { - List indexes = pairs.stream().map( p -> p.getLeft().getIndex() + 1 ).collect( toList() ); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); - - return pairs.stream().map( p -> p.getRight() ).collect( Collectors.toList() ); - } - - private static List> sortPairs( EvaluationContext ctx, DecisionTable dt, List matches, List results) { - List> pairs = new ArrayList<>( ); - for( int i = 0; i < matches.size(); i++ ) { - pairs.add( new Pair<>( matches.get( i ), results.get( i ) ) ); - } - - if ( dt.getOutputs().size() == 1 && !dt.getOutputs().get( 0 ).getOutputValues().isEmpty() ) { - // single output, just sort the results - List outs = dt.getOutputs().get( 0 ).getOutputValues(); - pairs.sort( (r1, r2) -> { - return sortByOutputsOrder( ctx, outs, r1.getRight(), r2.getRight() ); - } ); - } else if ( dt.getOutputs().size() > 1 ) { - // multiple outputs, collect the ones that have values listed - List priorities = dt.getOutputs().stream().filter( o -> !o.getOutputValues().isEmpty() ).collect( toList() ); - pairs.sort( (r1, r2) -> { - Map m1 = (Map) r1.getRight(); - Map m2 = (Map) r2.getRight(); - for ( DecisionTable.OutputClause oc : priorities ) { - int o = sortByOutputsOrder( ctx, oc.getOutputValues(), m1.get( oc.getName() ), m2.get( oc.getName() ) ); - if ( o != 0 ) { - return o; - } - } - // unable to sort, so keep order - return 0; - } ); - } - return pairs; - } - - private static int sortByOutputsOrder(EvaluationContext ctx, List outs, Object r1, Object r2) { - boolean r1found = false; - boolean r2found = false; - for( int index = 0; index < outs.size() && !r1found && !r2found; index++ ) { - UnaryTest ut = outs.get( index ); - if( ut.apply( ctx, r1 ) ) { - r1found = true; - } - if( ut.apply( ctx, r2 ) ) { - r2found = true; - } + List> pairs = sortPairs(ctx, dt, matches, results); + int index = pairs.get(0).getLeft().getIndex() + 1; + String id = pairs.get(0).getLeft().getId(); + notifyDecisionTableRulesSelectedEvent(ctx, dt, index, id); - } - if ( r1found && r2found ) { - return 0; - } else if ( r1found ) { - return -1; - } else if ( r2found ) { - return 1; - } else { - return 0; - } + return pairs.stream().map(Pair::getRight).collect(Collectors.toList()); } /** * Rule order – return a list of outputs in rule order - * Collect – return a list of the outputs in arbitrary order + * Collect – return a list of the outputs in arbitrary order */ public static Object ruleOrder( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - if ( matches.isEmpty() ) { + if (matches.isEmpty()) { return null; } - ctx.notifyEvt( () -> { - List indexes = matches.stream().map( m -> m.getIndex() + 1 ).collect( toList() ); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); + notifyDecisionTableRulesSelectedEventWithList(ctx, dt, matches); return results; } public static Collector singleValueOrContext(List outputs) { - return new SingleValueOrContextCollector<>( outputs.stream().map( DecisionTable.OutputClause::getName ).collect( toList() ) ); + return new SingleValueOrContextCollector<>(outputs.stream().map(DecisionTable.OutputClause::getName).collect(toList())); } public static Object generalizedCollect( @@ -358,16 +258,17 @@ public static Object generalizedCollect( List results, Function, Object> resultCollector) { final List> raw; - final List names = dt.getOutputs().stream().map( o -> o.getName() != null ? o.getName() : dt.getName() ).collect( toList() ); - if ( names.size() > 1 ) { + final List names = + dt.getOutputs().stream().map(o -> o.getName() != null ? o.getName() : dt.getName()).collect(toList()); + if (names.size() > 1) { raw = (List>) results; } else { - raw = results.stream().map( (Object r) -> Collections.singletonMap( names.get( 0 ), r ) ).collect( toList() ); + raw = results.stream().map((Object r) -> Collections.singletonMap(names.get(0), r)).collect(toList()); } - return range( 0, names.size() ) - .mapToObj( index -> names.get( index ) ) - .map( name -> resultCollector.apply( raw.stream().map( r -> r.get( name ) ) ) ) - .collect( singleValueOrContext( dt.getOutputs() ) ); + return range(0, names.size()) + .mapToObj(index -> names.get(index)) + .map(name -> resultCollector.apply(raw.stream().map(r -> r.get(name)))) + .collect(singleValueOrContext(dt.getOutputs())); } /** @@ -376,23 +277,14 @@ public static Object generalizedCollect( public static Object countCollect( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - ctx.notifyEvt( () -> { - List indexes = matches.stream().map( m -> m.getIndex() + 1 ).collect( toList() ); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); + notifyDecisionTableRulesSelectedEventWithList(ctx, dt, matches); return generalizedCollect( ctx, dt, results, - x -> new BigDecimal( x.collect( toSet() ).size() ) ); + x -> new BigDecimal(x.collect(toSet()).size())); } /** @@ -401,24 +293,14 @@ public static Object countCollect( public static Object minCollect( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { Object result = generalizedCollect( ctx, dt, results, - x -> x.map( y -> (Comparable) y ).collect( minBy( Comparator.naturalOrder() ) ).orElse( null ) ); - ctx.notifyEvt( () -> { - int resultIdx = results.indexOf( result ); - List indexes = resultIdx >= 0 ? Collections.singletonList( matches.get( resultIdx ).getIndex() + 1 ) : Collections.emptyList(); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); + x -> x.map(y -> (Comparable) y).collect(minBy(Comparator.naturalOrder())).orElse(null)); + notifyDecisionTableRulesSelectedEventByResultIdx(ctx, dt, matches, results, result); return result; } @@ -428,57 +310,159 @@ public static Object minCollect( public static Object maxCollect( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { Object result = generalizedCollect( ctx, dt, results, - x -> x.map( y -> (Comparable) y ).collect( maxBy( Comparator.naturalOrder() ) ).orElse( null ) ); - ctx.notifyEvt( () -> { - int resultIdx = results.indexOf( result ); - List indexes = resultIdx >= 0 ? Collections.singletonList( matches.get( resultIdx ).getIndex() + 1 ) : Collections.emptyList(); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); + x -> x.map(y -> (Comparable) y).collect(maxBy(Comparator.naturalOrder())).orElse(null)); + notifyDecisionTableRulesSelectedEventByResultIdx(ctx, dt, matches, results, result); return result; } /** - * C+ – return the sum of the outputs + * C+ – return the sum of the outputs */ public static Object sumCollect( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - ctx.notifyEvt( () -> { - List indexes = matches.stream().map( m -> m.getIndex() + 1 ).collect( toList() ); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); + notifyDecisionTableRulesSelectedEventWithList(ctx, dt, matches); return generalizedCollect( ctx, dt, results, - x -> x.reduce( BigDecimal.ZERO, (a, b) -> { - if ( !(a instanceof Number && b instanceof Number) ) { + x -> x.reduce(BigDecimal.ZERO, (a, b) -> { + if (!(a instanceof Number && b instanceof Number)) { return null; } else { - BigDecimal aB = new BigDecimal( a.toString() ); - BigDecimal bB = new BigDecimal( b.toString() ); - return aB.add( bB ); + BigDecimal aB = new BigDecimal(a.toString()); + BigDecimal bB = new BigDecimal(b.toString()); + return aB.add(bB); } - } ) ); + })); + } + + private static void notifyDecisionTableRulesSelectedEventByResultIdx(EvaluationContext ctx, + DecisionTable dt, + List matches, + List results, + Object result) { + int resultIdx = results.indexOf(result); + List indexes = resultIdx >= 0 ? + Collections.singletonList(matches.get(resultIdx).getIndex() + 1) : + Collections.emptyList(); + List matchesId = resultIdx >= 0 ? + Collections.singletonList(matches.get(resultIdx).getId() + 1) : + Collections.emptyList(); + notifyDecisionTableRulesSelectedEvent(ctx, dt, indexes, matchesId); + } + + private static void notifyDecisionTableRulesSelectedEventWithList(EvaluationContext ctx, + DecisionTable dt, + List matches) { + List indexes = new ArrayList<>(); + List matchesId = new ArrayList<>(); + matches.forEach(dr -> { + indexes.add(dr.getIndex() + 1); + if (dr.getId() != null && !dr.getId().isEmpty()) { + matchesId.add(dr.getId()); + } + }); + notifyDecisionTableRulesSelectedEvent(ctx, dt, indexes, matchesId); + } + + private static void notifyDecisionTableRulesSelectedEvent(EvaluationContext ctx, + DecisionTable dt, + List matches) { + int index = matches.get(0).getIndex() + 1; + String id = matches.get(0).getId(); + notifyDecisionTableRulesSelectedEvent(ctx, dt, index, id); + } + + private static void notifyDecisionTableRulesSelectedEvent(EvaluationContext ctx, + DecisionTable dt, + int index, + String id) { + ctx.notifyEvt(() -> new DecisionTableRulesSelectedEvent( + FEELEvent.Severity.INFO, + "Rule fired for decision table '" + dt.getName() + "': " + index, + dt.getName(), + dt.getName(), + Collections.singletonList(index), + Collections.singletonList(id)) + ); + } + + private static void notifyDecisionTableRulesSelectedEvent(EvaluationContext ctx, + DecisionTable dt, + List indexes, + List matchesId) { + ctx.notifyEvt(() -> new DecisionTableRulesSelectedEvent( + FEELEvent.Severity.INFO, + "Rules fired for decision table '" + dt.getName() + "': " + indexes, + dt.getName(), + dt.getName(), + indexes, + matchesId) + ); + } + + private static List> sortPairs(EvaluationContext ctx, DecisionTable dt, + List matches, List results) { + List> pairs = new ArrayList<>(); + for (int i = 0; i < matches.size(); i++) { + pairs.add(new Pair<>(matches.get(i), results.get(i))); + } + + if (dt.getOutputs().size() == 1 && !dt.getOutputs().get(0).getOutputValues().isEmpty()) { + // single output, just sort the results + List outs = dt.getOutputs().get(0).getOutputValues(); + pairs.sort((r1, r2) -> { + return sortByOutputsOrder(ctx, outs, r1.getRight(), r2.getRight()); + }); + } else if (dt.getOutputs().size() > 1) { + // multiple outputs, collect the ones that have values listed + List priorities = + dt.getOutputs().stream().filter(o -> !o.getOutputValues().isEmpty()).collect(toList()); + pairs.sort((r1, r2) -> { + Map m1 = (Map) r1.getRight(); + Map m2 = (Map) r2.getRight(); + for (DecisionTable.OutputClause oc : priorities) { + int o = sortByOutputsOrder(ctx, oc.getOutputValues(), m1.get(oc.getName()), m2.get(oc.getName())); + if (o != 0) { + return o; + } + } + // unable to sort, so keep order + return 0; + }); + } + return pairs; + } + + private static int sortByOutputsOrder(EvaluationContext ctx, List outs, Object r1, Object r2) { + boolean r1found = false; + boolean r2found = false; + for (int index = 0; index < outs.size() && !r1found && !r2found; index++) { + UnaryTest ut = outs.get(index); + if (ut.apply(ctx, r1)) { + r1found = true; + } + if (ut.apply(ctx, r2)) { + r2found = true; + } + } + if (r1found && r2found) { + return 0; + } else if (r1found) { + return -1; + } else if (r2found) { + return 1; + } else { + return 0; + } } } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesMatchedEvent.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesMatchedEvent.java index 60d4ee04f02..45d1dad350f 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesMatchedEvent.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesMatchedEvent.java @@ -32,12 +32,14 @@ public class DecisionTableRulesMatchedEvent private final String nodeName; private final String dtName; private final List matches; + private final List matchesIds; - public DecisionTableRulesMatchedEvent(Severity severity, String msg, String nodeName, String dtName, List matches) { + public DecisionTableRulesMatchedEvent(Severity severity, String msg, String nodeName, String dtName, List matches, List matchesIds) { super( severity, msg, null ); this.nodeName = nodeName; this.dtName = dtName; this.matches = matches; + this.matchesIds = matchesIds; } public String getNodeName() { @@ -52,6 +54,10 @@ public List getMatches() { return matches; } + public List getMatchesIds() { + return matchesIds; + } + @Override public String toString() { return "DecisionTableRulesMatchedEvent{" + @@ -60,6 +66,7 @@ public String toString() { ", nodeName='" + nodeName + '\'' + ", dtName='" + dtName + '\'' + ", matches='" + matches + '\'' + + ", matchesIds='" + matchesIds + '\'' + '}'; } } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesSelectedEvent.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesSelectedEvent.java index 4adb80d220a..c1569419833 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesSelectedEvent.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesSelectedEvent.java @@ -40,12 +40,14 @@ public class DecisionTableRulesSelectedEvent private final String nodeName; private final String dtName; private final List fired; + private final List firedIds; - public DecisionTableRulesSelectedEvent(Severity severity, String msg, String nodeName, String dtName, List fired) { + public DecisionTableRulesSelectedEvent(Severity severity, String msg, String nodeName, String dtName, List fired, List firedIds) { super( severity, msg, null ); this.nodeName = nodeName; this.dtName = dtName; this.fired = fired; + this.firedIds = firedIds; } public String getNodeName() { @@ -58,6 +60,10 @@ public List getFired() { return fired; } + public List getFiredIds() { + return firedIds; + } + @Override public String toString() { return "DecisionTableRulesMatchedEvent{" + @@ -66,6 +72,7 @@ public String toString() { ", nodeName='" + nodeName + '\'' + ", dtName='" + dtName + '\'' + ", fired='" + fired + '\'' + + ", firedIds='" + firedIds + '\'' + '}'; } } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/DecisionTableFunction.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/DecisionTableFunction.java index 80437477ada..651f334edaa 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/DecisionTableFunction.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/DecisionTableFunction.java @@ -153,7 +153,7 @@ protected List> objectToUnaryTestList(EvaluationContext ctx, Lis */ private static DTDecisionRule toDecisionRule(EvaluationContext mainCtx, FEEL embeddedFEEL, int index, List rule, int inputSize) { // TODO should be check indeed block of inputSize n inputs, followed by block of outputs. - DTDecisionRule dr = new DTDecisionRule( index ); + DTDecisionRule dr = new DTDecisionRule( index, null ); for ( int i = 0; i < rule.size(); i++ ) { Object o = rule.get( i ); if ( i < inputSize ) { diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java index 43547f15081..852ed9e2057 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java @@ -6,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - *

+ * * http://www.apache.org/licenses/LICENSE-2.0 - *

+ * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/DateFunctionTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/DateFunctionTest.java index db9ece6621b..f1462b8d79d 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/DateFunctionTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/DateFunctionTest.java @@ -32,7 +32,7 @@ class DateFunctionTest { @BeforeEach void setUp() { - dateFunction = new DateFunction(); + dateFunction = DateFunction.INSTANCE; } @Test From c978e44590224625d2cddf6a5059eb967832bcd7 Mon Sep 17 00:00:00 2001 From: Gabriele Cardosi Date: Fri, 18 Oct 2024 12:38:29 +0200 Subject: [PATCH 137/141] [incubator-kie-issues#1497] Defining NodeInstanceContainer.getSerializableNodeInstances to be used during serialization (#6116) Co-authored-by: Gabriele-Cardosi --- .../kie/api/runtime/process/NodeInstanceContainer.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/kie-api/src/main/java/org/kie/api/runtime/process/NodeInstanceContainer.java b/kie-api/src/main/java/org/kie/api/runtime/process/NodeInstanceContainer.java index f8a749bc758..c8915cc1e34 100644 --- a/kie-api/src/main/java/org/kie/api/runtime/process/NodeInstanceContainer.java +++ b/kie-api/src/main/java/org/kie/api/runtime/process/NodeInstanceContainer.java @@ -34,6 +34,16 @@ public interface NodeInstanceContainer { */ Collection getNodeInstances(); + /** + * Returns all node instances that are currently active + * within this container and are serializable + * + * @return the list of serializable node instances currently active + */ + default Collection getSerializableNodeInstances() { + return getNodeInstances(); // defaulting to getNodeInstances to avoid breaking + } + /** * Returns the node instance with the given id, or null * if the node instance cannot be found. From 3b7aa6ce2d06f43ab0e03c464e3ff879869926c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tibor=20Zim=C3=A1nyi?= Date: Tue, 22 Oct 2024 13:11:54 +0200 Subject: [PATCH 138/141] [kie-issues#1410] Fix type check for decision service input parameters. (#6133) --- .../DMNDecisionServiceFunctionDefinitionEvaluator.java | 8 ++++++-- .../core/decisionservices/DMNDecisionServicesTest.java | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java index 00c2c0f50f0..99700adc603 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java @@ -160,7 +160,7 @@ private Object performTypeCheckIfNeeded(Object param, int paramIndex) { dsFormalParameter.type, typeCheck, (rx, tx) -> MsgUtil.reportMessage(LOG, - DMNMessage.Severity.WARN, + DMNMessage.Severity.ERROR, null, resultContext, null, @@ -169,7 +169,11 @@ private Object performTypeCheckIfNeeded(Object param, int paramIndex) { dsFormalParameter.name, tx, MsgUtil.clipString(rx.toString(), 50))); - return result; + if (param != null && result == null) { + throw new IllegalArgumentException("Parameter " + param + " cannot be assigned to parameter of type " + dsFormalParameter.type + "!"); + } else { + return result; + } } @Override diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/decisionservices/DMNDecisionServicesTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/decisionservices/DMNDecisionServicesTest.java index 69be0798dd9..a98a5d1ea97 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/decisionservices/DMNDecisionServicesTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/decisionservices/DMNDecisionServicesTest.java @@ -633,8 +633,8 @@ void test20190520(boolean useExecModelCompiler) { final DMNResult dmnResult = runtime.evaluateAll(dmnModel, emptyContext); LOG.debug("{}", dmnResult); dmnResult.getDecisionResults().forEach(x -> LOG.debug("{}", x)); - assertThat(dmnResult.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnResult.getMessages())).isFalse(); - assertThat((Map) dmnResult.getDecisionResultByName("my invoke DS1").getResult()).containsEntry("outDS1", true); + assertThat(dmnResult.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnResult.getMessages())).isTrue(); + assertThat((Map) dmnResult.getDecisionResultByName("my invoke DS1").getResult()).isNull(); } @ParameterizedTest From bb48f8dc3aee2f07f6123ef9bd4c39469434b5d0 Mon Sep 17 00:00:00 2001 From: Jozef Marko Date: Wed, 23 Oct 2024 09:28:45 +0200 Subject: [PATCH 139/141] kie-issues#1541: Add testing models into kie-dmn-test-resources (#6135) * kie-issues#1541: Add testing models into kie-dmn-test-resources This PR is related to: https://github.com/apache/incubator-kie-kogito-apps/pull/2120 where we are adding new unit tests using DMN models from the drools/kie-dmn/kie-dmn-test-resources * Collections.dmn -> MultipleHitRules.dmn * Remove name attribute --- .../valid_models/DMNv1_5/MultipleHitRules.dmn | 94 +++++ .../DMNv1_5/RiskScore_Conditional.dmn | 328 ++++++++++++++++++ 2 files changed, 422 insertions(+) create mode 100644 kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/MultipleHitRules.dmn create mode 100644 kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Conditional.dmn diff --git a/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/MultipleHitRules.dmn b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/MultipleHitRules.dmn new file mode 100644 index 00000000000..b01f79264a5 --- /dev/null +++ b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/MultipleHitRules.dmn @@ -0,0 +1,94 @@ + + + + + number + + + + + + + + + + + + + Numbers + + + + + + + i + + + + + + + >0 + + + 1 + + + // Your annotations here + + + + + >1 + + + 2 + + + + + + + + >2 + + + 3 + + + + + + + + + + + + + + + 190 + + + 60 + 118 + 118 + 240 + + + + + + + + + + + + + + + + diff --git a/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Conditional.dmn b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Conditional.dmn new file mode 100644 index 00000000000..a4816f968de --- /dev/null +++ b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Conditional.dmn @@ -0,0 +1,328 @@ + + + + string + + "Asia", "Europe" + + + + string + + "Poor", "Fair", "Excellent" + + + + string + + "High", "Medium", "Low" + + + + string + + "Qualified", "Not Qualified" + + + + + + + + + + + + + + + + + + + + + + + World Region = "Asia" + + + + + + + Credit Score + + + + + DTI + + + + + + + "Poor" + + + - + + + 30 + + + // Your annotations here + + + + + "Fair" + + + - + + + 20 + + + + + + + + "Excellent" + + + - + + + 10 + + + + + + + + - + + + > 40 + + + 30 + + + + + + + + - + + + [20..40] + + + 20 + + + + + + + + - + + + < 20 + + + 10 + + + + + + + + + + + + Credit Score + + + + + DTI + + + + + + + "Poor" + + + - + + + 35 + + + // Your annotations here + + + + + "Fair" + + + - + + + 25 + + + + + + + + "Excellent" + + + - + + + 15 + + + + + + + + - + + + > 40 + + + 35 + + + + + + + + - + + + [20..40] + + + 25 + + + + + + + + - + + + < 20 + + + 15 + + + + + + + + + + + + + + + + + + + 60 + 145 + 118 + 118 + 240 + + + 120 + + + 60 + 145 + 118 + 118 + 240 + + + 190 + + + 190 + + + 232 + + + 60 + 145 + 118 + 118 + 240 + + + 60 + 145 + 118 + 118 + 240 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 9133aeeb9e0acd232e21260c2b6da716989a460e Mon Sep 17 00:00:00 2001 From: Paolo Bizzarri Date: Wed, 23 Oct 2024 10:33:48 +0200 Subject: [PATCH 140/141] [incubator-kie-drools-6136] Migrate droos test coverage module to JUnit5 - #1 (#6137) * Initial test migration * Migrated more unit tests * Migrated more unit tests * Fixed test * More tests migrated to junit5 * Fixed test --- .../test-compiler-integration/pom.xml | 21 +- .../integrationtests/AccumulateCepTest.java | 31 +- .../AccumulateConsistencyTest.java | 85 ++--- .../integrationtests/AnnotationsCepTest.java | 31 +- .../AnnotationsOnPatternTest.java | 61 ++-- .../integrationtests/AnnotationsTest.java | 46 ++- .../compiler/integrationtests/ArrayTest.java | 116 ++++--- .../compiler/integrationtests/BetaTest.java | 33 +- .../BigRuleSetCompilationTest.java | 2 +- .../integrationtests/CalendarTest.java | 26 +- .../CepEspNegativeCloudTest.java | 38 +- .../integrationtests/CepJavaTypeTest.java | 37 +- .../integrationtests/ClassLoaderTest.java | 2 +- .../integrationtests/CommandsTest.java | 26 +- .../integrationtests/ConditionLimitTest.java | 26 +- .../ConsequenceOffsetTest.java | 2 +- .../integrationtests/ConsequenceTypeTest.java | 26 +- .../integrationtests/ConstraintsTest.java | 96 +++--- .../CustomOperatorOnlyDrlTest.java | 26 +- .../integrationtests/CustomOperatorTest.java | 48 ++- .../ErrorOnInsertLogicalTest.java | 2 +- .../integrationtests/FromSharingTest.java | 31 +- .../integrationtests/ImmutableFactsTest.java | 32 +- .../integrationtests/IndexingTest.java | 197 ++++++----- .../JoinNodeRangeIndexingTest.java | 123 +++---- .../integrationtests/KieBaseIncludeTest.java | 26 +- .../integrationtests/MultiSheetsTest.java | 55 ++- .../integrationtests/PassivePatternTest.java | 26 +- .../PropertyChangeSupportTest.java | 2 +- .../PropertyReactivityTest.java | 26 +- .../integrationtests/RuleChainingTest.java | 31 +- .../integrationtests/SharingTest.java | 68 ++-- .../integrationtests/StreamsTest.java | 107 +++--- .../integrationtests/SubnetworkCEPTest.java | 26 +- .../integrationtests/SubnetworkTest.java | 86 +++-- .../integrationtests/UnexpectedLoopTest.java | 25 +- .../integrationtests/operators/AndTest.java | 26 +- .../operators/ContainsTest.java | 36 +- .../operators/EnabledTest.java | 29 +- .../operators/EqualsTest.java | 30 +- .../operators/EvalRewriteTest.java | 36 +- .../integrationtests/operators/EvalTest.java | 107 +++--- .../operators/ExistsTest.java | 61 ++-- .../operators/ForAllTest.java | 227 ++++++------ .../operators/FormulaTest.java | 31 +- .../operators/FromOnlyExecModelTest.java | 31 +- .../integrationtests/operators/FromTest.java | 155 +++++---- .../integrationtests/operators/InTest.java | 30 +- .../operators/InstanceOfTest.java | 26 +- .../operators/MatchesTest.java | 57 ++- .../integrationtests/operators/MathTest.java | 36 +- .../operators/MemberOfTest.java | 31 +- .../integrationtests/operators/NotTest.java | 46 ++- .../integrationtests/operators/OrTest.java | 91 ++--- .../operators/SoundsLikeTest.java | 51 ++- .../common/util/TestParametersUtil2.java | 324 ++++++++++++++++++ 56 files changed, 1674 insertions(+), 1429 deletions(-) create mode 100644 drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/TestParametersUtil2.java diff --git a/drools-test-coverage/test-compiler-integration/pom.xml b/drools-test-coverage/test-compiler-integration/pom.xml index 6ccf1cbdc67..f470744b644 100644 --- a/drools-test-coverage/test-compiler-integration/pom.xml +++ b/drools-test-coverage/test-compiler-integration/pom.xml @@ -101,7 +101,26 @@ xstream test - + + org.junit.vintage + junit-vintage-engine + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + org.assertj assertj-core diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateCepTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateCepTest.java index 60569200768..00f7fa2f8cc 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateCepTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateCepTest.java @@ -19,19 +19,18 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import org.drools.compiler.integrationtests.incrementalcompilation.TestUtil; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.core.impl.RuleBaseFactory; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; @@ -42,7 +41,6 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class AccumulateCepTest { public static final String TEST_MANY_SLIDING_WINDOWS_DRL = "package com.sample;\n" + @@ -72,19 +70,13 @@ public class AccumulateCepTest { "end\n" + "\n"; - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public AccumulateCepTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } - @Test - public void testAccumulatesExpireVsCancel() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulatesExpireVsCancel(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // JBRULES-3201 final String drl = "package com.sample;\n" + "\n" + @@ -134,8 +126,9 @@ public void testAccumulatesExpireVsCancel() throws Exception { } } - @Test - public void testManySlidingWindows() { + @ParameterizedTest + @MethodSource("parameters") + public void testManySlidingWindows(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("accumulate-test", kieBaseTestConfiguration, TEST_MANY_SLIDING_WINDOWS_DRL); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateConsistencyTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateConsistencyTest.java index 41eb61e5d42..ee6caa2c2e0 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateConsistencyTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateConsistencyTest.java @@ -23,14 +23,15 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.MyFact; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.runtime.KieSession; @@ -40,31 +41,25 @@ import org.kie.api.runtime.rule.Variable; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.arguments; -@RunWith(Parameterized.class) public class AccumulateConsistencyTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - private final boolean accumulateNullPropagation; - public AccumulateConsistencyTest(final KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - this.accumulateNullPropagation = accumulateNullPropagation; - } // accumulateNullPropagation is false by default in drools 7.x - @Parameterized.Parameters(name = "KieBase type={0}, accumulateNullPropagation= {1}") - public static Collection getParameters() { - Collection parameters = new ArrayList<>(); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY, false}); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY_MODEL_PATTERN, false}); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY, true}); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY_MODEL_PATTERN, true}); - return parameters; + public static Stream parameters() { + Collection parameters = new ArrayList<>(); + parameters.add(arguments(KieBaseTestConfiguration.CLOUD_IDENTITY, false)); + parameters.add(arguments(KieBaseTestConfiguration.CLOUD_IDENTITY_MODEL_PATTERN, false)); + parameters.add(arguments(KieBaseTestConfiguration.CLOUD_IDENTITY, true)); + parameters.add(arguments(KieBaseTestConfiguration.CLOUD_IDENTITY_MODEL_PATTERN, true)); + return parameters.stream(); } - @Test - public void testMinNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -93,8 +88,9 @@ public void testMinNoMatch() { } } - @Test - public void testMaxNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMaxNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -123,8 +119,9 @@ public void testMaxNoMatch() { } } - @Test - public void testAveNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testAveNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -153,8 +150,9 @@ public void testAveNoMatch() { } } - @Test - public void testSumNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testSumNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -179,8 +177,9 @@ public void testSumNoMatch() { } } - @Test - public void testCountNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testCountNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -205,8 +204,9 @@ public void testCountNoMatch() { } } - @Test - public void testMinMaxNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinMaxNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -232,8 +232,9 @@ public void testMinMaxNoMatch() { } } - @Test - public void testMinMaxMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinMaxMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -269,8 +270,9 @@ public void testMinMaxMatch() { } } - @Test - public void testMinNoMatchAccFrom() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinNoMatchAccFrom(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + @@ -300,8 +302,9 @@ public void testMinNoMatchAccFrom() { } } - @Test - public void testMinMatchUnification() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinMatchUnification(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + @@ -330,8 +333,9 @@ public void testMinMatchUnification() { } } - @Test - public void testMinNoMatchUnification() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinNoMatchUnification(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -363,8 +367,9 @@ public void testMinNoMatchUnification() { } } - @Test - public void testMinMatchUnificationQuery() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinMatchUnificationQuery(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsCepTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsCepTest.java index 6f14418494f..b52d7fb25c1 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsCepTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsCepTest.java @@ -18,37 +18,29 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.conf.MBeansOption; import org.kie.api.definition.rule.Rule; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class AnnotationsCepTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public AnnotationsCepTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } - @Test - public void testRuleAnnotation() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRuleAnnotation(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Person.class.getCanonicalName() + "; \n" + "rule X\n" + @@ -74,8 +66,9 @@ public void testRuleAnnotation() { } - @Test - public void testRuleAnnotation2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRuleAnnotation2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Person.class.getCanonicalName() + "; \n" + "rule X\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsOnPatternTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsOnPatternTest.java index af509a19d0d..691a692741b 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsOnPatternTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsOnPatternTest.java @@ -19,9 +19,9 @@ package org.drools.compiler.integrationtests; import java.util.Arrays; -import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.base.definitions.rule.impl.RuleImpl; import org.drools.base.factmodel.AnnotationDefinition; @@ -30,32 +30,24 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.definition.rule.Rule; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class AnnotationsOnPatternTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public AnnotationsOnPatternTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(false); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(false).stream(); } - @Test - public void testAnnotationWithUnknownProperty() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationWithUnknownProperty(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Outer.class.getName().replace("$", ".") + "; " + "import " + Inner.class.getName().replace("$", ".") + "; " + @@ -70,8 +62,9 @@ public void testAnnotationWithUnknownProperty() { assertThat(kieBuilder.getResults().getMessages()).hasSize(1); } - @Test - public void testAnnotationWithUnknownClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationWithUnknownClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Outer.class.getName().replace("$", ".") + "; " + @@ -85,8 +78,9 @@ public void testAnnotationWithUnknownClass() { assertThat(kieBuilder.getResults().getMessages()).hasSize(1); } - @Test - public void testAnnotationWithQualifiandClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationWithQualifiandClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Outer.class.getName().replace("$", ".") + "; " + @@ -107,8 +101,9 @@ public void testAnnotationWithQualifiandClass() { assertThat(adef).isNotNull(); } - @Test - public void testNestedAnnotations() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNestedAnnotations(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Outer.class.getName().replace("$", ".") + "; " + "import " + Inner.class.getName().replace("$", ".") + "; " + @@ -136,8 +131,9 @@ public void testNestedAnnotations() { assertThat(inner.getPropertyValue("text")).isEqualTo("world"); } - @Test - public void testNestedAnnotationsWithMultiplicity() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNestedAnnotationsWithMultiplicity(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Outer.class.getName().replace("$", ".") + "; " + "import " + Inner.class.getName().replace("$", ".") + "; " + @@ -162,8 +158,9 @@ public void testNestedAnnotationsWithMultiplicity() { assertThat(val instanceof AnnotationDefinition[]).isTrue(); } - @Test - public void testRuleAnnotations() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRuleAnnotations(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Inner.class.getName().replace("$", ".") + "; " + @@ -185,8 +182,9 @@ public void testRuleAnnotations() { assertThat(((Map) obj).get("text")).isEqualTo("a"); } - @Test - public void testTypedSimpleArrays() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testTypedSimpleArrays(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + AnnotationsTest.Simple.class.getName().replace("$", ".") + "; " + @@ -209,8 +207,9 @@ public void testTypedSimpleArrays() { assertThat(val instanceof int[]).isTrue(); } - @Test - public void testCollectAnnotationsParsingAndBuilding() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCollectAnnotationsParsingAndBuilding(KieBaseTestConfiguration kieBaseTestConfiguration) { final String packageName = "org.drools.compiler.integrationtests"; 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 0a737a950e1..267e636c286 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 @@ -24,15 +24,14 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.definition.type.FactType; @@ -43,18 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) public class AnnotationsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public AnnotationsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } public enum AnnPropEnum { @@ -97,8 +88,9 @@ public String getValue() { AnnPropEnum[] enumArrProp() default {AnnPropEnum.TWO, AnnPropEnum.THREE}; } - @Test - public void annotationTest() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void annotationTest(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test;\n " + "" + @@ -192,8 +184,9 @@ public void annotationTest() { assertThat(ann2.enumArrProp()).isEqualTo(new AnnPropEnum[]{AnnPropEnum.TWO, AnnPropEnum.THREE}); } - @Test - public void annotationErrorTest() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void annotationErrorTest(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test;\n " + "" + @@ -221,8 +214,9 @@ public void annotationErrorTest() { assertThat(kieBuilder2.getResults().getMessages()).hasSize(3); } - @Test - public void testAnnotationNameClash() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationNameClash(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test\n" + "" + "declare Annot\n" + @@ -256,8 +250,9 @@ public static class Duration { } - @Test - public void testAnnotationNameClashWithRegularClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationNameClashWithRegularClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test\n" + "import " + Duration.class.getCanonicalName() + "; " + @@ -278,8 +273,9 @@ public void testAnnotationNameClashWithRegularClass() { int[] numbers(); } - @Test - public void testAnnotationOnLHSAndMerging() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationOnLHSAndMerging(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler; " + " " + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ArrayTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ArrayTest.java index ab781ef687c..63abe7b8cc7 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ArrayTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ArrayTest.java @@ -19,39 +19,31 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Primitives; import org.drools.testcoverage.common.model.TestParam; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ArrayTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ArrayTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testEqualsOnIntArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEqualsOnIntArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler;\n" + @@ -82,8 +74,9 @@ public void testEqualsOnIntArray() { } } - @Test - public void testContainsBooleanArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsBooleanArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Boolean", false, "true")); @@ -106,8 +99,9 @@ public void testContainsBooleanArray() { } } - @Test - public void testNotContainsBooleanArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsBooleanArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler;\n" + "import " + Primitives.class.getCanonicalName() + ";\n" + @@ -145,8 +139,9 @@ public void testNotContainsBooleanArray() { } } - @Test - public void testContainsByteArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsByteArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Byte", false, "1")); final KieSession kieSession = kbase.newKieSession(); @@ -168,8 +163,9 @@ public void testContainsByteArray() { } } - @Test - public void testNotContainsByteArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsByteArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Byte", true, "1")); final KieSession kieSession = kbase.newKieSession(); @@ -191,8 +187,9 @@ public void testNotContainsByteArray() { } } - @Test - public void testContainsShortArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsShortArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Short", false, "1")); final KieSession kieSession = kbase.newKieSession(); @@ -214,8 +211,9 @@ public void testContainsShortArray() { } } - @Test - public void testNotContainsShortArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsShortArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Short", true, "1")); final KieSession kieSession = kbase.newKieSession(); @@ -237,8 +235,9 @@ public void testNotContainsShortArray() { } } - @Test - public void testContainsCharArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsCharArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Character", false, "'c'")); final KieSession kieSession = kbase.newKieSession(); @@ -260,8 +259,9 @@ public void testContainsCharArray() { } } - @Test - public void testNotContainsCharArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsCharArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Character", true, "'c'")); final KieSession kieSession = kbase.newKieSession(); @@ -283,8 +283,9 @@ public void testNotContainsCharArray() { } } - @Test - public void testContainsIntArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsIntArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Integer", false, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -306,8 +307,9 @@ public void testContainsIntArray() { } } - @Test - public void testNotContainsIntArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsIntArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Integer", true, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -329,8 +331,9 @@ public void testNotContainsIntArray() { } } - @Test - public void testContainsLongArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsLongArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Long", false, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -352,8 +355,9 @@ public void testContainsLongArray() { } } - @Test - public void testNotContainsLongArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsLongArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Long", true, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -375,8 +379,9 @@ public void testNotContainsLongArray() { } } - @Test - public void testContainsFloatArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsFloatArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Float", false, "10f")); final KieSession kieSession = kbase.newKieSession(); @@ -398,8 +403,9 @@ public void testContainsFloatArray() { } } - @Test - public void testNotContainsFloatArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsFloatArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Float", true, "10f")); final KieSession kieSession = kbase.newKieSession(); @@ -421,8 +427,9 @@ public void testNotContainsFloatArray() { } } - @Test - public void testContainsDoubleArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsDoubleArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Double", false, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -444,8 +451,9 @@ public void testContainsDoubleArray() { } } - @Test - public void testNotContainsDoubleArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsDoubleArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Double", true, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -528,8 +536,9 @@ private void testArrayContains(final KieSession kieSession, final Primitives p1, assertThat(resultsList.size()).isEqualTo(2); } - @Test - public void testPrimitiveArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testPrimitiveArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Primitives.class.getCanonicalName() + "\n" + "global java.util.List result;\n" + @@ -587,8 +596,9 @@ public void testPrimitiveArray() { } } - @Test - public void testArrayUsage() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testArrayUsage(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + TestParam.class.getCanonicalName() + "\n" + "global java.util.List list;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BetaTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BetaTest.java index a939bd41741..7e4f9cf1fc9 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BetaTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BetaTest.java @@ -19,40 +19,33 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.FirstClass; import org.drools.testcoverage.common.model.SecondClass; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class BetaTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public BetaTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testDefaultBetaConstrains() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDefaultBetaConstrains(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + FirstClass.class.getCanonicalName() + "\n" + @@ -132,8 +125,10 @@ public void testDefaultBetaConstrains() { } } - @Test(timeout = 5000) - public void testEfficientBetaNodeNetworkUpdate() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(5000) + public void testEfficientBetaNodeNetworkUpdate(KieBaseTestConfiguration kieBaseTestConfiguration) { // [JBRULES-3372] final String drl = "declare SimpleMembership\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BigRuleSetCompilationTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BigRuleSetCompilationTest.java index 21266b156cd..ff64d1a2320 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BigRuleSetCompilationTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BigRuleSetCompilationTest.java @@ -23,7 +23,7 @@ import org.drools.io.ByteArrayResource; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CalendarTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CalendarTest.java index 3130b72d5a7..c5f6d37f746 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CalendarTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CalendarTest.java @@ -20,35 +20,27 @@ import java.util.ArrayList; import java.util.Calendar; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class CalendarTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CalendarTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void test() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test(KieBaseTestConfiguration kieBaseTestConfiguration) { // BZ-1007385 final String drl = "package org.drools.compiler.integrationtests;\n" + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepEspNegativeCloudTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepEspNegativeCloudTest.java index 17f87ca5159..e5d497cebc4 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepEspNegativeCloudTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepEspNegativeCloudTest.java @@ -18,17 +18,17 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.StockTick; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; @@ -39,22 +39,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) public class CepEspNegativeCloudTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CepEspNegativeCloudTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test(timeout=10000) - public void testCloudModeExpiration() throws InstantiationException, IllegalAccessException, InterruptedException { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(10000) + public void testCloudModeExpiration(KieBaseTestConfiguration kieBaseTestConfiguration) throws InstantiationException, IllegalAccessException, InterruptedException { final String drl = "package org.drools.cloud\n" + "import " + StockTick.class.getCanonicalName() + "\n" + "declare Event\n" + @@ -105,8 +99,9 @@ public void testCloudModeExpiration() throws InstantiationException, IllegalAcce } } - @Test - public void testThrowsWhenCreatingKieBaseUsingWindowsInCloudMode() { + @ParameterizedTest + @MethodSource("parameters") + public void testThrowsWhenCreatingKieBaseUsingWindowsInCloudMode(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "declare TestEvent\n" + " @role( event )\n" + @@ -126,8 +121,9 @@ public void testThrowsWhenCreatingKieBaseUsingWindowsInCloudMode() { } } - @Test - public void testTemporalQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testTemporalQuery(KieBaseTestConfiguration kieBaseTestConfiguration) { // BZ-967441 final String drl = "package org.drools.compiler.integrationtests;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepJavaTypeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepJavaTypeTest.java index 451c5a28c19..8213c074f0a 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepJavaTypeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepJavaTypeTest.java @@ -19,15 +19,16 @@ package org.drools.compiler.integrationtests; import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; +import org.drools.testcoverage.common.util.TestParametersUtil2; import org.drools.testcoverage.common.util.TimeUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.definition.type.Expires; @@ -37,25 +38,18 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class CepJavaTypeTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CepJavaTypeTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } @Role(value = Role.Type.EVENT) public static class Event { } - @Test - public void testJavaTypeAnnotatedWithRole_WindowTime() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testJavaTypeAnnotatedWithRole_WindowTime(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "\n" + "import " + CepJavaTypeTest.Event.class.getCanonicalName() + ";\n" @@ -70,8 +64,9 @@ public void testJavaTypeAnnotatedWithRole_WindowTime() { assertThat(kieBuilder.getResults().getMessages()).isEmpty(); } - @Test - public void testJavaTypeAnnotatedWithRole_WindowLength() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testJavaTypeAnnotatedWithRole_WindowLength(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "\n" + "import " + CepJavaTypeTest.Event.class.getCanonicalName() + ";\n" @@ -104,8 +99,10 @@ public MyMessage(final String n) { public long getTs() { return ts; } } - @Test(timeout = 5000) - public void testEventWithShortExpiration() throws InterruptedException { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(5000) + public void testEventWithShortExpiration(KieBaseTestConfiguration kieBaseTestConfiguration) throws InterruptedException { // BZ-1265773 final String drl = "import " + MyMessage.class.getCanonicalName() +"\n" + "rule \"Rule A Start\"\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ClassLoaderTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ClassLoaderTest.java index cd44b685e1e..54ec8480c47 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ClassLoaderTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ClassLoaderTest.java @@ -26,7 +26,7 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; import org.drools.testcoverage.common.util.KieUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CommandsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CommandsTest.java index ad42a905458..e9c314aefc8 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CommandsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CommandsTest.java @@ -18,17 +18,16 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.command.KieCommands; @@ -36,22 +35,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class CommandsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CommandsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testSessionTimeCommands() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSessionTimeCommands(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests \n" + "import " + Cheese.class.getCanonicalName() + " \n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConditionLimitTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConditionLimitTest.java index ed6455944e2..7fba9629c95 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConditionLimitTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConditionLimitTest.java @@ -18,32 +18,23 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ConditionLimitTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ConditionLimitTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } public static class FieldObject { @@ -69,8 +60,9 @@ public void setValue(String value) { } } - @Test - public void testEvalErrorHandling() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalErrorHandling(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6856 final int INPUT_COUNT = 65; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceOffsetTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceOffsetTest.java index 3df7f6dd35b..0da5e296b9a 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceOffsetTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceOffsetTest.java @@ -20,7 +20,7 @@ import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; import org.drools.drl.ast.descr.RuleDescr; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.io.ResourceType; import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderFactory; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceTypeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceTypeTest.java index 8129a57ac28..07f0f48d1d8 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceTypeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceTypeTest.java @@ -19,35 +19,27 @@ package org.drools.compiler.integrationtests; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ConsequenceTypeTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ConsequenceTypeTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void test() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test(KieBaseTestConfiguration kieBaseTestConfiguration) { // KIE-1133 int ruleNr = 100; 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 a67fc39c7be..ca9a368903e 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 @@ -19,11 +19,11 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Message; @@ -32,32 +32,24 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ConstraintsTest { - - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ConstraintsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testExpressionConstraints1() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExpressionConstraints1(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Mailbox.FolderType.class.getCanonicalName() + ";\n" + "import " + Mailbox.class.getCanonicalName() + ";\n" + @@ -77,11 +69,12 @@ public void testExpressionConstraints1() { " then\n" + "end\n"; - testExpressionConstraints(drl); + testExpressionConstraints(kieBaseTestConfiguration, drl); } - @Test - public void testExpressionConstraints2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExpressionConstraints2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Mailbox.FolderType.class.getCanonicalName() + ";\n" + "import " + Mailbox.class.getCanonicalName() + ";\n" + @@ -106,11 +99,12 @@ public void testExpressionConstraints2() { " then\n" + "end\n"; - testExpressionConstraints(drl); + testExpressionConstraints(kieBaseTestConfiguration, drl); } - @Test - public void testExpressionConstraints3() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExpressionConstraints3(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Mailbox.FolderType.class.getCanonicalName() + ";\n" + "import " + Mailbox.class.getCanonicalName() + ";\n" + @@ -144,10 +138,10 @@ public void testExpressionConstraints3() { " then\n" + "end"; - testExpressionConstraints(drl); + testExpressionConstraints(kieBaseTestConfiguration, drl); } - private void testExpressionConstraints(final String drl) { + private void testExpressionConstraints(KieBaseTestConfiguration kieBaseTestConfiguration, final String drl) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("constraints-test", kieBaseTestConfiguration, drl); final KieSession ksession = kbase.newKieSession(); try { @@ -165,8 +159,9 @@ private void testExpressionConstraints(final String drl) { } } - @Test - public void testExpressionConstraints4() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExpressionConstraints4(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Mailbox.FolderType.class.getCanonicalName() + ";\n" + "import " + Mailbox.class.getCanonicalName() + ";\n" + @@ -196,8 +191,9 @@ public void testExpressionConstraints4() { } } - @Test - public void testDeeplyNestedCompactExpressions() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDeeplyNestedCompactExpressions(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools\n" + "rule R1\n" + " when\n" + @@ -212,8 +208,9 @@ public void testDeeplyNestedCompactExpressions() { assertThat(kieBuilder.getResults().getMessages()).isNotEmpty(); } - @Test - public void testConstraintConnectors() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testConstraintConnectors(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources("constraints-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_ConstraintConnectors.drl"); final KieSession ksession = kbase.newKieSession(); @@ -268,8 +265,9 @@ public void testConstraintConnectors() { } } - @Test - public void testConnectorsAndOperators() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testConnectorsAndOperators(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -298,8 +296,9 @@ public void testConnectorsAndOperators() { } } - @Test - public void testConstraintExpression() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testConstraintExpression(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"test\"\n" + @@ -318,8 +317,9 @@ public void testConstraintExpression() { } } - @Test - public void testMethodConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMethodConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"test\"\n" + @@ -340,8 +340,9 @@ public void testMethodConstraint() { } } - @Test - public void testDeepNestedConstraints() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDeepNestedConstraints(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -372,8 +373,9 @@ public void testDeepNestedConstraints() { } } - @Test - public void testMultiRestrictionFieldConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMultiRestrictionFieldConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources("constraints-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_MultiRestrictionFieldConstraint.drl"); final KieSession ksession = kbase.newKieSession(); @@ -438,8 +440,9 @@ public void testMultiRestrictionFieldConstraint() { } } - @Test - public void testNonBooleanConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNonBooleanConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import java.util.List\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -457,8 +460,9 @@ public void testNonBooleanConstraint() { .isNotEmpty(); } - @Test - public void testVarargConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testVarargConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-3268 final String drl = "package org.drools.compiler.test;\n" + "import " + VarargBean.class.getCanonicalName() + ";\n" + 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 5ed622236b2..d6835f92ab5 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 @@ -21,7 +21,7 @@ import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.base.base.ValueResolver; import org.drools.base.base.ValueType; @@ -34,30 +34,22 @@ import org.drools.mvel.evaluators.VariableRestriction; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.rule.FactHandle; import org.kie.internal.builder.conf.EvaluatorOption; -@RunWith(Parameterized.class) public class CustomOperatorOnlyDrlTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CustomOperatorOnlyDrlTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { + public static Stream parameters() { // TODO EM DROOLS-6302 - return TestParametersUtil.getKieBaseCloudConfigurations(false); + return TestParametersUtil2.getKieBaseCloudConfigurations(false).stream(); } - @Test - public void testCustomOperatorCombiningConstraints() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCustomOperatorCombiningConstraints(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-3517 final String drl = "declare GN\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 8f7c8ef7aab..0161f772935 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 @@ -22,6 +22,7 @@ import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; +import java.util.stream.Stream; import org.drools.base.base.ValueResolver; import org.drools.base.base.ValueType; @@ -36,10 +37,9 @@ import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; @@ -47,50 +47,45 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class CustomOperatorTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CustomOperatorTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testCustomOperatorUsingCollections() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCustomOperatorUsingCollections(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = " $alice : Person(name == \"Alice\")\n" + " $bob : Person(name == \"Bob\", addresses supersetOf $alice.addresses)\n"; - customOperatorUsingCollections(constraints); + customOperatorUsingCollections(kieBaseTestConfiguration, constraints); } - @Test - public void testNoOperatorInstancesCreatedAtRuntime() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + 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"; - customOperatorUsingCollections(constraints); + customOperatorUsingCollections(kieBaseTestConfiguration, constraints); assertThat(SupersetOfEvaluatorDefinition.INSTANCES_COUNTER).isEqualTo(0); } - @Test - public void testCustomOperatorUsingCollectionsInverted() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCustomOperatorUsingCollectionsInverted(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6983 String constraints = " $bob : Person(name == \"Bob\")\n" + " $alice : Person(name == \"Alice\", $bob.addresses supersetOf this.addresses)\n"; - customOperatorUsingCollections(constraints); + customOperatorUsingCollections(kieBaseTestConfiguration, constraints); } - private void customOperatorUsingCollections(String constraints) { + private void customOperatorUsingCollections(KieBaseTestConfiguration kieBaseTestConfiguration, String constraints) { final String drl = "import " + Address.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -210,8 +205,9 @@ public boolean evaluateAll(final Collection leftCollection, final Collection rig } } - @Test - public void testCustomOperatorOnKieModule() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCustomOperatorOnKieModule(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Address.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ErrorOnInsertLogicalTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ErrorOnInsertLogicalTest.java index 24fa39fcb7a..4fa3454a9c3 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ErrorOnInsertLogicalTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ErrorOnInsertLogicalTest.java @@ -24,7 +24,7 @@ import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; import org.drools.io.ReaderResource; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.KieServices; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/FromSharingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/FromSharingTest.java index b90a9f29f6a..6766d061ca5 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/FromSharingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/FromSharingTest.java @@ -19,39 +19,31 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class FromSharingTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public FromSharingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testSharingFromWithoutHashCodeEquals() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSharingFromWithoutHashCodeEquals(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-2557 final String drl = "import " + PersonWithoutHashCodeEquals.class.getCanonicalName() + "\n" + @@ -189,8 +181,9 @@ public String toString() { } } - @Test - public void testFromSharingWithPropReactvityOnItsConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromSharingWithPropReactvityOnItsConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-3606 final String drl = "import " + Person.class.getCanonicalName() + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ImmutableFactsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ImmutableFactsTest.java index c16e4ff35d2..1267afe28d7 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ImmutableFactsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ImmutableFactsTest.java @@ -18,15 +18,14 @@ */ package org.drools.compiler.integrationtests; -import java.util.ArrayList; import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.ClassObjectFilter; import org.kie.api.runtime.KieSession; @@ -34,25 +33,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ImmutableFactsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ImmutableFactsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - Collection parameters = new ArrayList<>(); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY_IMMUTABLE}); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY_IMMUTABLE_MODEL_PATTERN}); - return parameters; + public static Stream parameters() { + return Stream.of(KieBaseTestConfiguration.CLOUD_IDENTITY_IMMUTABLE, KieBaseTestConfiguration.CLOUD_IDENTITY_IMMUTABLE_MODEL_PATTERN); } - @Test - public void testAlphaConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -95,8 +84,9 @@ public void testAlphaConstraint() { } } - @Test - public void testBetaConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBetaConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + 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 5426dc6f9ec..1d0e530e664 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 @@ -20,10 +20,10 @@ import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.ancompiler.CompiledNetwork; import org.drools.base.base.DroolsQuery; @@ -54,10 +54,10 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.rule.Rule; import org.kie.api.definition.type.FactType; @@ -70,22 +70,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.drools.core.util.DroolsTestUtil.rulestoMap; -@RunWith(Parameterized.class) public class IndexingTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public IndexingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test() - public void testAlphaNodeSharing() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaNodeSharing(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -135,8 +128,10 @@ public void testAlphaNodeSharing() { } } - @Test(timeout = 10000) - public void testBuildsIndexedAlphaNodes() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testBuildsIndexedAlphaNodes(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -168,8 +163,10 @@ public void testBuildsIndexedAlphaNodes() { } } - @Test(timeout = 10000) - public void testBuildsIndexedMemory() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testBuildsIndexedMemory(KieBaseTestConfiguration kieBaseTestConfiguration) { // tests indexes are correctly built final String drl = "package org.drools.compiler.test\n" + @@ -247,8 +244,10 @@ public void testBuildsIndexedMemory() { } } - @Test(timeout = 10000) - public void testIndexingOnQueryUnification() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testIndexingOnQueryUnification(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -283,8 +282,10 @@ public void testIndexingOnQueryUnification() { } } - @Test(timeout = 10000) - public void testIndexingOnQueryUnificationWithNot() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testIndexingOnQueryUnificationWithNot(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -416,8 +417,10 @@ private void assertInsertedUpdatedDeleted(final Map insertUpdat assertThat(insertUpdateDeleteMap.get("deleted").intValue()).isEqualTo(expectedDeleted); } - @Test(timeout = 10000) - public void testFullFastIteratorResume() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testFullFastIteratorResume(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -496,8 +499,10 @@ public void rowUpdated(final Row row) { } } - @Test(timeout = 10000) - public void testRangeIndex() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testRangeIndex(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "rule R1\n" + "when\n" + @@ -519,8 +524,10 @@ public void testRangeIndex() { } } - @Test(timeout = 10000) - public void testRangeIndex2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testRangeIndex2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "rule R1\n" + "when\n" + @@ -542,8 +549,10 @@ public void testRangeIndex2() { } } - @Test(timeout = 10000) - public void testNotNode() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testNotNode(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 salience 10\n" + @@ -570,8 +579,10 @@ public void testNotNode() { } } - @Test(timeout = 10000) - public void testNotNodeModifyRight() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testNotNodeModifyRight(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 salience 10 when\n" + @@ -597,8 +608,10 @@ public void testNotNodeModifyRight() { } } - @Test(timeout = 10000) - public void testRange() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testRange(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 salience 10 when\n" + @@ -624,8 +637,10 @@ public void testRange() { } } - @Test(timeout = 10000) - public void testRange2() throws IllegalAccessException, InstantiationException { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testRange2(KieBaseTestConfiguration kieBaseTestConfiguration) throws IllegalAccessException, InstantiationException { final String drl = "package org.drools.compiler.test\n" + "declare A\n" + " a: int\n" + @@ -674,8 +689,9 @@ public void testRange2() throws IllegalAccessException, InstantiationException { } } - @Test - public void testHashingAfterRemoveRightTuple() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testHashingAfterRemoveRightTuple(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1326 final String drl = "package " + this.getClass().getPackage().getName() + ";\n" + "import " + MyPojo.class.getCanonicalName() + "\n" + @@ -776,8 +792,9 @@ public String toString() { } } - @Test - public void testRequireLeftReorderingWithRangeIndex() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRequireLeftReorderingWithRangeIndex(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1326 final String drl = "import " + Queen.class.getCanonicalName() + ";\n" + "rule \"multipleQueensHorizontal\"\n" @@ -846,8 +863,10 @@ public int getRowIndex() { } } - @Test(timeout = 10000) - public void testBuildsIndexedMemoryWithThis() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testBuildsIndexedMemoryWithThis(KieBaseTestConfiguration kieBaseTestConfiguration) { // tests indexes are correctly built final String drl = "package org.drools.compiler.test\n" + @@ -879,8 +898,9 @@ public void testBuildsIndexedMemoryWithThis() { } } - @Test - public void testAlphaIndexWithBigDecimalCoercion() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaIndexWithBigDecimalCoercion(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -909,7 +929,7 @@ public void testAlphaIndexWithBigDecimalCoercion() { try { // BigDecimal Index is disabled - assertAlphaIndex(kbase, Person.class, 0); + assertAlphaIndex(kieBaseTestConfiguration, kbase, Person.class, 0); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -924,8 +944,9 @@ public void testAlphaIndexWithBigDecimalCoercion() { } } - @Test - public void testBeta() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBeta(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + @@ -962,11 +983,11 @@ public void testBeta() { } } - private void assertAlphaIndex(KieBase kbase, Class clazz, int hashedSize) { + private void assertAlphaIndex(KieBaseTestConfiguration kieBaseTestConfiguration, KieBase kbase, Class clazz, int hashedSize) { final ObjectTypeNode otn = KieUtil.getObjectTypeNode(kbase, clazz); assertThat(otn).isNotNull(); ObjectSinkPropagator objectSinkPropagator = otn.getObjectSinkPropagator(); - if (this.kieBaseTestConfiguration.useAlphaNetworkCompiler()) { + if (kieBaseTestConfiguration.useAlphaNetworkCompiler()) { objectSinkPropagator = ((CompiledNetwork) objectSinkPropagator).getOriginalSinkPropagator(); } CompositeObjectSinkAdapter sinkAdapter = (CompositeObjectSinkAdapter) objectSinkPropagator; @@ -978,8 +999,9 @@ private void assertAlphaIndex(KieBase kbase, Class clazz, int hashedSize) { } } - @Test - public void testAlphaIndexWithBigDecimalDifferentScale() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaIndexWithBigDecimalDifferentScale(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1008,7 +1030,7 @@ public void testAlphaIndexWithBigDecimalDifferentScale() { try { // BigDecimal Index is disabled - assertAlphaIndex(kbase, Person.class, 0); + assertAlphaIndex(kieBaseTestConfiguration, kbase, Person.class, 0); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1023,8 +1045,9 @@ public void testAlphaIndexWithBigDecimalDifferentScale() { } } - @Test - public void testBetaIndexWithBigDecimalDifferentScale() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBetaIndexWithBigDecimalDifferentScale(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1057,8 +1080,9 @@ public void testBetaIndexWithBigDecimalDifferentScale() { } } - @Test - public void testAlphaIndexOnField() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaIndexOnField(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1086,7 +1110,7 @@ public void testAlphaIndexOnField() { KieSession ksession = kbase.newKieSession(); try { - assertAlphaIndex(kbase, Person.class, 3); + assertAlphaIndex(kieBaseTestConfiguration, kbase, Person.class, 3); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1100,8 +1124,9 @@ public void testAlphaIndexOnField() { } } - @Test - public void testAlphaIndexOnThis() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaIndexOnThis(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "global java.util.List list\n" + @@ -1128,7 +1153,7 @@ public void testAlphaIndexOnThis() { KieSession ksession = kbase.newKieSession(); try { - assertAlphaIndex(kbase, Integer.class, 3); + assertAlphaIndex(kieBaseTestConfiguration, kbase, Integer.class, 3); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1141,41 +1166,47 @@ public void testAlphaIndexOnThis() { } } - public void betaIndexWithBigDecimalAndInt() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void betaIndexWithBigDecimalAndInt(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = "salary == $p1.salary, age == $p1.age"; - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 30, new BigDecimal("10")), true, 1); - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 1); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 30, new BigDecimal("10")), true, 1); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 1); } - @Test - public void betaIndexWithIntAndBigDecimal() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void betaIndexWithIntAndBigDecimal(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = "age == $p1.age, salary == $p1.salary"; - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 30, new BigDecimal("10")), true, 1); - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 1); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 30, new BigDecimal("10")), true, 1); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 1); } - @Test - public void betaIndexWithIntAndBigDecimalAndString() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void betaIndexWithIntAndBigDecimalAndString(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = "age == $p1.age, salary == $p1.salary, likes == $p1.likes"; - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10"), "dog"), new Person("Paul", 30, new BigDecimal("10"), "dog"), true, 2); - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10"), "dog"), new Person("Paul", 30, new BigDecimal("10"), "cat"), false, 2); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10"), "dog"), new Person("Paul", 30, new BigDecimal("10"), "dog"), true, 2); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10"), "dog"), new Person("Paul", 30, new BigDecimal("10"), "cat"), false, 2); } - @Test - public void betaIndexWithIntInequalityAndBigDecimal() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void betaIndexWithIntInequalityAndBigDecimal(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = "age > $p1.age, salary == $p1.salary"; - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 40, new BigDecimal("10")), true, 0); - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 0); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 40, new BigDecimal("10")), true, 0); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 0); } - @Test - public void betaIndexWithBigDecimalOnly() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void betaIndexWithBigDecimalOnly(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = "salary == $p1.salary"; - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), true, 0); - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("20")), false, 0); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), true, 0); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("20")), false, 0); } - private void betaIndexWithBigDecimalWithAdditionalBetaConstraint(String constraints, Person firstPerson, Person secondPerson, boolean shouldMatch, int expectedIndexCount) { + private void betaIndexWithBigDecimalWithAdditionalBetaConstraint(KieBaseTestConfiguration kieBaseTestConfiguration, String constraints, Person firstPerson, Person secondPerson, boolean shouldMatch, int expectedIndexCount) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/JoinNodeRangeIndexingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/JoinNodeRangeIndexingTest.java index d1616208a80..001e8ba6a3b 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/JoinNodeRangeIndexingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/JoinNodeRangeIndexingTest.java @@ -20,12 +20,12 @@ import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Stream; import org.drools.ancompiler.CompiledNetwork; import org.drools.core.common.BetaConstraints; @@ -41,10 +41,9 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieModule; import org.kie.api.conf.BetaRangeIndexOption; @@ -52,27 +51,20 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class JoinNodeRangeIndexingTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public JoinNodeRangeIndexingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - private KieBase getKieBaseWithRangeIndexOption(String drl) { + private KieBase getKieBaseWithRangeIndexOption(KieBaseTestConfiguration kieBaseTestConfiguration, String drl) { KieModule kieModule = KieUtil.getKieModuleFromDrls("indexing-test", kieBaseTestConfiguration, drl); return KieBaseUtil.newKieBaseFromKieModuleWithAdditionalOptions(kieModule, kieBaseTestConfiguration, BetaRangeIndexOption.ENABLED); } - @Test - public void testRangeIndexForJoin() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRangeIndexForJoin(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Pet.class.getCanonicalName() + ";\n" + "rule R1\n" + @@ -82,9 +74,9 @@ public void testRangeIndexForJoin() { "then\n" + "end\n"; - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Person.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Person.class); final KieSession ksession = kbase.newKieSession(); try { @@ -97,20 +89,20 @@ public void testRangeIndexForJoin() { } } - private void assertIndexedTrue(KieBase kbase, Class factClass) { - assertIndexed(kbase, factClass, true); + private void assertIndexedTrue(KieBaseTestConfiguration kieBaseTestConfiguration, KieBase kbase, Class factClass) { + assertIndexed(kieBaseTestConfiguration, kbase, factClass, true); } - private void assertIndexedFalse(KieBase kbase, Class factClass) { - assertIndexed(kbase, factClass, false); + private void assertIndexedFalse(KieBaseTestConfiguration kieBaseTestConfiguration, KieBase kbase, Class factClass) { + assertIndexed(kieBaseTestConfiguration, kbase, factClass, false); } - private void assertIndexed(KieBase kbase, Class factClass, boolean isIndexed) { + private void assertIndexed(KieBaseTestConfiguration kieBaseTestConfiguration, KieBase kbase, Class factClass, boolean isIndexed) { final ObjectTypeNode otn = KieUtil.getObjectTypeNode(kbase, factClass); assertThat(otn).isNotNull(); ObjectSinkPropagator objectSinkPropagator = otn.getObjectSinkPropagator(); - if (this.kieBaseTestConfiguration.useAlphaNetworkCompiler()) { + if (kieBaseTestConfiguration.useAlphaNetworkCompiler()) { objectSinkPropagator = ((CompiledNetwork) objectSinkPropagator).getOriginalSinkPropagator(); } @@ -128,8 +120,9 @@ private void assertIndexed(KieBase kbase, Class factClass, boolean isIndexed) assertThat(isPassedForJoinNode).isTrue(); } - @Test - public void testCoercionBigDecimalVsInt() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCoercionBigDecimalVsInt(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Primitives.class.getCanonicalName() + ";\n" + @@ -144,9 +137,9 @@ public void testCoercionBigDecimalVsInt() { // Integer is coerced to BigDecimal - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Primitives.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Primitives.class); final KieSession ksession = kbase.newKieSession(); try { @@ -170,8 +163,9 @@ public void testCoercionBigDecimalVsInt() { } } - @Test - public void testCoercionIntVsBigDecimal() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCoercionIntVsBigDecimal(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "import " + Primitives.class.getCanonicalName() + ";\n" + @@ -187,9 +181,9 @@ public void testCoercionIntVsBigDecimal() { // BigDecimal is coerced to Integer - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Primitives.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Primitives.class); final KieSession ksession = kbase.newKieSession(); try { @@ -215,8 +209,9 @@ public void testCoercionIntVsBigDecimal() { } } - @Test - public void testCoercionStringVsIntWithMap() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCoercionStringVsIntWithMap(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Map.class.getCanonicalName() + ";\n" + @@ -232,10 +227,10 @@ public void testCoercionStringVsIntWithMap() { // Integer is coerced to String (thus, String comparison) - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); // We don't index this case - assertIndexedFalse(kbase, Cheese.class); + assertIndexedFalse(kieBaseTestConfiguration, kbase, Cheese.class); final KieSession ksession = kbase.newKieSession(); try { @@ -263,8 +258,9 @@ public void testCoercionStringVsIntWithMap() { } } - @Test - public void testCoercionIntVsStringWithMap() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCoercionIntVsStringWithMap(KieBaseTestConfiguration kieBaseTestConfiguration) { // we don't enable range index for this case final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -280,10 +276,10 @@ public void testCoercionIntVsStringWithMap() { // String is coerced to Integer (thus, Number comparison) - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); // We don't index this case - assertIndexedFalse(kbase, MapHolder.class); + assertIndexedFalse(kieBaseTestConfiguration, kbase, MapHolder.class); final KieSession ksession = kbase.newKieSession(); try { @@ -327,8 +323,9 @@ public void setMap(Map map) { } - @Test - public void testJoinWithGlobal() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testJoinWithGlobal(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "global Integer minAge;\n" + "rule R1\n" + @@ -339,7 +336,7 @@ public void testJoinWithGlobal() { // Actually, [age > minAge] becomes an AlphaNode and doesn't use index. - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); final KieSession ksession = kbase.newKieSession(); try { @@ -351,8 +348,9 @@ public void testJoinWithGlobal() { } } - @Test - public void testInsertUpdateDelete() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testInsertUpdateDelete(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Pet.class.getCanonicalName() + ";\n" + "global java.util.Set result;\n" + @@ -388,9 +386,9 @@ public void testInsertUpdateDelete() { " delete($pet);\n" + "end\n"; - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Person.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Person.class); final KieSession ksession = kbase.newKieSession(); try { @@ -425,8 +423,9 @@ public void testInsertUpdateDelete() { } } - @Test - public void testBoxed() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBoxed(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + IntegerHolder.class.getCanonicalName() + ";\n" + "rule R1\n" + @@ -436,9 +435,9 @@ public void testBoxed() { "then\n" + "end\n"; - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Person.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Person.class); final KieSession ksession = kbase.newKieSession(); try { @@ -451,8 +450,9 @@ public void testBoxed() { } } - @Test - public void testBoxed2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBoxed2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + IntegerHolder.class.getCanonicalName() + ";\n" + "rule R1\n" + @@ -462,9 +462,9 @@ public void testBoxed2() { "then\n" + "end\n"; - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, IntegerHolder.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, IntegerHolder.class); final KieSession ksession = kbase.newKieSession(); try { @@ -489,8 +489,9 @@ public Integer getValue() { } } - @Test - public void testMultipleFacts() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMultipleFacts(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Pet.class.getCanonicalName() + ";\n" + @@ -503,9 +504,9 @@ public void testMultipleFacts() { " result.add( $person.getName() + \" > \" + $pet.getName() );\n" + "end\n"; - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Person.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Person.class); final KieSession ksession = kbase.newKieSession(); Set result = new HashSet<>(); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/KieBaseIncludeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/KieBaseIncludeTest.java index 46006bac4d9..673f159457e 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/KieBaseIncludeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/KieBaseIncludeTest.java @@ -20,14 +20,14 @@ import java.io.File; import java.io.IOException; +import java.util.stream.Stream; import org.drools.compiler.kie.builder.impl.DrlProject; import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.drools.core.util.FileManager; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; @@ -40,21 +40,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class KieBaseIncludeTest { - private final Class projectType; - public KieBaseIncludeTest(boolean useModel) { - this.projectType = useModel ? ExecutableModelProject.class : DrlProject.class; + public static Stream> parameters() { + return Stream.of(ExecutableModelProject.class, DrlProject.class); } - @Parameterized.Parameters(name = "{0}") - public static Object[] params() { - return new Object[] {false, true}; - } - - @Test - public void testKJarIncludedDependency() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void testKJarIncludedDependency(Class projectType) throws Exception { String rule = "package org.test rule R when String() then end"; KieServices ks = KieServices.Factory.get(); @@ -64,7 +58,7 @@ public void testKJarIncludedDependency() throws Exception { FileManager fileManager = new FileManager(); fileManager.setUp(); - InternalKieModule kJar1 = createKieJar( ks, includedReleaseId, rule ); + InternalKieModule kJar1 = createKieJar(projectType, ks, includedReleaseId, rule ); fileManager.tearDown(); fileManager = new FileManager(); @@ -90,7 +84,7 @@ public void testKJarIncludedDependency() throws Exception { fileManager.tearDown(); } - private InternalKieModule createKieJar(KieServices ks, ReleaseId releaseId, String... rules) throws IOException { + private InternalKieModule createKieJar(Class projectType, KieServices ks, ReleaseId releaseId, String... rules) throws IOException { KieModuleModel kproj = ks.newKieModuleModel(); KieBaseModel kieBaseModel1 = kproj.newKieBaseModel("KBase1"); KieSessionModel ksession1 = kieBaseModel1.newKieSessionModel("KSession1"); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/MultiSheetsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/MultiSheetsTest.java index 8e37053a634..94255c44875 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/MultiSheetsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/MultiSheetsTest.java @@ -18,16 +18,15 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.compiler.kie.builder.impl.DrlProject; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.model.Result; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; @@ -38,41 +37,37 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class MultiSheetsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public MultiSheetsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testNoSheet() { - check(null, "Mario can drink"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNoSheet(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, null, "Mario can drink"); } - @Test - public void testSheet1() { - check("Sheet1", "Mario can drink"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSheet1(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "Sheet1", "Mario can drink"); } - @Test - public void testSheet2() { - check("Sheet2", "Mario can drive"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSheet2(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "Sheet2", "Mario can drive"); } - @Test - public void testSheet12() { - check("Sheet1,Sheet2", "Mario can drink", "Mario can drive"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSheet12(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "Sheet1,Sheet2", "Mario can drink", "Mario can drive"); } - private void check(String sheets, String... results) { + private void check(KieBaseTestConfiguration kieBaseTestConfiguration, String sheets, String... results) { KieServices ks = KieServices.get(); KieResources kr = ks.getResources(); @@ -89,7 +84,7 @@ private void check(String sheets, String... results) { kfs.writeKModuleXML( kproj.toXML() ); - KieBuilder kb = buildDTable( ks, kfs ); + KieBuilder kb = buildDTable(kieBaseTestConfiguration, ks, kfs); KieContainer kc = ks.newKieContainer(kb.getKieModule().getReleaseId()); KieSession sessionDtable = kc.newKieSession( "dtable" ); @@ -102,7 +97,7 @@ private void check(String sheets, String... results) { } } - private KieBuilder buildDTable( KieServices ks, KieFileSystem kfs ) { + private KieBuilder buildDTable(KieBaseTestConfiguration kieBaseTestConfiguration, KieServices ks, KieFileSystem kfs) { if (kieBaseTestConfiguration.getExecutableModelProjectClass().isPresent()) { return ks.newKieBuilder( kfs ).buildAll(kieBaseTestConfiguration.getExecutableModelProjectClass().get()); } else { diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PassivePatternTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PassivePatternTest.java index f6646b0209c..f1fc19a9b55 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PassivePatternTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PassivePatternTest.java @@ -19,37 +19,29 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class PassivePatternTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public PassivePatternTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testPassiveInsert() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testPassiveInsert(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "global java.util.List list\n" + "rule R when\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyChangeSupportTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyChangeSupportTest.java index 4dd9b680800..08c7bd59f7a 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyChangeSupportTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyChangeSupportTest.java @@ -21,7 +21,7 @@ import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieSession; import org.kie.internal.utils.KieHelper; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyReactivityTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyReactivityTest.java index f678d176e3c..f3b580b0ecf 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyReactivityTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyReactivityTest.java @@ -18,18 +18,17 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; import java.util.HashMap; import java.util.Map; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieModule; @@ -41,22 +40,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class PropertyReactivityTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public PropertyReactivityTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testDisablePropertyReactivity() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDisablePropertyReactivity(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-5746 final String drl = "import " + Person.class.getCanonicalName() + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/RuleChainingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/RuleChainingTest.java index 81c0dc86405..b40a316aacc 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/RuleChainingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/RuleChainingTest.java @@ -20,10 +20,9 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.event.rule.AfterMatchFiredEvent; import org.kie.api.event.rule.AgendaEventListener; @@ -34,8 +33,8 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -43,22 +42,15 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -@RunWith(Parameterized.class) public class RuleChainingTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public RuleChainingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testRuleChainingWithLogicalInserts() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRuleChainingWithLogicalInserts(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package com.sample\n" + " \n" + "declare Some\n" + @@ -126,8 +118,9 @@ public void testRuleChainingWithLogicalInserts() { } } - @Test - public void testDoubleInsertLogical() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDoubleInsertLogical(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-7525 final String drl = "package org.test;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SharingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SharingTest.java index 485b3097808..80bce07aedf 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SharingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SharingTest.java @@ -20,8 +20,8 @@ import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.base.base.ClassObjectType; import org.drools.kiesession.rulebase.InternalKnowledgeBase; @@ -36,28 +36,19 @@ import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.Agenda; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class SharingTest { - - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public SharingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } public static class TestStaticUtils { @@ -81,8 +72,9 @@ public static enum TestEnum { CCC; } - @Test - public void testDontShareAlphaWithStaticMethod() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDontShareAlphaWithStaticMethod(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl1 = "package c;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -148,8 +140,9 @@ private void assertNonHashableConstraint(ObjectTypeNode otn, String expected) { } } - @Test - public void testDontShareAlphaWithNonFinalField() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDontShareAlphaWithNonFinalField(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl = "package com.example;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -184,8 +177,9 @@ public void testDontShareAlphaWithNonFinalField() { } } - @Test - public void testShareAlphaWithFinalField() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShareAlphaWithFinalField(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl = "package com.example;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -225,8 +219,9 @@ public void testShareAlphaWithFinalField() { } } - @Test - public void testShareAlphaWithNestedFinalField() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShareAlphaWithNestedFinalField(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl = "package com.example;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -263,8 +258,9 @@ public void testShareAlphaWithNestedFinalField() { } } - @Test - public void testShareAlphaWithEnum() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShareAlphaWithEnum(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl = "package com.example;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -298,8 +294,9 @@ public void testShareAlphaWithEnum() { } } - @Test - public void testDontShareAlphaWithBigDecimalConstructor() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDontShareAlphaWithBigDecimalConstructor(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl = "package com.example;\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -333,8 +330,9 @@ public void testDontShareAlphaWithBigDecimalConstructor() { } } - @Test - public void testShouldAlphaShareNotEqualsInDifferentPackages() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShouldAlphaShareNotEqualsInDifferentPackages(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1404 final String drl1 = "package c;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -369,8 +367,9 @@ public void testShouldAlphaShareNotEqualsInDifferentPackages() { } } - @Test - public void testShouldAlphaShareNotEqualsInDifferentPackages2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShouldAlphaShareNotEqualsInDifferentPackages2(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1404 final String drl1 = "package c;\n" + "import " + FactWithList.class.getCanonicalName() + "\n" + @@ -408,8 +407,9 @@ public void testShouldAlphaShareNotEqualsInDifferentPackages2() { } } - @Test - public void testSubnetworkSharing() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSubnetworkSharing(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + A.class.getCanonicalName() + "\n" + "import " + B.class.getCanonicalName() + "\n" + 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 65c323457ba..82341ecac21 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 @@ -22,6 +22,7 @@ import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import org.drools.base.base.ClassObjectType; import org.drools.core.common.InternalFactHandle; @@ -36,10 +37,10 @@ import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.definition.type.FactType; @@ -61,22 +62,16 @@ /** * Tests related to the stream support features */ -@RunWith(Parameterized.class) public class StreamsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public StreamsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } - @Test(timeout = 10000) - public void testEventAssertion() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testEventAssertion(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -155,8 +150,9 @@ public void testEventAssertion() { } } - @Test - public void testEntryPointReference() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEntryPointReference(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources("stream-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_EntryPointReference.drl"); final KieSession session = kbase.newKieSession(); @@ -195,8 +191,10 @@ public void testEntryPointReference() { } } - @Test(timeout = 10000) - public void testModifyRetracOnEntryPointFacts() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testModifyRetracOnEntryPointFacts(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -265,8 +263,9 @@ public void testModifyRetracOnEntryPointFacts() { } } - @Test - public void testModifyOnEntryPointFacts() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testModifyOnEntryPointFacts(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -322,8 +321,10 @@ public void testModifyOnEntryPointFacts() { } } - @Test(timeout = 10000) - public void testEntryPointWithAccumulateAndMVEL() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testEntryPointWithAccumulateAndMVEL(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "rule R1 dialect 'mvel'\n" + @@ -356,8 +357,10 @@ public void testEntryPointWithAccumulateAndMVEL() { } } - @Test(timeout = 10000) - public void testGetEntryPointList() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testGetEntryPointList(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources("stream-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_EntryPointReference.drl"); final KieSession session = kbase.newKieSession(); @@ -378,8 +381,10 @@ public void testGetEntryPointList() { } } - @Test(timeout = 10000) - public void testEventDoesNotExpireIfNotInPattern() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testEventDoesNotExpireIfNotInPattern(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -423,8 +428,10 @@ public void testEventDoesNotExpireIfNotInPattern() { } } - @Test(timeout = 10000) - public void testEventExpirationSetToZero() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testEventExpirationSetToZero(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -471,8 +478,10 @@ public void testEventExpirationSetToZero() { } } - @Test(timeout = 10000) - public void testEventExpirationValue() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testEventExpirationValue(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl1 = "package org.drools.pkg1\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -505,8 +514,10 @@ public void testEventExpirationValue() { } } - @Test(timeout = 10000) - public void testDeclaredEntryPoint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testDeclaredEntryPoint(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.jboss.qa.brms.declaredep\n" + "declare entry-point UnusedEntryPoint\n" + "end\n" + @@ -527,8 +538,9 @@ public void testDeclaredEntryPoint() { } } - @Test - public void testWindowDeclaration() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testWindowDeclaration(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -576,8 +588,10 @@ public void testWindowDeclaration() { } } - @Test(timeout = 10000) - public void testWindowDeclaration2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testWindowDeclaration2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "declare Double\n" + " @role(event)\n" + @@ -618,8 +632,10 @@ public void testWindowDeclaration2() { } } - @Test(timeout = 10000) - public void testMultipleWindows() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testMultipleWindows(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -656,8 +672,9 @@ public void testMultipleWindows() { } } - @Test - public void testWindowWithEntryPointCompilationError() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testWindowWithEntryPointCompilationError(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "declare window X\n" + " Cheese( type == \"gorgonzola\" ) over window:time(1m) from entry-point Z\n" + @@ -674,8 +691,10 @@ public void testWindowWithEntryPointCompilationError() { .isNotEmpty(); } - @Test(timeout = 10000) - public void testAtomicActivationFiring() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testAtomicActivationFiring(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // JBRULES-3383 final String drl = "package org.drools.compiler.test\n" + "declare Event\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkCEPTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkCEPTest.java index 219a2f44382..c9732da2c91 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkCEPTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkCEPTest.java @@ -18,34 +18,26 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; -@RunWith(Parameterized.class) public class SubnetworkCEPTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public SubnetworkCEPTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } - @Test - public void testNPEOnFlushingOfUnlinkedPmem() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNPEOnFlushingOfUnlinkedPmem(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1285 final String drl = "import " + SubnetworkTest.A.class.getCanonicalName() + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkTest.java index dadf5387ac3..223e2883be9 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkTest.java @@ -20,10 +20,10 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.Role; import org.kie.api.runtime.KieSession; @@ -33,25 +33,17 @@ import java.awt.Dimension; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class SubnetworkTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public SubnetworkTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } @Role(Role.Type.EVENT) @@ -69,8 +61,10 @@ public static class C { } - @Test(timeout = 10000) - public void testRightStagingOnSharedSubnetwork() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testRightStagingOnSharedSubnetwork(KieBaseTestConfiguration kieBaseTestConfiguration) { // RHBRMS-2624 final String drl = "import " + AtomicInteger.class.getCanonicalName() + ";\n" + @@ -107,8 +101,10 @@ public void testRightStagingOnSharedSubnetwork() { } } - @Test(timeout = 10000) - public void testUpdateOnSharedSubnetwork() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testUpdateOnSharedSubnetwork(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1360 final String drl = "import " + AtomicInteger.class.getCanonicalName() + ";\n" + @@ -154,8 +150,10 @@ public void testUpdateOnSharedSubnetwork() { } } - @Test(timeout = 10000) - public void testSubNeworkNotRemoveRightRemove() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubNeworkNotRemoveRightRemove(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Dimension.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -188,8 +186,10 @@ public void testSubNeworkNotRemoveRightRemove() { } } - @Test(timeout = 10000) - public void testSubNeworkNotRemoveLeftRemove() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubNeworkNotRemoveLeftRemove(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Dimension.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -226,8 +226,10 @@ public void testSubNeworkNotRemoveLeftRemove() { } } - @Test(timeout = 10000) - public void testSubNeworkQueryTest() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubNeworkQueryTest(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Dimension.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -273,16 +275,20 @@ public void testSubNeworkQueryTest() { } } - @Test(timeout = 10000) - public void testSubNetworks() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubNetworks(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kieBase = KieBaseUtil.getKieBaseFromClasspathResources("subnetwork-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_SubNetworks.drl"); final KieSession session = kieBase.newKieSession(); session.dispose(); } - @Test(timeout = 10000) - public void testSubnetworkSharingWith2SinksFromLia() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubnetworkSharingWith2SinksFromLia(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1656 final String drl = "import " + X.class.getCanonicalName() + "\n" + @@ -340,8 +346,10 @@ public void testSubnetworkSharingWith2SinksFromLia() { } } - @Test(timeout = 10000) - public void testSubnetworkSharingWith2SinksAfterLia() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubnetworkSharingWith2SinksAfterLia(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1656 final String drl = "import " + X.class.getCanonicalName() + "\n" + @@ -460,19 +468,21 @@ public void setId(final int id) { } } - @Test - public void subnetworkSharingWith2SinksAndRightTupleDelete_shouldNotThrowNPE() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void subnetworkSharingWith2SinksAndRightTupleDelete_shouldNotThrowNPE(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-7420 - testFromCollectInSubnetwork(true); + testFromCollectInSubnetwork(kieBaseTestConfiguration, true); } - @Test - public void subnetworkNoSharingWith2SinksAndRightTupleDelete_shouldNotThrowNPE() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void subnetworkNoSharingWith2SinksAndRightTupleDelete_shouldNotThrowNPE(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-7420 - testFromCollectInSubnetwork(false); + testFromCollectInSubnetwork(kieBaseTestConfiguration, false); } - private void testFromCollectInSubnetwork(boolean nodeSharing) { + private void testFromCollectInSubnetwork(KieBaseTestConfiguration kieBaseTestConfiguration, boolean nodeSharing) { String accConstraint = nodeSharing ? "" : "size > 0"; final String drl = "import " + List.class.getCanonicalName() + ";\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/UnexpectedLoopTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/UnexpectedLoopTest.java index 4a700f65084..af5a2f1c61b 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/UnexpectedLoopTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/UnexpectedLoopTest.java @@ -18,39 +18,32 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.compiler.integrationtests.model.CalcFact; import org.drools.compiler.integrationtests.model.Item; import org.drools.compiler.integrationtests.model.RecordFact; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class UnexpectedLoopTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - public UnexpectedLoopTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); - } - - @Test - public void joinFromFromPeerUpdate_shouldNotLoop() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void joinFromFromPeerUpdate_shouldNotLoop(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kieBase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "org/drools/compiler/integrationtests/joinFromFrom.drl"); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/AndTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/AndTest.java index cd4564ac5a7..bd2d2c3b6a7 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/AndTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/AndTest.java @@ -19,38 +19,30 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Message; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class AndTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public AndTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testExplicitAnd() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExplicitAnd(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package HelloWorld\n" + " \n" + "import " + Message.class.getCanonicalName() + ";\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ContainsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ContainsTest.java index a2e7b4bc73c..21597f74be4 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ContainsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ContainsTest.java @@ -19,8 +19,8 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Cheesery; @@ -29,31 +29,23 @@ import org.drools.testcoverage.common.model.Primitives; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ContainsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ContainsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testContainsCheese() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsCheese(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -106,8 +98,9 @@ public void testContainsCheese() { } } - @Test - public void testContainsInArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsInArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + Primitives.class.getCanonicalName() + " ;\n" + @@ -151,8 +144,9 @@ public void testContainsInArray() { } } - @Test - public void testNotContainsOperator() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsOperator(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2404: "not contains" operator doesn't work on nested fields final String str = "package org.drools.compiler.integrationtests.operators\n" + "import " + Order.class.getCanonicalName() + " ;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EnabledTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EnabledTest.java index a3c837bf20f..38d63f05d14 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EnabledTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EnabledTest.java @@ -19,17 +19,17 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.MyFact; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.runners.Parameterized; import org.kie.api.KieBase; import org.kie.api.KieServices; @@ -45,22 +45,16 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -@RunWith(Parameterized.class) public class EnabledTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public EnabledTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(false); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(false).stream(); } - @Test - public void testEnabledExpression() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEnabledExpression(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -129,8 +123,9 @@ public void testEnabledExpression() { } } - @Test - public void testEnabledExpression2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEnabledExpression2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + MyFact.class.getName() + ";\n" + "rule R1\n" + " enabled( rule.name == $f.name )" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EqualsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EqualsTest.java index 7c68e02c6ee..fd5e809f11a 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EqualsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EqualsTest.java @@ -27,30 +27,22 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class EqualsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public EqualsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { + public static Collection parameters() { return TestParametersUtil.getKieBaseCloudConfigurations(true); } - @Test - public void testEqualitySupport() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEqualitySupport(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + PersonWithSpecificEquals.class.getCanonicalName() + " ;\n" + @@ -92,8 +84,9 @@ public void testEqualitySupport() { } } - @Test - public void testNotEqualsOperator() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotEqualsOperator(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-3003: restriction evaluation returns 'false' for "trueField != falseField" final String str = "package org.drools.compiler.integrationtests.operators\n" + @@ -124,8 +117,9 @@ public void testNotEqualsOperator() { } } - @Test - public void testCharComparisons() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCharComparisons(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + Primitives.class.getCanonicalName() + " ;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalRewriteTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalRewriteTest.java index a24bae0c194..c6e8a5856df 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalRewriteTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalRewriteTest.java @@ -19,38 +19,30 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Order; import org.drools.testcoverage.common.model.OrderItem; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class EvalRewriteTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public EvalRewriteTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testEvalRewrite() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalRewrite(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + OrderItem.class.getCanonicalName() + " ;\n" + @@ -147,8 +139,9 @@ public void testEvalRewrite() { } } - @Test - public void testEvalRewriteMatches() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalRewriteMatches(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + OrderItem.class.getCanonicalName() + " ;\n" + @@ -199,8 +192,9 @@ public void testEvalRewriteMatches() { } } - @Test - public void testEvalRewriteWithSpecialOperators() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalRewriteWithSpecialOperators(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + OrderItem.class.getCanonicalName() + " ;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalTest.java index 5f728494d27..bac22467050 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalTest.java @@ -21,8 +21,8 @@ import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.core.reteoo.ReteDumper; import org.drools.testcoverage.common.model.Cheese; @@ -33,10 +33,9 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieModule; @@ -47,22 +46,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) public class EvalTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public EvalTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testEvalDefaultCompiler() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalDefaultCompiler(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -96,8 +88,9 @@ public void testEvalDefaultCompiler() { } } - @Test - public void testEvalNoPatterns() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalNoPatterns(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "global java.util.List list\n" + "rule \"no patterns1\"\n" + @@ -145,8 +138,9 @@ public void testEvalNoPatterns() { } } - @Test - public void testEvalMore() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalMore(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -186,8 +180,9 @@ public void testEvalMore() { } } - @Test - public void testEvalCE() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalCE(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"inline eval\"\n" + @@ -217,8 +212,9 @@ public void testEvalCE() { } } - @Test - public void testEvalException() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalException(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "function boolean throwException(Object object) {\n" + @@ -251,8 +247,9 @@ public void testEvalException() { } } - @Test - public void testEvalInline() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalInline(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"inline eval\"\n" + @@ -281,8 +278,9 @@ public void testEvalInline() { } } - @Test - public void testEvalWithLineBreaks() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalWithLineBreaks(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "\n" + "global java.util.List results\n" + @@ -317,8 +315,9 @@ public void testEvalWithLineBreaks() { } } - @Test - public void testEvalWithBigDecimal() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalWithBigDecimal(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import java.math.BigDecimal; \n" + @@ -350,8 +349,9 @@ public void testEvalWithBigDecimal() { } } - @Test - public void testFieldBiningsAndEvalSharing() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFieldBiningsAndEvalSharing(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -373,11 +373,12 @@ public void testFieldBiningsAndEvalSharing() { " then\n" + " list.add(\"rule2 fired\");\n" + "end "; - evalSharingTest(drl); + evalSharingTest(kieBaseTestConfiguration, drl); } - @Test - public void testFieldBiningsAndPredicateSharing() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFieldBiningsAndPredicateSharing(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -397,10 +398,10 @@ public void testFieldBiningsAndPredicateSharing() { " then\n" + " list.add(\"rule2 fired\");\n" + "end"; - evalSharingTest(drl); + evalSharingTest(kieBaseTestConfiguration, drl); } - private void evalSharingTest(final String drl) { + private void evalSharingTest(KieBaseTestConfiguration kieBaseTestConfiguration, final String drl) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("eval-test", kieBaseTestConfiguration, drl); @@ -423,8 +424,9 @@ private void evalSharingTest(final String drl) { } } - @Test - public void testCastingInsideEvals() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCastingInsideEvals(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "\n" + "global java.lang.Integer value;\n" + @@ -452,8 +454,9 @@ public void testCastingInsideEvals() { } } - @Test - public void testAlphaEvalWithOrCE() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaEvalWithOrCE(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + FactA.class.getCanonicalName() + ";\n" + "import " + FactB.class.getCanonicalName() + ";\n" + @@ -491,8 +494,9 @@ public void testAlphaEvalWithOrCE() { } } - @Test - public void testModifyWithLiaToEval() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testModifyWithLiaToEval(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -527,8 +531,9 @@ public void testModifyWithLiaToEval() { } } - @Test - public void testBigDecimalWithFromAndEval() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBigDecimalWithFromAndEval(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "rule \"Test Rule\"\n" + "when\n" + @@ -548,8 +553,9 @@ public void testBigDecimalWithFromAndEval() { } } - @Test - public void testPredicate() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testPredicate(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list;\n" + @@ -588,8 +594,9 @@ public void testPredicate() { } } - @Test - public void testPredicateException() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testPredicateException(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "function boolean throwException(Object object) {\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ExistsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ExistsTest.java index e4c9d13e39f..5a114a6d3b3 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ExistsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ExistsTest.java @@ -20,39 +20,31 @@ import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.AFact; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ExistsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ExistsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testExistsIterativeModifyBug() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExistsIterativeModifyBug(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2809 // This bug occurs when a tuple is modified, the remove/add puts it onto the memory end // However before this was done it would attempt to find the next tuple, starting from itself @@ -113,8 +105,9 @@ public void testExistsIterativeModifyBug() { } } - @Test - public void testNodeSharingNotExists() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNodeSharingNotExists(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -156,8 +149,9 @@ public void testNodeSharingNotExists() { } } - @Test - public void testLastMemoryEntryExistsBug() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testLastMemoryEntryExistsBug(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2809 // This occurs when a blocker is the last in the node's memory, or if there is only one fact in the node // And it gets no opportunity to rematch with itself @@ -208,8 +202,9 @@ public void testLastMemoryEntryExistsBug() { } } - @Test - public void testExistsWithOrAndSubnetwork() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExistsWithOrAndSubnetwork(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6550 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -245,8 +240,9 @@ public void testExistsWithOrAndSubnetwork() { } } - @Test - public void testSharedExistsWithNot() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSharedExistsWithNot(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6710 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -289,8 +285,9 @@ public void testSharedExistsWithNot() { } } - @Test - public void existsAndNotWithSingleCoercion_shouldNotMatchExists() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void existsAndNotWithSingleCoercion_shouldNotMatchExists(KieBaseTestConfiguration kieBaseTestConfiguration) { // KIE-766 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -331,8 +328,9 @@ public void existsAndNotWithSingleCoercion_shouldNotMatchExists() { } } - @Test - public void existsAndNotWithMultipleCoercion_shouldNotMatchExists() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void existsAndNotWithMultipleCoercion_shouldNotMatchExists(KieBaseTestConfiguration kieBaseTestConfiguration) { // KIE-766 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -373,8 +371,9 @@ public void existsAndNotWithMultipleCoercion_shouldNotMatchExists() { } } - @Test - public void existsAndNotWithBigDecimals_shouldNotMatchExists() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void existsAndNotWithBigDecimals_shouldNotMatchExists(KieBaseTestConfiguration kieBaseTestConfiguration) { // KIE-766 final String drl = "package org.drools.compiler.integrationtests.operators;\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 6ece353028a..7b1a6f500bf 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 @@ -20,131 +20,138 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ForAllTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ForAllTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void test1P1CFiring1() { - check("age >= 18", 1, new Person("Mario", 45)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CFiring1(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18", 1, new Person("Mario", 45)); } - @Test - public void test1P1CFiring2() { - check("age == 8 || == 45", 1, new Person("Mario", 45), new Person("Sofia", 8)); + @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)); } - @Test - public void test1P1CNotFiring() { - check("age >= 18", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CNotFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18", 0, new Person("Sofia", 8)); } - @Test - public void test1P1CNotFiringWithAnd() { - check("name == \"Sofia\" && age >= 18", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CNotFiringWithAnd(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "name == \"Sofia\" && age >= 18", 0, new Person("Sofia", 8)); } - @Test - public void test1P1CNotFiringWithParenthesis() { - check("(name == \"Sofia\" && age >= 18)", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CNotFiringWithParenthesis(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "(name == \"Sofia\" && age >= 18)", 0, new Person("Sofia", 8)); } - @Test - public void test1P1CNotFiringWithOr() { - check("age >= 18 || name == \"Mario\"", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CNotFiringWithOr(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18 || name == \"Mario\"", 0, new Person("Sofia", 8)); } - @Test - public void test1P1CNotFiringWithParenthesisAndOr() { - check("(name == \"Sofia\" && age >= 18) || name == \"Mario\"", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CNotFiringWithParenthesisAndOr(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "(name == \"Sofia\" && age >= 18) || name == \"Mario\"", 0, new Person("Sofia", 8)); } - @Test - public void test1P2CFiring() { - check("age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P2CFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43)); } - @Test - public void test1P2CFiringWithIn() { - check("age >= 18, name in(\"Mario\", \"Mark\")", 1, new Person("Mario", 45), new Person("Mark", 43)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P2CFiringWithIn(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18, name in(\"Mario\", \"Mark\")", 1, new Person("Mario", 45), new Person("Mark", 43)); } - @Test - public void test1P2CNotFiring1() { - check("age >= 18, name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Mark", 43), new Person("Edson", 40)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P2CNotFiring1(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18, name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Mark", 43), new Person("Edson", 40)); } - @Test - public void test1P2CNotFiring2() { - check("age < 18, name.startsWith(\"M\")", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P2CNotFiring2(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age < 18, name.startsWith(\"M\")", 0, new Person("Sofia", 8)); } - @Test - public void test2P1CFiring() { - check("age >= 18", "name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test2P1CFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18", "name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Sofia", 8)); } - @Test - public void test2P1CNotFiring() { - check("age >= 1", "name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test2P1CNotFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 1", "name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Sofia", 8)); } - @Test - public void test2P2CFiring() { - check("", "age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test2P2CFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "", "age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43)); } - @Test - public void test2P2CNotFiring1() { - check("", "age >= 18, name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Mark", 43), new Person("Edson", 40)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test2P2CNotFiring1(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "", "age >= 18, name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Mark", 43), new Person("Edson", 40)); } - @Test - public void test2P3CFiring() { - check("name.length() < 6", "age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43), new Person("Daniele", 43)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test2P3CFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "name.length() < 6", "age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43), new Person("Daniele", 43)); } - @Test - public void testNoFiring() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNoFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-5915 - check("", "age >= 18", 0); + check(kieBaseTestConfiguration, "", "age >= 18", 0); } - private void check(String constraints1, int expectedFires, Object... objs) { - check( constraints1, null, expectedFires, objs ); + private void check(KieBaseTestConfiguration kieBaseTestConfiguration, String constraints1, int expectedFires, Object... objs) { + check( kieBaseTestConfiguration, constraints1, null, expectedFires, objs ); } - private void check(String constraints1, String constraints2, int expectedFires, Object... objs) { + private void check(KieBaseTestConfiguration kieBaseTestConfiguration, String constraints1, String constraints2, int expectedFires, Object... objs) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -173,8 +180,9 @@ private void check(String constraints1, String constraints2, int expectedFires, } } - @Test - public void testWithDate() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testWithDate(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-4925 String pkg = "org.drools.compiler.integrationtests.operators"; @@ -206,8 +214,9 @@ public void testWithDate() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testWithIndexedAlpha() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testWithIndexedAlpha(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-5019 String pkg = "org.drools.compiler.integrationtests.operators"; @@ -237,8 +246,9 @@ public void testWithIndexedAlpha() throws Exception { assertThat(ksession2.fireAllRules()).isEqualTo(0); } - @Test - public void testForallWithNotEqualConstraint() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithNotEqualConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-5100 String drl = @@ -256,8 +266,9 @@ public void testForallWithNotEqualConstraint() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testForallWithNotEqualConstraintOnDate() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithNotEqualConstraintOnDate(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-5224 String drl = @@ -316,17 +327,19 @@ public String toString() { } } - @Test - public void testForallWithEmptyListConstraintCombinedWithOrFiring() throws Exception { - checkForallWithEmptyListConstraintCombinedWithOrFiring(true); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithEmptyListConstraintCombinedWithOrFiring(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithEmptyListConstraintCombinedWithOrFiring(kieBaseTestConfiguration, true); } - @Test - public void testForallWithEmptyListConstraintCombinedWithOrNotFiring() throws Exception { - checkForallWithEmptyListConstraintCombinedWithOrFiring(false); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithEmptyListConstraintCombinedWithOrNotFiring(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithEmptyListConstraintCombinedWithOrFiring(kieBaseTestConfiguration, false); } - private void checkForallWithEmptyListConstraintCombinedWithOrFiring(boolean firing) { + private void checkForallWithEmptyListConstraintCombinedWithOrFiring(KieBaseTestConfiguration kieBaseTestConfiguration, boolean firing) { // DROOLS-5682 String drl = @@ -348,39 +361,45 @@ private void checkForallWithEmptyListConstraintCombinedWithOrFiring(boolean firi assertThat(ksession.fireAllRules()).isEqualTo(firing ? 1 : 0); } - @Test - public void testForallWithMultipleConstraints() throws Exception { - checkForallWithComplexExpression("value > 1, value < 10"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithMultipleConstraints(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithComplexExpression(kieBaseTestConfiguration, "value > 1, value < 10"); } - @Test - public void testForallWithAnd() throws Exception { - checkForallWithComplexExpression("value > 1 && value < 10"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithAnd(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithComplexExpression(kieBaseTestConfiguration, "value > 1 && value < 10"); } - @Test - public void testForallWithAndInMultipleConstraints() throws Exception { - checkForallWithComplexExpression("value > 1, value > 2 && value < 10"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithAndInMultipleConstraints(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithComplexExpression(kieBaseTestConfiguration, "value > 1, value > 2 && value < 10"); } - @Test - public void testForallWithOr() throws Exception { - checkForallWithComplexExpression("value < 1 || value > 50"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithOr(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithComplexExpression(kieBaseTestConfiguration, "value < 1 || value > 50"); } - @Test - public void testForallWithIn() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithIn(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-6560 - checkForallWithComplexExpression("value in (1, 43)"); + checkForallWithComplexExpression(kieBaseTestConfiguration, "value in (1, 43)"); } - @Test - public void testForallWithNotIn() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithNotIn(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-6560 - checkForallWithComplexExpression("value not in (1, 42)"); + checkForallWithComplexExpression(kieBaseTestConfiguration, "value not in (1, 42)"); } - private void checkForallWithComplexExpression(String expression) throws Exception { + private void checkForallWithComplexExpression(KieBaseTestConfiguration kieBaseTestConfiguration, String expression) throws Exception { // DROOLS-6469 String drl = "package test\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FormulaTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FormulaTest.java index eea8a94149c..fd2efe890f7 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FormulaTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FormulaTest.java @@ -18,36 +18,28 @@ */ package org.drools.compiler.integrationtests.operators; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class FormulaTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public FormulaTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testConstants() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testConstants(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -74,8 +66,9 @@ public void testConstants() { } } - @Test - public void testBoundField() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBoundField(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromOnlyExecModelTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromOnlyExecModelTest.java index 290736d2d63..c30ab9cce99 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromOnlyExecModelTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromOnlyExecModelTest.java @@ -18,34 +18,28 @@ */ package org.drools.compiler.integrationtests.operators; -import java.util.Collection; import java.util.HashMap; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.model.functions.NativeImageTestUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import static org.drools.compiler.integrationtests.operators.FromTest.testFromSharingCommon; -@RunWith(Parameterized.class) public class FromOnlyExecModelTest { - protected final KieBaseTestConfiguration kieBaseTestConfiguration; - public FromOnlyExecModelTest(KieBaseTestConfiguration kieBaseTestConfiguration1) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration1; + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudOnlyExecModelConfiguration().stream(); } - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudOnlyExecModelConfiguration(); - } - - @Test // KOGITO-3771 - public void testFromSharingWithNativeImage() { + // KOGITO-3771 + @ParameterizedTest + @MethodSource("parameters") + public void testFromSharingWithNativeImage(KieBaseTestConfiguration kieBaseTestConfiguration) { try { NativeImageTestUtil.setNativeImage(); testFromSharingCommon(kieBaseTestConfiguration, new HashMap<>(), 2, 2); @@ -55,8 +49,9 @@ public void testFromSharingWithNativeImage() { } // This test that the node sharing isn't working without lambda externalisation - @Test - public void testFromSharingWithNativeImageWithoutLambdaExternalisation() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromSharingWithNativeImageWithoutLambdaExternalisation(KieBaseTestConfiguration kieBaseTestConfiguration) { try { NativeImageTestUtil.setNativeImage(); HashMap properties = new HashMap<>(); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromTest.java index 212c091146d..de7fe255ae3 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromTest.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -50,11 +49,10 @@ import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.KieServices; @@ -70,18 +68,10 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class FromTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public FromTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } public static class ListsContainer { @@ -97,8 +87,9 @@ public Number getSingleValue() { } - @Test - public void testFromSharing() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromSharing(KieBaseTestConfiguration kieBaseTestConfiguration) { testFromSharingCommon(kieBaseTestConfiguration, new HashMap<>(), 2, 2); } @@ -144,8 +135,9 @@ public static void testFromSharingCommon(KieBaseTestConfiguration kieBaseTestCon } } - @Test - public void testFromSharingWithPropertyReactive() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromSharingWithPropertyReactive(KieBaseTestConfiguration kieBaseTestConfiguration) { // As above but with property reactive as default final String drl = fromSharingRule(); // property reactive as default: @@ -218,8 +210,9 @@ private static ObjectTypeNode insertObjectFireRules(InternalKnowledgeBase kbase, return epn.getObjectTypeNodes().get(new ClassObjectType(ListsContainer.class)); } - @Test - public void testFromSharingWithAccumulate() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromSharingWithAccumulate(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "\n" + @@ -299,8 +292,9 @@ public void testFromSharingWithAccumulate() { } } - @Test - public void testFromWithSingleValue() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithSingleValue(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1243 final String drl = "import " + ListsContainer.class.getCanonicalName() + "\n" + @@ -330,8 +324,9 @@ public void testFromWithSingleValue() { } } - @Test - public void testFromWithSingleValueAndIncompatibleType() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithSingleValueAndIncompatibleType(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1243 final String drl = "import " + ListsContainer.class.getCanonicalName() + "\n" + @@ -358,8 +353,9 @@ public Number getSingleValue() { return this.wrapped; } } - @Test - public void testFromWithInterfaceAndAbstractClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithInterfaceAndAbstractClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Container2.class.getCanonicalName() + "\n" + "import " + Comparable.class.getCanonicalName() + "\n" + @@ -411,8 +407,9 @@ public CustomInteger(final int initialValue) { super(initialValue); } } - @Test - public void testFromWithInterfaceAndConcreteClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithInterfaceAndConcreteClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Container2b.class.getCanonicalName() + "\n" + "import " + CustomIntegerMarker.class.getCanonicalName() + "\n" + @@ -459,8 +456,9 @@ public Integer getSingleValue() { } } - @Test - public void testFromWithInterfaceAndFinalClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithInterfaceAndFinalClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Container3.class.getCanonicalName() + "\n" + "import " + CustomIntegerMarker.class.getCanonicalName() + "\n" + @@ -478,8 +476,9 @@ public void testFromWithInterfaceAndFinalClass() { assertThat(kieBuilder.getResults().getMessages()).isNotEmpty(); } - @Test - public void testBasicFrom() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBasicFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -578,8 +577,10 @@ public List toList(final Object object1, } } - @Test @Ignore - public void testFromWithParams() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Disabled + public void testFromWithParams(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + " \n" + @@ -666,8 +667,9 @@ public Query(String pattern, String column) { } } - @Test - public void testFromWithNewConstructor() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithNewConstructor(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "\n" + @@ -693,8 +695,9 @@ public void testFromWithNewConstructor() { /** * JBRULES-1415 Certain uses of from causes NullPointerException in WorkingMemoryLogger */ - @Test - public void testFromDeclarationWithWorkingMemoryLogger() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromDeclarationWithWorkingMemoryLogger(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheesery.class.getCanonicalName() + ";\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -729,8 +732,9 @@ public void testFromDeclarationWithWorkingMemoryLogger() { } } - @Test - public void testFromArrayIteration() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromArrayIteration(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + DomainObject.class.getCanonicalName() + ";\n" + @@ -766,8 +770,9 @@ public void testFromArrayIteration() { } } - @Test - public void testFromExprFollowedByNot() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromExprFollowedByNot(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -802,8 +807,9 @@ public void testFromExprFollowedByNot() { } } - @Test - public void testFromNestedAccessors() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromNestedAccessors(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Order.class.getCanonicalName() + ";\n" + @@ -843,8 +849,9 @@ public void testFromNestedAccessors() { } } - @Test - public void testFromNodeWithMultipleBetas() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromNodeWithMultipleBetas(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Address.class.getCanonicalName() + ";\n" + @@ -872,8 +879,9 @@ public void testFromNodeWithMultipleBetas() { } } - @Test - public void testFromWithStrictModeOn() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithStrictModeOn(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-3533 final String drl = "import java.util.Map;\n" + @@ -892,17 +900,19 @@ public void testFromWithStrictModeOn() { assertThat(kieBuilder.getResults().getMessages()).isNotEmpty(); } - @Test - public void testJavaImplicitWithFrom() { - testDialectWithFrom("java"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testJavaImplicitWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { + testDialectWithFrom(kieBaseTestConfiguration, "java"); } - @Test - public void testMVELImplicitWithFrom() { - testDialectWithFrom("mvel"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMVELImplicitWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { + testDialectWithFrom(kieBaseTestConfiguration, "mvel"); } - private void testDialectWithFrom(final String dialect) { + private void testDialectWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration, final String dialect) { final String drl = "" + "package org.drools.compiler.test \n" + "import java.util.List \n" + @@ -931,8 +941,9 @@ private void testDialectWithFrom(final String dialect) { } } - @Test - public void testMultipleFroms() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMultipleFroms(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import java.util.List;\n" + @@ -975,8 +986,9 @@ public void testMultipleFroms() { } } - @Test - public void testNetworkBuildErrorAcrossEntryPointsAndFroms() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNetworkBuildErrorAcrossEntryPointsAndFroms(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -1016,8 +1028,9 @@ public void testNetworkBuildErrorAcrossEntryPointsAndFroms() { } } - @Test - public void testUpdateFromCollect() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testUpdateFromCollect(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6504 final String drl = "import " + List.class.getCanonicalName() + ";\n" + @@ -1088,25 +1101,27 @@ public List getValues() { " modify($p){setAge(10)};\n" + "end\n"; - @Test - public void testJoinAndFrom() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testJoinAndFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6821 // Add JoinNode first - runKSessionWithAgendaGroup(RULE_HEAD + + runKSessionWithAgendaGroup(kieBaseTestConfiguration, RULE_HEAD + RULE_WITH_JOIN + RULE_WITH_FROM); } - @Test - public void testFromAndJoin() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromAndJoin(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6821 // Add FromNode first - runKSessionWithAgendaGroup(RULE_HEAD + + runKSessionWithAgendaGroup(kieBaseTestConfiguration, RULE_HEAD + RULE_WITH_FROM + RULE_WITH_JOIN); } - private void runKSessionWithAgendaGroup(String drl) { + private void runKSessionWithAgendaGroup(KieBaseTestConfiguration kieBaseTestConfiguration, String drl) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("from-test", kieBaseTestConfiguration, drl); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InTest.java index f1e28fec62d..dd232dbdf94 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InTest.java @@ -18,36 +18,29 @@ */ package org.drools.compiler.integrationtests.operators; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class InTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - public InTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); - } - - @Test - public void testInOperator() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testInOperator(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"test in\"\n" + @@ -78,8 +71,9 @@ public void testInOperator() { } } - @Test - public void testNegatedIn() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNegatedIn(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"test negated in\"\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InstanceOfTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InstanceOfTest.java index ec125b917ba..1d13b9e8953 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InstanceOfTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InstanceOfTest.java @@ -18,37 +18,29 @@ */ package org.drools.compiler.integrationtests.operators; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.LongAddress; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class InstanceOfTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public InstanceOfTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testInstanceof() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testInstanceof(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-3591 final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + LongAddress.class.getCanonicalName() + ";\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MatchesTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MatchesTest.java index 2019fd37f48..662d6c293d6 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MatchesTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MatchesTest.java @@ -19,40 +19,32 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class MatchesTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public MatchesTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testMatchesMVEL() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMatchesMVEL(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import java.util.Map;\n" + @@ -107,8 +99,9 @@ private String getMatchesDRL() { "end"; } - @Test - public void testMatchesMVEL2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMatchesMVEL2(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("matches-test", kieBaseTestConfiguration, getMatchesDRL()); @@ -125,8 +118,9 @@ public void testMatchesMVEL2() { } } - @Test - public void testMatchesMVEL3() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMatchesMVEL3(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("matches-test", kieBaseTestConfiguration, getMatchesDRL()); @@ -143,8 +137,9 @@ public void testMatchesMVEL3() { } } - @Test - public void testMatchesNotMatchesCheese() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMatchesNotMatchesCheese(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -222,19 +217,21 @@ public void testMatchesNotMatchesCheese() { } } - @Test - public void testNotMatchesSucceeds() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotMatchesSucceeds(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2914: Rule misfires due to "not matches" not working - testMatchesSuccessFail("-..x..xrwx", 0); + testMatchesSuccessFail(kieBaseTestConfiguration, "-..x..xrwx", 0); } - @Test - public void testNotMatchesFails() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotMatchesFails(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2914: Rule misfires due to "not matches" not working - testMatchesSuccessFail("d..x..xrwx", 1); + testMatchesSuccessFail(kieBaseTestConfiguration, "d..x..xrwx", 1); } - private void testMatchesSuccessFail(final String personName, final int expectedFireCount) { + private void testMatchesSuccessFail(KieBaseTestConfiguration kieBaseTestConfiguration, final String personName, final int expectedFireCount) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule NotMatches\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MathTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MathTest.java index b6aeac7eccd..9a305878136 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MathTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MathTest.java @@ -20,39 +20,31 @@ import java.io.Serializable; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.Random; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class MathTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public MathTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testAddition() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAddition(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -118,8 +110,9 @@ public Integer getValue() { } - @Test - public void testNumberComparisons() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNumberComparisons(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + RandomNumber.class.getCanonicalName() + ";\n" + "import " + Guess.class.getCanonicalName() + ";\n" + @@ -197,8 +190,9 @@ public void testNumberComparisons() { } } - @Test - public void testShiftOperator() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShiftOperator(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "dialect \"mvel\"\n" + "rule kickOff\n" + "when\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MemberOfTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MemberOfTest.java index 8bc640f4de1..70da7ae21ca 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MemberOfTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MemberOfTest.java @@ -19,8 +19,8 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Cheesery; @@ -28,31 +28,23 @@ import org.drools.testcoverage.common.model.Pet; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class MemberOfTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public MemberOfTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testMemberOfAndNotMemberOf() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMemberOfAndNotMemberOf(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test;\n" + "\n" + @@ -108,8 +100,9 @@ public void testMemberOfAndNotMemberOf() { } } - @Test - public void testMemberOfWithOr() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMemberOfWithOr(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/NotTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/NotTest.java index 9cdd7ed1a35..02a99666cab 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/NotTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/NotTest.java @@ -20,8 +20,8 @@ import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.base.base.ClassObjectType; import org.drools.core.common.InternalFactHandle; @@ -40,10 +40,9 @@ import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; @@ -51,22 +50,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) public class NotTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public NotTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testLastMemoryEntryNotBug() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testLastMemoryEntryNotBug(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2809 // This occurs when a blocker is the last in the node's memory, or if there is only one fact in the node // And it gets no opportunity to rematch with itself @@ -117,8 +109,9 @@ public void testLastMemoryEntryNotBug() { } } - @Test - public void testNegatedConstaintInNot() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNegatedConstaintInNot(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -140,8 +133,9 @@ public void testNegatedConstaintInNot() { } } - @Test - public void testMissingRootBlockerEquality() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMissingRootBlockerEquality(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6636 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -270,8 +264,9 @@ public String toString() { } } - @Test - public void testNotWithInnerJoin() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotWithInnerJoin(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6652 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -312,8 +307,9 @@ public void testNotWithInnerJoin() { assertThat(results.get(0)).isEqualTo("Paris"); } - @Test - public void testNotWithUnification() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotWithUnification(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-7629 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + 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 be828e8ec5b..16d6b7a28e3 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 @@ -19,8 +19,8 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.core.common.InternalFactHandle; import org.drools.testcoverage.common.model.Cheese; @@ -32,10 +32,9 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.definition.type.FactType; @@ -44,22 +43,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class OrTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public OrTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testOr() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOr(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -105,8 +97,9 @@ public void testOr() { } } - @Test - public void testOrCE() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrCE(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -148,8 +141,9 @@ public void testOrCE() { } } - @Test - public void testOrCEFollowedByEval() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrCEFollowedByEval(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + FactA.class.getCanonicalName() + ";\n" + "import " + FactB.class.getCanonicalName() + ";\n" + @@ -184,8 +178,9 @@ public void testOrCEFollowedByEval() { } } - @Test - public void testOrWithAndUsingNestedBindings() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrWithAndUsingNestedBindings(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List mlist\n" + @@ -268,8 +263,9 @@ public void testOrWithAndUsingNestedBindings() { } } - @Test - public void testOrWithBinding() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrWithBinding(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -314,8 +310,9 @@ public void testOrWithBinding() { } } - @Test - public void testOrWithFrom() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2274: Rule does not fire as expected using deep object model and nested 'or' clause final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Order.class.getCanonicalName() + ";\n" @@ -354,8 +351,9 @@ public void testOrWithFrom() { } } - @Test - public void testOrWithReturnValueRestriction() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrWithReturnValueRestriction(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -385,8 +383,9 @@ public void testOrWithReturnValueRestriction() { } } - @Test - public void testBindingsWithOr() throws InstantiationException, IllegalAccessException { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBindingsWithOr(KieBaseTestConfiguration kieBaseTestConfiguration) throws InstantiationException, IllegalAccessException { // JBRULES-2917: matching of field==v1 || field==v2 breaks when variable binding is added final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "declare Assignment\n" + @@ -424,8 +423,9 @@ public void testBindingsWithOr() throws InstantiationException, IllegalAccessExc } } - @Test - public void testConstraintConnectorOr() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testConstraintConnectorOr(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -478,8 +478,9 @@ public void testConstraintConnectorOr() { } } - @Test - public void testVariableBindingWithOR() throws Exception{ + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testVariableBindingWithOR(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception{ // JBRULES-3390 final String drl1 = "package org.drools.compiler.integrationtests.operators; \n" + "declare A\n" + @@ -549,8 +550,9 @@ public void testVariableBindingWithOR() throws Exception{ } } - @Test - public void testRestrictionsWithOr() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRestrictionsWithOr(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2203: NullPointerException When Using Conditional Element "or" in LHS Together with a Return Value Restriction final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -577,8 +579,9 @@ public void testRestrictionsWithOr() { } } - @Test - public void testEmptyIdentifier() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEmptyIdentifier(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -635,8 +638,9 @@ public void testEmptyIdentifier() { } } - @Test - public void testIndexAfterOr() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testIndexAfterOr(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1604 final String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -674,8 +678,9 @@ public void testIndexAfterOr() { } } - @Test - public void testOrWithDifferenceOffsetsForConsequence() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrWithDifferenceOffsetsForConsequence(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1604 final String drl = "import " + Person.class.getCanonicalName() + ";" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/SoundsLikeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/SoundsLikeTest.java index d44158f5cc3..0ff2098af41 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/SoundsLikeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/SoundsLikeTest.java @@ -18,40 +18,31 @@ */ package org.drools.compiler.integrationtests.operators; -import java.util.Collection; import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class SoundsLikeTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public SoundsLikeTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testSoundsLike() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSoundsLike(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2991: Operator soundslike is broken - testFiredRules("package org.drools.compiler.integrationtests.operators;\n" + + testFiredRules(kieBaseTestConfiguration, "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule SoundsLike\n" + "when\n" + @@ -63,11 +54,12 @@ public void testSoundsLike() { "Bob"); } - @Test - public void testSoundsLikeNegativeCase() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSoundsLikeNegativeCase(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2991: Operator soundslike is broken - testFiredRules("package org.drools.compiler.integrationtests.operators;\n" + + testFiredRules(kieBaseTestConfiguration, "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule SoundsLike\n" + "when\n" + @@ -78,11 +70,12 @@ public void testSoundsLikeNegativeCase() { "Mark"); } - @Test - public void testNotSoundsLike() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotSoundsLike(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2991: Operator soundslike is broken - testFiredRules("package org.drools.compiler.integrationtests.operators;\n" + + testFiredRules(kieBaseTestConfiguration, "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule NotSoundsLike\n" + "when\n" + @@ -93,11 +86,12 @@ public void testNotSoundsLike() { "John"); } - @Test - public void testNotSoundsLikeNegativeCase() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotSoundsLikeNegativeCase(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2991: Operator soundslike is broken - testFiredRules("package org.drools.compiler.integrationtests.operators;\n" + + testFiredRules(kieBaseTestConfiguration, "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule NotSoundsLike\n" + "when\n" + @@ -108,7 +102,8 @@ public void testNotSoundsLikeNegativeCase() { "Bob"); } - private void testFiredRules(final String rule, + private void testFiredRules(KieBaseTestConfiguration kieBaseTestConfiguration, + final String rule, final int firedRulesCount, final String... persons) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("sounds-like-test", diff --git a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/TestParametersUtil2.java b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/TestParametersUtil2.java new file mode 100644 index 00000000000..46011c70122 --- /dev/null +++ b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/TestParametersUtil2.java @@ -0,0 +1,324 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.testcoverage.common.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.drools.model.codegen.ExecutableModelProject; + +/** + * Utility class that holds default tests parameters. + */ +public final class TestParametersUtil2 { + + private static final boolean TEST_WITH_ALPHA_NETWORK = Boolean.valueOf(System.getProperty("alphanetworkCompilerEnabled")); + + /** + * Get all KieBaseConfigurations for tests based on specified engine configurations. + * @param engineConfigurations Engine configurations for tests. They should contain every configuration that + * should be tested. What is not specified, is not returned as part of KieBaseConfigurations. + * @return + */ + public static Collection getKieBaseConfigurations(final EngineTestConfiguration... engineConfigurations) { + if (engineConfigurations == null || engineConfigurations.length == 0) { + throw new IllegalArgumentException("No parameters specified! Please provide some required parameters"); + } + final Collection parameters = new ArrayList<>(); + for (final KieBaseTestConfiguration testConfiguration : KieBaseTestConfiguration.values()) { + if (isTestConfigurationValid(testConfiguration, engineConfigurations)) { + parameters.add(testConfiguration); + } + } + return parameters; + } + + /** + * Checks, if a test configuration matches specified engine configurations. Take note that the engine configurations + * can contain contradictory configurations on first sight. This is because they should include all + * configurations requested for tests. E.g. a test could require both combinations with executable model on and also off. + * + * @param testConfiguration A configuration that is checked if it matches the specified engine configurations + * @param engineConfigurations Specified engine configurations for tests + * @return true, if the test configuration is valid for specified engine configurations, otherwise false + */ + private static boolean isTestConfigurationValid(final KieBaseTestConfiguration testConfiguration, + final EngineTestConfiguration[] engineConfigurations) { + final Set engineTestConfigurationSet = new HashSet<>(Arrays.asList(engineConfigurations)); + + if (testConfiguration.isImmutable() && !engineTestConfigurationSet.contains(EngineTestConfiguration.IMMUTABLE_KIE_BASE)) { + return false; + } + + if (testConfiguration.isStreamMode() && !engineTestConfigurationSet.contains(EngineTestConfiguration.STREAM_MODE)) { + return false; + } + + if (!testConfiguration.isStreamMode() && !engineTestConfigurationSet.contains(EngineTestConfiguration.CLOUD_MODE)) { + return false; + } + + if (testConfiguration.isIdentity() && !engineTestConfigurationSet.contains(EngineTestConfiguration.IDENTITY_MODE)) { + return false; + } + + if (!testConfiguration.isIdentity() && !engineTestConfigurationSet.contains(EngineTestConfiguration.EQUALITY_MODE)) { + return false; + } + + if (testConfiguration.useAlphaNetworkCompiler() + && !engineTestConfigurationSet.contains(EngineTestConfiguration.ALPHA_NETWORK_COMPILER_TRUE)) { + return false; + } + + if (!testConfiguration.useAlphaNetworkCompiler() + && !engineTestConfigurationSet.contains(EngineTestConfiguration.ALPHA_NETWORK_COMPILER_FALSE)) { + return false; + } + + if (!testConfiguration.getExecutableModelProjectClass().isPresent() + && !engineTestConfigurationSet.contains(EngineTestConfiguration.EXECUTABLE_MODEL_OFF)) { + return false; + } + + if (testConfiguration.getExecutableModelProjectClass().isPresent()) { + if (testConfiguration.getExecutableModelProjectClass().get().equals(ExecutableModelProject.class) + && !engineTestConfigurationSet.contains(EngineTestConfiguration.EXECUTABLE_MODEL_PATTERN)) { + return false; + } + } + return true; + } + + /** + * Prepares collection of KieBaseTestConfiguration. + * @return Collection of KieBaseTestConfiguration for parameterized tests. + */ + public static Collection getKieBaseConfigurations() { + final List engineTestConfigurations = Arrays.stream(EngineTestConfiguration.values()) + .filter(config -> (TEST_WITH_ALPHA_NETWORK || config != EngineTestConfiguration.ALPHA_NETWORK_COMPILER_TRUE) + && config != EngineTestConfiguration.EQUALITY_MODE + && config != EngineTestConfiguration.IMMUTABLE_KIE_BASE) + .collect(Collectors.toList()); + return getKieBaseConfigurations(engineTestConfigurations.toArray(new EngineTestConfiguration[]{})); + } + + /** + * Prepares collection of stream KieBaseTestConfiguration. + * @return Collection of KieBaseTestConfiguration for parameterized tests. + * @param testAlsoExecutableModel If true, the configurations returned contain configurations with executable model. + */ + public static Collection getKieBaseStreamConfigurations(final boolean testAlsoExecutableModel) { + return getKieBaseStreamOrCloudConfigurations(EngineTestConfiguration.STREAM_MODE, testAlsoExecutableModel); + } + + /** + * Prepares collection of stream KieBaseTestConfiguration. + * @return Collection of KieBaseTestConfiguration for parameterized tests. + * @param testAlsoExecutableModel If true, the configurations returned contain configurations with executable model. + * @param testEquality If true, the configurations returned contain configurations with EQUALITY_MODE instead of IDENTITY_MODE. + */ + public static Collection getKieBaseStreamConfigurations(final boolean testAlsoExecutableModel, final boolean testEquality) { + return getKieBaseStreamOrCloudConfigurations(EngineTestConfiguration.STREAM_MODE, testAlsoExecutableModel, testEquality); + } + + /** + * Prepares collection of stream KieBaseTestConfiguration. + * @return Collection of KieBaseTestConfiguration for parameterized tests. + * @param testAlsoExecutableModel If true, the configurations returned contain configurations with executable model. + */ + public static Collection getKieBaseCloudConfigurations(final boolean testAlsoExecutableModel) { + return getKieBaseStreamOrCloudConfigurations(EngineTestConfiguration.CLOUD_MODE, testAlsoExecutableModel); + } + + /** + * Prepares collection of stream KieBaseTestConfiguration. + * @return Collection of KieBaseTestConfiguration for parameterized tests. + * @param testAlsoExecutableModel If true, the configurations returned contain configurations with executable model. + * @param testEquality If true, the configurations returned contain configurations with EQUALITY_MODE instead of IDENTITY_MODE. + */ + public static Collection getKieBaseCloudConfigurations(final boolean testAlsoExecutableModel, final boolean testEquality) { + return getKieBaseStreamOrCloudConfigurations(EngineTestConfiguration.CLOUD_MODE, testAlsoExecutableModel, testEquality); + } + + private static Collection getKieBaseStreamOrCloudConfigurations(final EngineTestConfiguration streamOrCloudConfig, + final boolean testAlsoExecutableModel) { + // Testing just IDENTITY_MODE by default, leaving EQUALITY_MODE to specialized tests. + return getKieBaseStreamOrCloudConfigurations(streamOrCloudConfig, testAlsoExecutableModel, false); + } + + private static Collection getKieBaseStreamOrCloudConfigurations(final EngineTestConfiguration streamOrCloudConfig, + final boolean testAlsoExecutableModel, final boolean testEquality) { + final List engineTestConfigurations = new ArrayList<>(); + engineTestConfigurations.add(streamOrCloudConfig); + if (testEquality) { + engineTestConfigurations.add(EngineTestConfiguration.EQUALITY_MODE); + } else { + engineTestConfigurations.add(EngineTestConfiguration.IDENTITY_MODE); + } + engineTestConfigurations.add(EngineTestConfiguration.EXECUTABLE_MODEL_OFF); + engineTestConfigurations.add(EngineTestConfiguration.ALPHA_NETWORK_COMPILER_FALSE); + + if (TEST_WITH_ALPHA_NETWORK) { + engineTestConfigurations.add(EngineTestConfiguration.ALPHA_NETWORK_COMPILER_TRUE); + } + + if (testAlsoExecutableModel) { + engineTestConfigurations.add(EngineTestConfiguration.EXECUTABLE_MODEL_PATTERN); + } + + return getKieBaseConfigurations(engineTestConfigurations.toArray(new EngineTestConfiguration[]{})); + } + + public static Collection getKieBaseCloudOnlyExecModelConfiguration() { + final List engineTestConfigurations = new ArrayList<>(); + engineTestConfigurations.add(EngineTestConfiguration.CLOUD_MODE); + engineTestConfigurations.add(EngineTestConfiguration.IDENTITY_MODE); + engineTestConfigurations.add(EngineTestConfiguration.ALPHA_NETWORK_COMPILER_FALSE); + engineTestConfigurations.add(EngineTestConfiguration.EXECUTABLE_MODEL_PATTERN); + + return getKieBaseConfigurations(engineTestConfigurations.toArray(new EngineTestConfiguration[]{})); + } + + /** + * Prepares various combinations of KieBaseTestConfiguration and KieSessionTestConfiguration. + * @return Collection of combinations for parameterized tests. + */ + public static Collection getKieBaseAndKieSessionConfigurations() { + final Collection parameters = new ArrayList<>(); + // These are wrapped in an array, because these are parameters for JUnit Parameterized runner. + Collection kieBaseConfigurations = getKieBaseCloudConfigurations(true); + for (final KieSessionTestConfiguration kieSessionTestConfiguration : KieSessionTestConfiguration.values()) { + for (final KieBaseTestConfiguration kieBaseConfigWrapped : kieBaseConfigurations) { + parameters.add(new Object[]{kieBaseConfigWrapped, kieSessionTestConfiguration}); + } + } + + kieBaseConfigurations = getKieBaseStreamConfigurations(true); + for (final KieBaseTestConfiguration kieBaseConfigWrapped : kieBaseConfigurations) { + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_REALTIME}); + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_PSEUDO}); + } + + return parameters; + } + + /** + * Prepares various combinations of KieBaseTestConfiguration and KieSessionTestConfiguration. + * Use only stateful kie sessions. + * @return Collection of combinations for parameterized tests. + */ + public static Collection getKieBaseAndStatefulKieSessionConfigurations() { + final Collection parameters = new ArrayList<>(); + final Collection kieBaseConfigurations = getKieBaseConfigurations(); + for (final KieBaseTestConfiguration kieBaseConfigWrapped : kieBaseConfigurations) { + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_REALTIME}); + if ((kieBaseConfigWrapped).isStreamMode()) { + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_PSEUDO}); + } + } + + return parameters; + } + + /** + * Prepares various combinations of KieBaseTestConfiguration and KieSessionTestConfiguration. + * Use only stream kie bases and stateful kie sessions. + * @return Collection of combinations for parameterized tests. + */ + public static Collection getStreamKieBaseAndStatefulKieSessionConfigurations() { + final Collection parameters = new ArrayList<>(); + final Collection kieBaseConfigurations = getKieBaseStreamConfigurations(true); + for (final KieBaseTestConfiguration kieBaseConfigWrapped : kieBaseConfigurations) { + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_REALTIME}); + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_PSEUDO}); + } + + return parameters; + } + + /** + * Returns KieBaseTestConfiguration instance with Equality while other properties are the same as original. + */ + public static KieBaseTestConfiguration getEqualityInstanceOf(KieBaseTestConfiguration orig) { + for (final KieBaseTestConfiguration config : KieBaseTestConfiguration.values()) { + if (!config.isIdentity() + && config.isStreamMode() == orig.isStreamMode() + && config.useAlphaNetworkCompiler() == orig.useAlphaNetworkCompiler() + && config.getExecutableModelProjectClass().equals(orig.getExecutableModelProjectClass())) { + return config; + } + } + throw new RuntimeException("Cannot find Equality instance of " + orig); + } + + /** + * Returns KieBaseTestConfiguration instance with Identity while other properties are the same as original. + */ + public static KieBaseTestConfiguration getIdentityInstanceOf(KieBaseTestConfiguration orig) { + for (final KieBaseTestConfiguration config : KieBaseTestConfiguration.values()) { + if (config.isIdentity() + && config.isStreamMode() == orig.isStreamMode() + && config.useAlphaNetworkCompiler() == orig.useAlphaNetworkCompiler() + && config.getExecutableModelProjectClass().equals(orig.getExecutableModelProjectClass())) { + return config; + } + } + throw new RuntimeException("Cannot find Identity instance of " + orig); + } + + /** + * Returns KieBaseTestConfiguration instance with Stream while other properties are the same as original. + */ + public static KieBaseTestConfiguration getStreamInstanceOf(KieBaseTestConfiguration orig) { + for (final KieBaseTestConfiguration config : KieBaseTestConfiguration.values()) { + if (config.isStreamMode() + && config.isIdentity() == orig.isIdentity() + && config.useAlphaNetworkCompiler() == orig.useAlphaNetworkCompiler() + && config.getExecutableModelProjectClass().equals(orig.getExecutableModelProjectClass())) { + return config; + } + } + throw new RuntimeException("Cannot find Stream instance of " + orig); + } + + /** + * Returns KieBaseTestConfiguration instance with Cloud while other properties are the same as original. + */ + public static KieBaseTestConfiguration getCloudInstanceOf(KieBaseTestConfiguration orig) { + for (final KieBaseTestConfiguration config : KieBaseTestConfiguration.values()) { + if (!config.isStreamMode() + && config.isIdentity() == orig.isIdentity() + && config.useAlphaNetworkCompiler() == orig.useAlphaNetworkCompiler() + && config.getExecutableModelProjectClass().equals(orig.getExecutableModelProjectClass())) { + return config; + } + } + throw new RuntimeException("Cannot find Cloud instance of " + orig); + } + + private TestParametersUtil2() { + // Creating instances of util classes should not be possible. + } +} From 20d17bd0291eafec3521c29d5cac074ca442ddd8 Mon Sep 17 00:00:00 2001 From: Gabriele Cardosi Date: Wed, 23 Oct 2024 10:42:21 +0200 Subject: [PATCH 141/141] [incubator-kie-issues#1546] Fix DMN TCK range equality test failures for unary test ranges (#6134) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Introduce undefined boundaries for range instances. Signed-off-by: Tibor Zimányi * Update inclusion and equality methods for FEEL range. Signed-off-by: Tibor Zimányi * Fix compiled FEEL scenarios with ranges. * Restore FEELRangesTest. * Add RangeImpl unit tests. * [range-problems-gc] WIP * [range-problems-gc] WIP * [incubator-kie-issues#1546] Add UndefinedValueComparable UndefinedValueNode * [incubator-kie-issues#1546] Fixing tests - WIP * [incubator-kie-issues#1546] Fixing tests - WIP * [incubator-kie-issues#1546] Fixing tests * [incubator-kie-issues#1546] Fixing tests --------- Signed-off-by: Tibor Zimányi Co-authored-by: Tibor Zimányi Co-authored-by: Gabriele-Cardosi --- .../kie/dmn/feel/parser/feel11/FEEL_1_1.g4 | 9 ++- .../codegen/feel11/ASTCompilerHelper.java | 6 ++ .../codegen/feel11/ASTCompilerVisitor.java | 7 +++ .../codegen/feel11/ASTUnaryTestTransform.java | 6 ++ .../codegen/feel11/DMNCodegenConstants.java | 2 + .../dmn/feel/lang/ast/ASTBuilderFactory.java | 4 ++ .../org/kie/dmn/feel/lang/ast/RangeNode.java | 11 +++- .../dmn/feel/lang/ast/UndefinedValueNode.java | 39 ++++++++++++ .../org/kie/dmn/feel/lang/ast/Visitor.java | 1 + .../visitor/ASTHeuristicCheckerVisitor.java | 7 +-- .../lang/ast/visitor/DefaultedVisitor.java | 6 ++ .../feel/parser/feel11/ASTBuilderVisitor.java | 13 ++-- .../java/org/kie/dmn/feel/runtime/Range.java | 2 + .../feel/runtime/functions/RangeFunction.java | 1 + .../kie/dmn/feel/runtime/impl/RangeImpl.java | 60 ++++++++++++++++--- .../impl/UndefinedValueComparable.java | 43 +++++++++++++ .../org/kie/dmn/feel/util/EvalHelper.java | 4 ++ .../java/org/kie/dmn/feel/util/TypeUtil.java | 47 ++++++++++++--- .../marshaller/FEELCodeMarshallerTest.java | 12 +++- .../FEELCodeMarshallerUnmarshallTest.java | 14 ++++- .../parser/feel11/FEELParserSeverityTest.java | 2 +- .../kie/dmn/feel/runtime/FEELRangesTest.java | 12 +++- .../dmn/feel/runtime/impl/RangeImplTest.java | 38 ++++++++++++ .../validation/dtanalysis/DMNDTAnalyser.java | 10 ++-- .../validation/dtanalysis/model/Interval.java | 3 +- 25 files changed, 317 insertions(+), 42 deletions(-) create mode 100644 kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/UndefinedValueNode.java create mode 100644 kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/UndefinedValueComparable.java diff --git a/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 b/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 index 9f04edc4532..09eb8cb081a 100644 --- a/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 +++ b/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 @@ -324,7 +324,8 @@ literal | BooleanLiteral #boolLiteral | atLiteral #atLiteralLabel | StringLiteral #stringLiteral - | NULL #nullLiteral + | NULL #nullLiteral + | UNDEFINEDVALUE #undefined ; atLiteral @@ -340,6 +341,7 @@ BooleanLiteral | FALSE ; + /************************** * OTHER CONSTRUCTS **************************/ @@ -463,6 +465,7 @@ reusableKeywords | BETWEEN | NOT | NULL + | UNDEFINEDVALUE | TRUE | FALSE ; @@ -536,6 +539,10 @@ NULL : 'null' ; +UNDEFINEDVALUE + : 'undefined' + ; + TRUE : 'true' ; diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java index dc87cd9e5d7..b2b5f1bf59d 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java @@ -79,6 +79,7 @@ import org.kie.dmn.feel.lang.ast.TypeNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.impl.JavaBackedType; import org.kie.dmn.feel.lang.impl.MapBackedType; import org.kie.dmn.feel.lang.types.AliasFEELType; @@ -144,6 +145,7 @@ import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.TYPE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.UNARYTESTLISTNODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.UNARYTESTNODE_CT; +import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.UNDEFINEDVALUENODE_CT; import static org.kie.dmn.feel.util.CodegenUtils.getEnumExpression; import static org.kie.dmn.feel.util.CodegenUtils.getListExpression; import static org.kie.dmn.feel.util.CodegenUtils.getStringLiteralExpr; @@ -488,6 +490,10 @@ public BlockStmt add(UnaryTestNode n) { n.getText()); } + public BlockStmt add(UndefinedValueNode n) { + return addVariableDeclaratorWithObjectCreation(UNDEFINEDVALUENODE_CT, NodeList.nodeList()); + } + public String getLastVariableName() { return lastVariableName.get(); } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java index a4bef5554d3..ffa86fc0613 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java @@ -56,6 +56,7 @@ import org.kie.dmn.feel.lang.ast.TemporalConstantNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.ast.Visitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -290,6 +291,12 @@ public BlockStmt visit(UnaryTestNode n) { return compilerHelper.add(n); } + @Override + public BlockStmt visit(UndefinedValueNode n) { + LOGGER.trace("visit {}", n); + return compilerHelper.add(n); + } + public String getLastVariableName() { LOGGER.trace("getLastVariableName"); return compilerHelper.getLastVariableName(); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTUnaryTestTransform.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTUnaryTestTransform.java index 133531034e8..3f2ea6e9077 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTUnaryTestTransform.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTUnaryTestTransform.java @@ -37,6 +37,7 @@ import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.ast.visitor.DefaultedVisitor; public class ASTUnaryTestTransform extends DefaultedVisitor { @@ -136,6 +137,11 @@ public UnaryTestSubexpr visit(QualifiedNameNode n) { } } + @Override + public UnaryTestSubexpr visit(UndefinedValueNode n) { + return new SimpleUnaryExpression(n); + } + private UnaryTestSubexpr propagateWildcard(ASTNode n) { return Arrays.stream(n.getChildrenNode()).map(e -> e.accept(this)).anyMatch(UnaryTestSubexpr::isWildcard) ? new WildCardUnaryExpression((BaseNode) n) : new SimpleUnaryExpression((BaseNode) n); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java index f5db4e41509..4b214951b05 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java @@ -57,6 +57,7 @@ import org.kie.dmn.feel.lang.ast.TemporalConstantNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.impl.JavaBackedType; import org.kie.dmn.feel.lang.impl.MapBackedType; import org.kie.dmn.feel.lang.types.AliasFEELType; @@ -172,6 +173,7 @@ public class DMNCodegenConstants { parseClassOrInterfaceType(UnaryTestListNode.class.getCanonicalName()); public static final ClassOrInterfaceType UNARYTESTNODE_CT = parseClassOrInterfaceType(UnaryTestNode.class.getCanonicalName()); + public static final ClassOrInterfaceType UNDEFINEDVALUENODE_CT = parseClassOrInterfaceType(UndefinedValueNode.class.getCanonicalName()); private DMNCodegenConstants() { } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/ASTBuilderFactory.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/ASTBuilderFactory.java index 95a1f5c54a3..8908a3a9dde 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/ASTBuilderFactory.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/ASTBuilderFactory.java @@ -43,6 +43,10 @@ public static NullNode newNullNode(ParserRuleContext ctx) { return new NullNode( ctx ); } + public static UndefinedValueNode newUndefinedValueNode() { + return new UndefinedValueNode(); + } + public static StringNode newStringNode(ParserRuleContext ctx) { return new StringNode( ctx ); } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeNode.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeNode.java index c64317ad43d..0d44d025d79 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeNode.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeNode.java @@ -28,6 +28,7 @@ import org.kie.dmn.feel.lang.types.impl.ComparablePeriod; import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.impl.RangeImpl; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; import org.kie.dmn.feel.util.Msg; public class RangeNode @@ -113,13 +114,17 @@ public Range evaluate(EvaluationContext ctx) { Type sType = BuiltInType.determineTypeFromInstance(s); Type eType = BuiltInType.determineTypeFromInstance(e); - if (s != null && e != null && sType != eType && !s.getClass().isAssignableFrom(e.getClass())) { + boolean withUndefined = s instanceof UndefinedValueComparable || e instanceof UndefinedValueComparable; + if (s != null && e != null && + !withUndefined && + sType != eType && + !s.getClass().isAssignableFrom(e.getClass())) { ctx.notifyEvt( astEvent(Severity.ERROR, Msg.createMessage(Msg.X_TYPE_INCOMPATIBLE_WITH_Y_TYPE, "Start", "End"))); return null; } - Comparable start = convertToComparable( ctx, s ); - Comparable end = convertToComparable( ctx, e ); + Comparable start = s instanceof UndefinedValueComparable ? (Comparable) s : convertToComparable(ctx, s ); + Comparable end = e instanceof UndefinedValueComparable ? (Comparable) e : convertToComparable( ctx, e ); return new RangeImpl( lowerBound==IntervalBoundary.OPEN ? Range.RangeBoundary.OPEN : Range.RangeBoundary.CLOSED, start, diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/UndefinedValueNode.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/UndefinedValueNode.java new file mode 100644 index 00000000000..dd423acdb56 --- /dev/null +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/UndefinedValueNode.java @@ -0,0 +1,39 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.feel.lang.ast; + +import org.kie.dmn.feel.lang.EvaluationContext; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; + +public class UndefinedValueNode + extends BaseNode { + + public UndefinedValueNode() { } + + @Override + public Object evaluate(EvaluationContext ctx) { + return new UndefinedValueComparable(); + } + + @Override + public T accept(Visitor v) { + return v.visit(this); + } + +} diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java index 82775356454..1158d134b07 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java @@ -60,4 +60,5 @@ default T visit(TemporalConstantNode n) { T visit(UnaryTestListNode n); T visit(UnaryTestNode n); + T visit(UndefinedValueNode n); } \ No newline at end of file diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/ASTHeuristicCheckerVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/ASTHeuristicCheckerVisitor.java index 2d39b7d19da..5927d3e0c0d 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/ASTHeuristicCheckerVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/ASTHeuristicCheckerVisitor.java @@ -19,16 +19,15 @@ package org.kie.dmn.feel.lang.ast.visitor; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.api.feel.runtime.events.FEELEvent.Severity; import org.kie.dmn.feel.lang.ast.ASTNode; import org.kie.dmn.feel.lang.ast.InfixOpNode; -import org.kie.dmn.feel.lang.ast.NullNode; import org.kie.dmn.feel.lang.ast.RangeNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.runtime.events.ASTHeuristicCheckEvent; import org.kie.dmn.feel.util.Msg; @@ -63,8 +62,8 @@ public List visit(UnaryTestNode n) { @Override public List visit(RangeNode n) { - if ((n.getStart() instanceof NullNode && n.getEnd() instanceof RangeNode) - || (n.getStart() instanceof RangeNode && n.getEnd() instanceof NullNode)) { + if ((n.getStart() instanceof UndefinedValueNode && n.getEnd() instanceof RangeNode) + || (n.getStart() instanceof RangeNode && n.getEnd() instanceof UndefinedValueNode)) { return List.of(new ASTHeuristicCheckEvent(Severity.WARN, Msg.createMessage(Msg.UT_OF_UT, n.getText()), n)); } return defaultVisit(n); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java index 6eb2d6b79d5..1b55497e2f9 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java @@ -54,6 +54,7 @@ import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.ast.Visitor; public abstract class DefaultedVisitor implements Visitor { @@ -240,4 +241,9 @@ public T visit(FunctionTypeNode n) { return defaultVisit(n); } + @Override + public T visit(UndefinedValueNode n) { + return defaultVisit(n); + } + } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java index 295b9fe539f..64465e00d0e 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java @@ -113,6 +113,11 @@ public BaseNode visitNullLiteral(FEEL_1_1Parser.NullLiteralContext ctx) { return ASTBuilderFactory.newNullNode( ctx ); } + @Override + public BaseNode visitUndefined(FEEL_1_1Parser.UndefinedContext ctx) { + return ASTBuilderFactory.newUndefinedValueNode(); + } + @Override public BaseNode visitStringLiteral(FEEL_1_1Parser.StringLiteralContext ctx) { return ASTBuilderFactory.newStringNode( ctx ); @@ -188,13 +193,13 @@ public BaseNode visitPositiveUnaryTestIneqInterval(FEEL_1_1Parser.PositiveUnaryT String op = ctx.op.getText(); switch (UnaryOperator.determineOperator(op)) { case GT: - return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, value, ASTBuilderFactory.newNullNode(ctx), RangeNode.IntervalBoundary.OPEN); + return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, value, ASTBuilderFactory.newUndefinedValueNode(), RangeNode.IntervalBoundary.OPEN); case GTE: - return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.CLOSED, value, ASTBuilderFactory.newNullNode(ctx), RangeNode.IntervalBoundary.OPEN); + return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.CLOSED, value, ASTBuilderFactory.newUndefinedValueNode(), RangeNode.IntervalBoundary.OPEN); case LT: - return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, ASTBuilderFactory.newNullNode(ctx), value, RangeNode.IntervalBoundary.OPEN); + return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, ASTBuilderFactory.newUndefinedValueNode(), value, RangeNode.IntervalBoundary.OPEN); case LTE: - return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, ASTBuilderFactory.newNullNode(ctx), value, RangeNode.IntervalBoundary.CLOSED); + return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, ASTBuilderFactory.newUndefinedValueNode(), value, RangeNode.IntervalBoundary.CLOSED); default: throw new UnsupportedOperationException("by the parser rule FEEL grammar rule 7.a for range syntax should not have determined the operator " + op); } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/Range.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/Range.java index 39666b6c858..3ca1ec857b7 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/Range.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/Range.java @@ -34,4 +34,6 @@ enum RangeBoundary { Boolean includes(Object param); + boolean isWithUndefined(); + } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/RangeFunction.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/RangeFunction.java index 9dab904aca7..5e37b769bca 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/RangeFunction.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/RangeFunction.java @@ -134,6 +134,7 @@ public FEELFnResult invoke(@ParameterName("from") String from) { return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "from", "endpoints must be of equivalent types")); } + // Boundary values need to be always defined in range string. They can be undefined only in unary test, that represents range, e.g. (<10). return FEELFnResult.ofResult(new RangeImpl(startBoundary, (Comparable) left, (Comparable) right, endBoundary)); } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/RangeImpl.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/RangeImpl.java index f16ee87dd3a..51893062d91 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/RangeImpl.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/RangeImpl.java @@ -23,6 +23,11 @@ import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.util.BooleanEvalHelper; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.GT; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.GTE; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.LT; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.LTE; + public class RangeImpl implements Range { @@ -30,7 +35,7 @@ public class RangeImpl private RangeBoundary highBoundary; private Comparable lowEndPoint; private Comparable highEndPoint; - + private boolean withUndefined = false; public RangeImpl() { } @@ -40,6 +45,7 @@ public RangeImpl(RangeBoundary lowBoundary, Comparable lowEndPoint, Comparable h this.highBoundary = highBoundary; this.lowEndPoint = lowEndPoint; this.highEndPoint = highEndPoint; + withUndefined = lowEndPoint instanceof UndefinedValueComparable || highEndPoint instanceof UndefinedValueComparable; } @Override @@ -67,21 +73,30 @@ public Boolean includes(Object param) { if (param == null) { return null; } - if (lowEndPoint == null) { - if (highEndPoint == null) { + if (lowEndPoint == null || lowEndPoint instanceof UndefinedValueComparable) { + if (highEndPoint == null || highEndPoint instanceof UndefinedValueComparable) { return null; - } else { + } else if (lowEndPoint != null) { // it means it is UndefinedValueComparable return negInfRangeIncludes(param); + } else { + return false; } } else { - if (highEndPoint == null) { + if (highEndPoint instanceof UndefinedValueComparable) { return posInfRangeIncludes(param); - } else { + } else if (highEndPoint != null) { return finiteRangeIncludes(param); + } else { + return false; } } } + @Override + public boolean isWithUndefined() { + return withUndefined; + } + private Boolean finiteRangeIncludes(Object param) { if (lowBoundary == RangeBoundary.OPEN && highBoundary == RangeBoundary.OPEN) { return bothOrThrow(compare(lowEndPoint, param, (l, r) -> l.compareTo(r) < 0) , compare(highEndPoint, param, (l, r) -> l.compareTo(r) > 0), param); @@ -154,9 +169,36 @@ public int hashCode() { @Override public String toString() { + return withUndefined ? withUndefinedtoString() : withoutUndefinedtoString(); + } + + private String withoutUndefinedtoString() { return (lowBoundary == RangeBoundary.OPEN ? "(" : "[") + - " " + lowEndPoint + - " .. " + highEndPoint + - " " + ( highBoundary == RangeBoundary.OPEN ? ")" : "]" ); + " " + lowEndPoint + + " .. " + highEndPoint + + " " + ( highBoundary == RangeBoundary.OPEN ? ")" : "]" ); + } + + private String withUndefinedtoString() { + StringBuilder sb = new StringBuilder("( "); + if (lowEndPoint instanceof UndefinedValueComparable) { + if (highBoundary == RangeBoundary.OPEN) { + sb.append(LT.symbol); + } else { + sb.append(LTE.symbol); + } + sb.append(" "); + sb.append(highEndPoint); + } else if (highEndPoint instanceof UndefinedValueComparable) { + if (lowBoundary == RangeBoundary.OPEN) { + sb.append(GT.symbol); + } else { + sb.append(GTE.symbol); + } + sb.append(" "); + sb.append(lowEndPoint); + } + sb.append(" )"); + return sb.toString(); } } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/UndefinedValueComparable.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/UndefinedValueComparable.java new file mode 100644 index 00000000000..240f7c98dae --- /dev/null +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/UndefinedValueComparable.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.feel.runtime.impl; + +public class UndefinedValueComparable implements Comparable { + + + @Override + public int compareTo(UndefinedValueComparable o) { + return 0; + } + + @Override + public String toString() { + return "undefined"; + } + + @Override + public int hashCode() { + return 0; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof UndefinedValueComparable; + } +} \ No newline at end of file diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/EvalHelper.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/EvalHelper.java index ddd788b19d1..346712fe935 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/EvalHelper.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/EvalHelper.java @@ -38,6 +38,7 @@ import org.kie.dmn.feel.lang.FEELProperty; import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.Range.RangeBoundary; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -186,6 +187,9 @@ public static PropertyValueResult getDefinedValue(final Object current, final St default: return PropertyValueResult.notDefined(); } + if (result instanceof UndefinedValueComparable) { + result = null; + } } else { Method getter = getGenericAccessor( current.getClass(), property ); if ( getter != null ) { diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/TypeUtil.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/TypeUtil.java index 7af8ad5d7af..339f1dbf141 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/TypeUtil.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/TypeUtil.java @@ -41,6 +41,12 @@ import org.kie.dmn.feel.runtime.functions.DateAndTimeFunction; import org.kie.dmn.feel.runtime.functions.DateFunction; import org.kie.dmn.feel.runtime.functions.TimeFunction; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; + +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.GT; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.GTE; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.LT; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.LTE; public final class TypeUtil { @@ -78,7 +84,8 @@ public static String formatValue(final Object val, final boolean wrapForCodeUsag } else if (val instanceof ZoneTime zoneTime) { return formatTimeString(zoneTime.format(), wrapForCodeUsage); } else if (val instanceof LocalDateTime || val instanceof OffsetDateTime) { - return formatDateTimeString(DateAndTimeFunction.FEEL_DATE_TIME.format((TemporalAccessor) val), wrapForCodeUsage); + return formatDateTimeString(DateAndTimeFunction.FEEL_DATE_TIME.format((TemporalAccessor) val), + wrapForCodeUsage); } else if (val instanceof ZonedDateTime) { TemporalAccessor ta = (TemporalAccessor) val; ZoneId zone = ta.query(TemporalQueries.zone()); @@ -86,7 +93,8 @@ public static String formatValue(final Object val, final boolean wrapForCodeUsag // it is a ZoneRegion return formatDateTimeString(DateAndTimeFunction.REGION_DATETIME_FORMATTER.format((TemporalAccessor) val), wrapForCodeUsage); } else { - return formatDateTimeString(DateAndTimeFunction.FEEL_DATE_TIME.format((TemporalAccessor) val), wrapForCodeUsage); + return formatDateTimeString(DateAndTimeFunction.FEEL_DATE_TIME.format((TemporalAccessor) val), + wrapForCodeUsage); } } else if (val instanceof Duration) { return formatDuration((Duration) val, wrapForCodeUsage); @@ -183,11 +191,33 @@ public static String formatContext(final Map context, final boolean wrapDateTime public static String formatRange(final Range val, final boolean wrapDateTimeValuesInFunctions) { final StringBuilder sb = new StringBuilder(); - sb.append(val.getLowBoundary() == Range.RangeBoundary.OPEN ? "( " : "[ "); - sb.append(formatValue(val.getLowEndPoint(), wrapDateTimeValuesInFunctions)); - sb.append(" .. "); - sb.append(formatValue(val.getHighEndPoint(), wrapDateTimeValuesInFunctions)); - sb.append(val.getHighBoundary() == Range.RangeBoundary.OPEN ? " )" : " ]"); + if (val.isWithUndefined()) { + sb.append("( "); + if (val.getLowEndPoint() instanceof UndefinedValueComparable) { + if (val.getHighBoundary() == Range.RangeBoundary.OPEN) { + sb.append(LT.symbol); + } else { + sb.append(LTE.symbol); + } + sb.append(" "); + sb.append(formatValue(val.getHighEndPoint(), wrapDateTimeValuesInFunctions)); + } else if (val.getHighEndPoint() instanceof UndefinedValueComparable) { + if (val.getLowBoundary() == Range.RangeBoundary.OPEN) { + sb.append(GT.symbol); + } else { + sb.append(GTE.symbol); + } + sb.append(" "); + sb.append(formatValue(val.getLowEndPoint(), wrapDateTimeValuesInFunctions)); + } + sb.append(" )"); + } else { + sb.append(val.getLowBoundary() == Range.RangeBoundary.OPEN ? "( " : "[ "); + sb.append(formatValue(val.getLowEndPoint(), wrapDateTimeValuesInFunctions)); + sb.append(" .. "); + sb.append(formatValue(val.getHighEndPoint(), wrapDateTimeValuesInFunctions)); + sb.append(val.getHighBoundary() == Range.RangeBoundary.OPEN ? " )" : " ]"); + } return sb.toString(); } @@ -274,7 +304,8 @@ private static void appendToDurationString(final StringBuilder sb, final long da sb.append(timeSegmentChar); } - private static void appendSecondsToDurationString(final StringBuilder sb, final long seconds, final long nanoseconds) { + private static void appendSecondsToDurationString(final StringBuilder sb, final long seconds, + final long nanoseconds) { if (seconds < 0 && nanoseconds > 0) { if (seconds == -1) { sb.append("0"); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerTest.java index 8b2adc20b4d..b79ad9ab479 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerTest.java @@ -36,6 +36,7 @@ import org.kie.dmn.feel.lang.types.impl.ComparablePeriod; import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.impl.RangeImpl; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; import static org.assertj.core.api.Assertions.assertThat; @@ -96,13 +97,18 @@ private static Collection data() { { Arrays.asList( Duration.ofDays( 4 ), Duration.ofDays( 2 ), Duration.ofHours( 25 ) ), "[ duration( \"P4D\" ), duration( \"P2D\" ), duration( \"P1DT1H\" ) ]" }, { Arrays.asList( Arrays.asList( 1, 2 ), Arrays.asList( 3, 4 ) ), "[ [ 1, 2 ], [ 3, 4 ] ]" }, // ranges - { new RangeImpl( Range.RangeBoundary.CLOSED, "a", "z", Range.RangeBoundary.OPEN ), "[ \"a\" .. \"z\" )" }, - { new RangeImpl( Range.RangeBoundary.CLOSED, Duration.ofHours( 30 ), Duration.ofHours( 50 ), Range.RangeBoundary.OPEN ), "[ duration( \"P1DT6H\" ) .. duration( \"P2DT2H\" ) )" }, + { new RangeImpl( Range.RangeBoundary.CLOSED, "a", "z", Range.RangeBoundary.OPEN), "[ \"a\" .. \"z\" )" }, + { new RangeImpl( Range.RangeBoundary.CLOSED, Duration.ofHours( 30 ), Duration.ofHours( 50 ), Range.RangeBoundary.OPEN), "[ duration( \"P1DT6H\" ) .. duration( \"P2DT2H\" ) )" }, + { new RangeImpl(Range.RangeBoundary.OPEN, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN), "( > 1 )" }, + { new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN), "( >= 1 )" }, + { new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.OPEN), "( < 1 )" }, + { new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.CLOSED), "( <= 1 )" }, // context { new LinkedHashMap() {{ put( "Full Name", "John Doe"); put( "Age", 35 ); put( "Date of Birth", LocalDate.of( 1982, 6, 9 ) ); }}, "{ Full Name : \"John Doe\", Age : 35, Date of Birth : date( \"1982-06-09\" ) }" }, // null - { null, "null" } + { null, "null" }, + { new UndefinedValueComparable(), "undefined"} }; return Arrays.asList( cases ); } diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerUnmarshallTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerUnmarshallTest.java index aa2457b8362..0635ac36400 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerUnmarshallTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerUnmarshallTest.java @@ -37,6 +37,7 @@ import org.kie.dmn.feel.lang.types.impl.ComparablePeriod; import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.impl.RangeImpl; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; import static org.assertj.core.api.Assertions.assertThat; @@ -91,13 +92,20 @@ private static Collection data() { { BuiltInType.UNKNOWN, "[ duration( \"P4D\" ), duration( \"P2D\" ), duration( \"P1DT1H\" ) ]", Arrays.asList( Duration.ofDays( 4 ), Duration.ofDays( 2 ), Duration.ofHours( 25 ) ) }, { BuiltInType.UNKNOWN, "[ [ 1, 2 ], [ 3, 4 ] ]", Arrays.asList( Arrays.asList( BigDecimal.valueOf( 1 ), BigDecimal.valueOf( 2 ) ), Arrays.asList( BigDecimal.valueOf( 3 ), BigDecimal.valueOf( 4 ) ) ) }, // ranges - { BuiltInType.UNKNOWN, "[ \"a\" .. \"z\" )", new RangeImpl( Range.RangeBoundary.CLOSED, "a", "z", Range.RangeBoundary.OPEN ) }, - { BuiltInType.UNKNOWN, "[ duration( \"P1DT6H\" ) .. duration( \"P2DT2H\" ) )", new RangeImpl( Range.RangeBoundary.CLOSED, Duration.ofHours( 30 ), Duration.ofHours( 50 ), Range.RangeBoundary.OPEN ) }, + { BuiltInType.UNKNOWN, "[ \"a\" .. \"z\" )", new RangeImpl( Range.RangeBoundary.CLOSED, "a", "z", Range.RangeBoundary.OPEN) }, + { BuiltInType.UNKNOWN, "[ duration( \"P1DT6H\" ) .. duration( \"P2DT2H\" ) )", new RangeImpl( Range.RangeBoundary.CLOSED, Duration.ofHours( 30 ), Duration.ofHours( 50 ), Range.RangeBoundary.OPEN) }, + + { BuiltInType.UNKNOWN, "( > 1 )", new RangeImpl(Range.RangeBoundary.OPEN, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN)}, + { BuiltInType.UNKNOWN, "( >= 1 )", new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN) }, + { BuiltInType.UNKNOWN, "( < 1 )", new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.OPEN)}, + { BuiltInType.UNKNOWN, "( <= 1 )", new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.CLOSED) }, + // context { BuiltInType.UNKNOWN, "{ Full Name : \"John Doe\", Age : 35, Date of Birth : date( \"1982-06-09\" ) }", new LinkedHashMap() {{ put( "Full Name", "John Doe"); put( "Age", BigDecimal.valueOf( 35 ) ); put( "Date of Birth", LocalDate.of( 1982, 6, 9 ) ); }} }, // null - { BuiltInType.UNKNOWN, "null", null } + { BuiltInType.UNKNOWN, "null", null }, + { BuiltInType.UNKNOWN, "undefined", new UndefinedValueComparable() } }; return Arrays.asList( cases ); } diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/parser/feel11/FEELParserSeverityTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/parser/feel11/FEELParserSeverityTest.java index 6f499898978..02851b82d29 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/parser/feel11/FEELParserSeverityTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/parser/feel11/FEELParserSeverityTest.java @@ -83,7 +83,7 @@ void unexistentOperatorEQEQ() { @Test void unexistentOperatorInvokeLTLT() { - // RHDM-1119 + // RHDM-1119 String inputExpression = "{ m: <<18 }.m(16)"; ASTNode number = parseSeverity(inputExpression, FEELEvent.Severity.WARN); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELRangesTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELRangesTest.java index 780e31e96dd..b2419f52634 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELRangesTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELRangesTest.java @@ -31,6 +31,7 @@ import org.kie.dmn.feel.lang.FEELDialect; import org.kie.dmn.feel.lang.types.impl.ComparablePeriod; import org.kie.dmn.feel.runtime.impl.RangeImpl; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; public class FEELRangesTest extends BaseFEELTest { @@ -42,6 +43,13 @@ protected void instanceTest(String expression, Object result, FEELEvent.Severity private static Collection data() { final Object[][] cases = new Object[][]{ + // when converting from unary tests, boundaries are dictated by comparison + {"(>1)", new RangeImpl(Range.RangeBoundary.OPEN, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN), null}, + {"(>=1)", new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN), null}, + {"(<1)", new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.OPEN), null}, + {"(<=1)", new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.CLOSED), null}, + {"(null..10)", new RangeImpl(Range.RangeBoundary.OPEN, null, BigDecimal.valueOf(10), Range.RangeBoundary.OPEN), null}, + {"[1..2]", new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.ONE, BigDecimal.valueOf(2), Range.RangeBoundary.CLOSED), null}, {"[2..1]", new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.valueOf(2), BigDecimal.ONE, Range.RangeBoundary.CLOSED), null}, {"[1..2)", new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.ONE, BigDecimal.valueOf(2), Range.RangeBoundary.OPEN), null}, @@ -161,7 +169,7 @@ private static Collection data() { put("enddate", LocalDate.of(1978, 10, 13)); put("rangedates", new RangeImpl(Range.RangeBoundary.CLOSED, LocalDate.of(1978, 9, 12), LocalDate.of(1978, 10, 13), Range.RangeBoundary.CLOSED)); }}, null}, - + // Table 42: {"[1..10].start included", Boolean.TRUE, null}, {"[1..10].start", new BigDecimal(1), null}, @@ -172,12 +180,14 @@ private static Collection data() { {"(1..10].end", new BigDecimal(10), null}, {"(1..10].end included", Boolean.TRUE, null}, {"(<=10).start included", Boolean.FALSE, null}, + {"(<10).start", null, null}, {"(<=10).start", null, null}, {"(<=10).end", new BigDecimal(10), null}, {"(<=10).end included", Boolean.TRUE, null}, {"(>1).start included", Boolean.FALSE, null}, {"(>1).start", new BigDecimal(1), null}, {"(>1).end", null, null}, + {"(>=1).end", null, null}, {"(>1).end included", Boolean.FALSE, null}, }; return addAdditionalParameters(cases, false); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/impl/RangeImplTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/impl/RangeImplTest.java index 6201fe90b12..521abb12fc7 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/impl/RangeImplTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/impl/RangeImplTest.java @@ -25,6 +25,24 @@ class RangeImplTest { + @Test + void isWithUndefined() { + RangeImpl rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, null, null, Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isFalse(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, 10, null, Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isFalse(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, null, 10, Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isFalse(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, null, new UndefinedValueComparable(), Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isTrue(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, new UndefinedValueComparable(), null, Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isTrue(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, 10, new UndefinedValueComparable(), Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isTrue(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, new UndefinedValueComparable(), 10, Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isTrue(); + } + @Test void getLowBoundary() { final Range.RangeBoundary lowBoundary = Range.RangeBoundary.CLOSED; @@ -77,6 +95,26 @@ void includes() { assertThat(rangeImpl.includes(10)).isTrue(); assertThat(rangeImpl.includes(12)).isTrue(); assertThat(rangeImpl.includes(15)).isTrue(); + + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, new UndefinedValueComparable(), 15, Range.RangeBoundary.CLOSED); + assertThat(rangeImpl.includes(-1456)).isTrue(); + assertThat(rangeImpl.includes(20)).isFalse(); + assertThat(rangeImpl.includes(null)).isNull(); + + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, 15, new UndefinedValueComparable(), Range.RangeBoundary.CLOSED); + assertThat(rangeImpl.includes(-1456)).isFalse(); + assertThat(rangeImpl.includes(20)).isTrue(); + assertThat(rangeImpl.includes(null)).isNull(); + + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, null, new UndefinedValueComparable(), Range.RangeBoundary.CLOSED); + assertThat(rangeImpl.includes(-1456)).isNull(); + assertThat(rangeImpl.includes(20)).isNull(); + assertThat(rangeImpl.includes(null)).isNull(); + + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, new UndefinedValueComparable(), null, Range.RangeBoundary.CLOSED); + assertThat(rangeImpl.includes(-1456)).isNull(); + assertThat(rangeImpl.includes(20)).isNull(); + assertThat(rangeImpl.includes(null)).isNull(); } @Test diff --git a/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/DMNDTAnalyser.java b/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/DMNDTAnalyser.java index 84bdbc3683b..e82e068c888 100644 --- a/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/DMNDTAnalyser.java +++ b/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/DMNDTAnalyser.java @@ -55,6 +55,7 @@ import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.ast.Visitor; import org.kie.dmn.feel.lang.impl.FEELBuilder; import org.kie.dmn.feel.lang.impl.InterpretedExecutableExpression; @@ -289,9 +290,9 @@ private void verifyUtln(UnaryTestListNode utln, DecisionTable dt) { } private Optional checkForDiamondRange(RangeNode rangeNode) { - if ((rangeNode.getStart() instanceof NullNode || rangeNode.getStart() == null) && rangeNode.getUpperBound() == IntervalBoundary.OPEN && rangeNode.getEnd() instanceof RangeNode) { + if ((rangeNode.getStart() instanceof NullNode || rangeNode.getStart() instanceof UndefinedValueNode || rangeNode.getStart() == null) && rangeNode.getUpperBound() == IntervalBoundary.OPEN && rangeNode.getEnd() instanceof RangeNode) { return Optional.ofNullable(((RangeNode) rangeNode.getEnd()).getStart()); // <> value - } else if ((rangeNode.getEnd() instanceof NullNode || rangeNode.getEnd() == null) && rangeNode.getLowerBound() == IntervalBoundary.OPEN && rangeNode.getStart() instanceof RangeNode) { + } else if ((rangeNode.getEnd() instanceof NullNode || rangeNode.getEnd() instanceof UndefinedValueNode || rangeNode.getEnd() == null) && rangeNode.getLowerBound() == IntervalBoundary.OPEN && rangeNode.getStart() instanceof RangeNode) { return Optional.ofNullable(((RangeNode) rangeNode.getStart()).getEnd()); // >< value } else { return Optional.empty(); @@ -751,14 +752,15 @@ private Interval utnToInterval(UnaryTestNode ut, Interval minMax, List discreteV return new Interval(RangeBoundary.CLOSED, valueFromNode(ut.getValue()), minMax.getUpperBound().getValue(), minMax.getUpperBound().getBoundaryType(), rule, col); } else if (ut.getValue() instanceof RangeNode) { RangeNode rangeNode = (RangeNode) ut.getValue(); - if (!(rangeNode.getStart() instanceof NullNode || rangeNode.getEnd() instanceof NullNode)) { + if (!(rangeNode.getStart() instanceof NullNode || rangeNode.getStart() instanceof UndefinedValueNode || + rangeNode.getEnd() instanceof NullNode || rangeNode.getEnd() instanceof UndefinedValueNode)) { return new Interval(rangeNode.getLowerBound() == IntervalBoundary.OPEN ? RangeBoundary.OPEN : RangeBoundary.CLOSED, valueFromNode(rangeNode.getStart()), valueFromNode(rangeNode.getEnd()), rangeNode.getUpperBound() == IntervalBoundary.OPEN ? RangeBoundary.OPEN : RangeBoundary.CLOSED, rule, col); - } else if (rangeNode.getStart() instanceof NullNode) { + } else if (rangeNode.getStart() instanceof NullNode || rangeNode.getStart() instanceof UndefinedValueNode) { return new Interval(minMax.getLowerBound().getBoundaryType(), minMax.getLowerBound().getValue(), valueFromNode(rangeNode.getEnd()), diff --git a/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/model/Interval.java b/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/model/Interval.java index bb9c9ca09c4..fb4ebccc8a2 100644 --- a/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/model/Interval.java +++ b/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/model/Interval.java @@ -30,6 +30,7 @@ import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.Range.RangeBoundary; import org.kie.dmn.feel.runtime.impl.RangeImpl; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; import org.kie.dmn.feel.util.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -99,7 +100,7 @@ private static Comparable nullIfInfinity(Comparable input) { if (input != POS_INF && input != NEG_INF) { return input; } else { - return null; + return new UndefinedValueComparable(); } }