Search in sources :

Example 86 with PatternDescr

use of org.drools.compiler.lang.descr.PatternDescr in project drools by kiegroup.

the class QueryElementBuilder method build.

@SuppressWarnings("unchecked")
public RuleConditionElement build(RuleBuildContext context, BaseDescr descr, QueryImpl query) {
    PatternDescr patternDescr = (PatternDescr) descr;
    Declaration[] params = query.getParameters();
    List<BaseDescr> args = (List<BaseDescr>) patternDescr.getDescrs();
    List<Declaration> requiredDeclarations = new ArrayList<Declaration>();
    ObjectType argsObjectType = ClassObjectType.ObjectArray_ObjectType;
    InternalReadAccessor arrayReader = new SelfReferenceClassFieldReader(Object[].class);
    Pattern pattern = new Pattern(context.getNextPatternId(), 0, argsObjectType, null);
    if (!StringUtils.isEmpty(patternDescr.getIdentifier())) {
        if (query.isAbductive()) {
            Declaration declr = context.getDeclarationResolver().getDeclaration(patternDescr.getIdentifier());
            if (declr != null && !patternDescr.isUnification()) {
                context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Duplicate declaration " + patternDescr.getIdentifier() + ", unable to bind abducted value"));
            }
        } else {
            context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Query binding is not supported by non-abductive queries : " + patternDescr.getIdentifier()));
        }
    }
    boolean addAbductiveReturnArgument = query.isAbductive() && !StringUtils.isEmpty(patternDescr.getIdentifier()) && args.size() < params.length;
    if (addAbductiveReturnArgument) {
        ExprConstraintDescr extraDescr = new ExprConstraintDescr(patternDescr.getIdentifier());
        extraDescr.setPosition(patternDescr.getConstraint().getDescrs().size());
        extraDescr.setType(ExprConstraintDescr.Type.POSITIONAL);
        args.add(extraDescr);
    }
    QueryArgument[] arguments = new QueryArgument[params.length];
    // Deal with the constraints, both positional and bindings
    for (BaseDescr base : args) {
        String expression = null;
        boolean isPositional = false;
        boolean isBinding = false;
        BindingDescr bind = null;
        ConstraintConnectiveDescr result = null;
        if (base instanceof BindingDescr) {
            bind = (BindingDescr) base;
            expression = bind.getVariable() + (bind.isUnification() ? " := " : " : ") + bind.getExpression();
            isBinding = true;
        } else {
            if (base instanceof ExprConstraintDescr) {
                ExprConstraintDescr ecd = (ExprConstraintDescr) base;
                expression = ecd.getExpression();
                isPositional = ecd.getType() == ExprConstraintDescr.Type.POSITIONAL;
            } else {
                expression = base.getText();
            }
            result = parseExpression(context, patternDescr, expression);
            if (result == null) {
                // error, can't parse expression.
                context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Unable to parse constraint: \n" + expression));
                continue;
            }
            isBinding = result.getDescrs().size() == 1 && result.getDescrs().get(0) instanceof BindingDescr;
            if (isBinding) {
                bind = (BindingDescr) result.getDescrs().get(0);
            }
        }
        if ((!isPositional) && (!isBinding)) {
            // error, can't have non binding slots.
            context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Query's must use positional or bindings, not field constraints:\n" + expression));
        } else if (isPositional && isBinding) {
            // error, can't have positional binding slots.
            context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Query's can't use positional bindings:\n" + expression));
        } else if (isPositional) {
            processPositional(context, query, params, arguments, requiredDeclarations, arrayReader, pattern, base, expression, result);
        } else {
            // it is binding
            processBinding(context, descr, params, arguments, requiredDeclarations, arrayReader, pattern, bind);
        }
    }
    List<Integer> varIndexList = new ArrayList<Integer>();
    for (int i = 0; i < arguments.length; i++) {
        if (!(arguments[i] instanceof QueryArgument.Declr)) {
            if (arguments[i] instanceof QueryArgument.Var) {
                varIndexList.add(i);
            }
            continue;
        }
        Class actual = ((QueryArgument.Declr) arguments[i]).getArgumentClass();
        Declaration formalArgument = query.getParameters()[i];
        Class formal = formalArgument.getDeclarationClass();
        // input argument require a broader type, while output types require a narrower type, so we check for both.
        if (!ClassUtils.isTypeCompatibleWithArgumentType(actual, formal) && !ClassUtils.isTypeCompatibleWithArgumentType(formal, actual)) {
            context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Query is being invoked with known argument of type " + actual + " at position " + i + ", but the expected query argument is of type " + formal));
        }
    }
    return new QueryElement(pattern, query.getName(), arguments, toIntArray(varIndexList), requiredDeclarations.toArray(new Declaration[requiredDeclarations.size()]), !patternDescr.isQuery(), query.isAbductive());
}
Also used : BindingDescr(org.drools.compiler.lang.descr.BindingDescr) QueryArgument(org.drools.core.rule.QueryArgument) PatternDescr(org.drools.compiler.lang.descr.PatternDescr) ArrayList(java.util.ArrayList) QueryElement(org.drools.core.rule.QueryElement) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) ArrayList(java.util.ArrayList) List(java.util.List) Declaration(org.drools.core.rule.Declaration) ConstraintConnectiveDescr(org.drools.compiler.lang.descr.ConstraintConnectiveDescr) Pattern(org.drools.core.rule.Pattern) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) SelfReferenceClassFieldReader(org.drools.core.base.extractors.SelfReferenceClassFieldReader) BaseDescr(org.drools.compiler.lang.descr.BaseDescr) ExprConstraintDescr(org.drools.compiler.lang.descr.ExprConstraintDescr)

Example 87 with PatternDescr

use of org.drools.compiler.lang.descr.PatternDescr in project drools by kiegroup.

the class RestrictionConnectiveHandler method end.

public Object end(final String uri, final String localName, final ExtensibleXmlParser parser) throws SAXException {
    final Element element = parser.endElementBuilder();
    Object op = parser.getParent();
    ConnectiveDescr c = (ConnectiveDescr) parser.getCurrent();
    if (op instanceof PatternDescr) {
        StringBuilder sb = new StringBuilder();
        c.buildExpression(sb);
        ExprConstraintDescr expr = new ExprConstraintDescr();
        expr.setExpression(sb.toString());
        final PatternDescr patternDescr = (PatternDescr) op;
        patternDescr.addConstraint(expr);
    } else {
        ConnectiveDescr p = (ConnectiveDescr) op;
        p.add(c);
    }
    return c;
}
Also used : PatternDescr(org.drools.compiler.lang.descr.PatternDescr) Element(org.w3c.dom.Element) ConnectiveDescr(org.drools.compiler.lang.descr.ConnectiveDescr) RestrictionConnectiveDescr(org.drools.compiler.lang.descr.RestrictionConnectiveDescr) ExprConstraintDescr(org.drools.compiler.lang.descr.ExprConstraintDescr)

Example 88 with PatternDescr

use of org.drools.compiler.lang.descr.PatternDescr in project drools by kiegroup.

the class XmlPackageReaderTest method testAccumulateMultiPattern.

@Test
public void testAccumulateMultiPattern() throws Exception {
    final XmlPackageReader xmlPackageReader = getXmReader();
    xmlPackageReader.read(new InputStreamReader(getClass().getResourceAsStream("test_ParseAccumulate.xml")));
    final PackageDescr packageDescr = xmlPackageReader.getPackageDescr();
    assertNotNull(packageDescr);
    RuleDescr obj = (RuleDescr) packageDescr.getRules().get(1);
    Object patternobj = obj.getLhs().getDescrs().get(0);
    assertTrue(patternobj instanceof PatternDescr);
    final PatternDescr patterncheese = (PatternDescr) patternobj;
    assertEquals(patterncheese.getIdentifier(), "cheese");
    assertEquals(patterncheese.getObjectType(), "Cheese");
    AccumulateDescr accumulatedescr = (AccumulateDescr) patterncheese.getSource();
    assertEquals("total += $cheese.getPrice();", accumulatedescr.getActionCode());
    assertEquals("int total = 0;", accumulatedescr.getInitCode());
    assertEquals("new Integer( total ) );", accumulatedescr.getResultCode());
    AndDescr anddescr = (AndDescr) accumulatedescr.getInput();
    List descrlist = anddescr.getDescrs();
    PatternDescr[] listpattern = (PatternDescr[]) descrlist.toArray(new PatternDescr[descrlist.size()]);
    assertEquals(listpattern[0].getObjectType(), "Milk");
    assertEquals(listpattern[1].getObjectType(), "Cup");
}
Also used : InputStreamReader(java.io.InputStreamReader) PatternDescr(org.drools.compiler.lang.descr.PatternDescr) AndDescr(org.drools.compiler.lang.descr.AndDescr) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) List(java.util.List) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) AccumulateDescr(org.drools.compiler.lang.descr.AccumulateDescr) XmlPackageReader(org.drools.compiler.compiler.xml.XmlPackageReader) Test(org.junit.Test)

Example 89 with PatternDescr

use of org.drools.compiler.lang.descr.PatternDescr in project drools by kiegroup.

the class XmlPackageReaderTest method testParseQuery.

@Test
public void testParseQuery() throws Exception {
    final XmlPackageReader xmlPackageReader = getXmReader();
    xmlPackageReader.read(new InputStreamReader(getClass().getResourceAsStream("test_ParseQuery.xml")));
    final PackageDescr packageDescr = xmlPackageReader.getPackageDescr();
    assertNotNull(packageDescr);
    assertEquals("com.sample", packageDescr.getName());
    final List imports = packageDescr.getImports();
    assertEquals(2, imports.size());
    assertEquals("java.util.HashMap", ((ImportDescr) imports.get(0)).getTarget());
    assertEquals("org.drools.compiler.*", ((ImportDescr) imports.get(1)).getTarget());
    final List globals = packageDescr.getGlobals();
    assertEquals(2, globals.size());
    final GlobalDescr x = (GlobalDescr) globals.get(0);
    final GlobalDescr yada = (GlobalDescr) globals.get(1);
    assertEquals("com.sample.X", x.getType());
    assertEquals("x", x.getIdentifier());
    assertEquals("com.sample.Yada", yada.getType());
    assertEquals("yada", yada.getIdentifier());
    final FunctionDescr functionDescr = (FunctionDescr) packageDescr.getFunctions().get(0);
    final List names = functionDescr.getParameterNames();
    assertEquals("foo", names.get(0));
    assertEquals("bada", names.get(1));
    final List types = functionDescr.getParameterTypes();
    assertEquals("Bar", types.get(0));
    assertEquals("Bing", types.get(1));
    assertEquals("System.out.println(\"hello world\");", functionDescr.getText().trim());
    final QueryDescr queryDescr = (QueryDescr) packageDescr.getRules().get(0);
    assertEquals("my query", queryDescr.getName());
    final AndDescr lhs = queryDescr.getLhs();
    assertEquals(1, lhs.getDescrs().size());
    final PatternDescr patternDescr = (PatternDescr) lhs.getDescrs().get(0);
    assertEquals("Foo", patternDescr.getObjectType());
}
Also used : GlobalDescr(org.drools.compiler.lang.descr.GlobalDescr) QueryDescr(org.drools.compiler.lang.descr.QueryDescr) InputStreamReader(java.io.InputStreamReader) PatternDescr(org.drools.compiler.lang.descr.PatternDescr) AndDescr(org.drools.compiler.lang.descr.AndDescr) List(java.util.List) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) FunctionDescr(org.drools.compiler.lang.descr.FunctionDescr) XmlPackageReader(org.drools.compiler.compiler.xml.XmlPackageReader) Test(org.junit.Test)

Example 90 with PatternDescr

use of org.drools.compiler.lang.descr.PatternDescr in project drools by kiegroup.

the class XmlPackageReaderTest method testParseSimpleRule.

@Test
public void testParseSimpleRule() throws Exception {
    final XmlPackageReader xmlPackageReader = getXmReader();
    xmlPackageReader.read(new InputStreamReader(getClass().getResourceAsStream("test_SimpleRule1.xml")));
    final PackageDescr packageDescr = xmlPackageReader.getPackageDescr();
    assertNotNull(packageDescr);
    assertEquals("com.sample", packageDescr.getName());
    final List imports = packageDescr.getImports();
    assertEquals(2, imports.size());
    assertEquals("java.util.List", ((ImportDescr) imports.get(0)).getTarget());
    assertEquals("org.drools.compiler.Person", ((ImportDescr) imports.get(1)).getTarget());
    RuleDescr ruleDescr = (RuleDescr) packageDescr.getRules().get(0);
    assertEquals("simple_rule1", ruleDescr.getName());
    AndDescr lhs = ruleDescr.getLhs();
    PatternDescr patternDescr = (PatternDescr) lhs.getDescrs().get(0);
    assertEquals("Person", patternDescr.getObjectType());
    ExprConstraintDescr expr = (ExprConstraintDescr) ((AndDescr) patternDescr.getConstraint()).getDescrs().get(0);
    assertEquals("name == \"darth\"", expr.getExpression());
    ruleDescr = (RuleDescr) packageDescr.getRules().get(1);
    assertEquals("simple_rule2", ruleDescr.getName());
    lhs = ruleDescr.getLhs();
    patternDescr = (PatternDescr) lhs.getDescrs().get(0);
    assertEquals("Person", patternDescr.getObjectType());
    expr = (ExprConstraintDescr) ((AndDescr) patternDescr.getConstraint()).getDescrs().get(0);
    assertEquals("age == 35 || == -3.5", expr.getExpression());
    ruleDescr = (RuleDescr) packageDescr.getRules().get(2);
    assertEquals("simple_rule3", ruleDescr.getName());
    lhs = ruleDescr.getLhs();
    patternDescr = (PatternDescr) lhs.getDescrs().get(0);
    assertEquals("Person", patternDescr.getObjectType());
    expr = (ExprConstraintDescr) ((AndDescr) patternDescr.getConstraint()).getDescrs().get(0);
    assertEquals("age == 35 || (!= 7.0 && != -70)", expr.getExpression());
    ruleDescr = (RuleDescr) packageDescr.getRules().get(3);
    assertEquals("simple_rule3", ruleDescr.getName());
    lhs = ruleDescr.getLhs();
    patternDescr = (PatternDescr) lhs.getDescrs().get(1);
    assertEquals("Person", patternDescr.getObjectType());
    expr = (ExprConstraintDescr) ((AndDescr) patternDescr.getConstraint()).getDescrs().get(0);
    assertEquals("name == $s", expr.getExpression());
    ruleDescr = (RuleDescr) packageDescr.getRules().get(4);
    assertEquals("simple_rule4", ruleDescr.getName());
    lhs = ruleDescr.getLhs();
    patternDescr = (PatternDescr) lhs.getDescrs().get(1);
    assertEquals("Person", patternDescr.getObjectType());
    expr = (ExprConstraintDescr) ((AndDescr) patternDescr.getConstraint()).getDescrs().get(0);
    assertEquals("(name == $s) || (age == 35 || (!= 7.0 && != -70))", expr.getExpression());
    ruleDescr = (RuleDescr) packageDescr.getRules().get(5);
    assertEquals("simple_rule5", ruleDescr.getName());
    lhs = ruleDescr.getLhs();
    patternDescr = (PatternDescr) lhs.getDescrs().get(1);
    assertEquals("Person", patternDescr.getObjectType());
    expr = (ExprConstraintDescr) ((AndDescr) patternDescr.getConstraint()).getDescrs().get(0);
    assertEquals("(name == $s) || ((age != 34) && (age != 37) && (name != \"yoda\"))", expr.getExpression());
}
Also used : InputStreamReader(java.io.InputStreamReader) PatternDescr(org.drools.compiler.lang.descr.PatternDescr) AndDescr(org.drools.compiler.lang.descr.AndDescr) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) List(java.util.List) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) ExprConstraintDescr(org.drools.compiler.lang.descr.ExprConstraintDescr) XmlPackageReader(org.drools.compiler.compiler.xml.XmlPackageReader) Test(org.junit.Test)

Aggregations

PatternDescr (org.drools.compiler.lang.descr.PatternDescr)150 Test (org.junit.Test)122 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)103 PackageDescr (org.drools.compiler.lang.descr.PackageDescr)84 ExprConstraintDescr (org.drools.compiler.lang.descr.ExprConstraintDescr)56 AndDescr (org.drools.compiler.lang.descr.AndDescr)52 AccumulateDescr (org.drools.compiler.lang.descr.AccumulateDescr)19 Cheese (org.drools.compiler.Cheese)14 FromDescr (org.drools.compiler.lang.descr.FromDescr)14 BindingDescr (org.drools.compiler.lang.descr.BindingDescr)11 NotDescr (org.drools.compiler.lang.descr.NotDescr)11 OrDescr (org.drools.compiler.lang.descr.OrDescr)11 CompositeObjectSinkAdapterTest (org.drools.core.reteoo.CompositeObjectSinkAdapterTest)11 Element (org.w3c.dom.Element)9 BaseDescr (org.drools.compiler.lang.descr.BaseDescr)8 InputStreamReader (java.io.InputStreamReader)7 List (java.util.List)7 XmlPackageReader (org.drools.compiler.compiler.xml.XmlPackageReader)7 GlobalDescr (org.drools.compiler.lang.descr.GlobalDescr)7 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)7