To be called from {@link #match(AnalyzedSentence)} for rules that want
{@link #getAntiPatterns()} to be considered.
@since 3.1
500505
protected AnalyzedSentence getSentenceWithImmunization(AnalyzedSentence sentence) {
    if (!getAntiPatterns().isEmpty()) {
      //we need a copy of the sentence, not reference to the old one
      AnalyzedSentence immunizedSentence = sentence.copy(sentence);
      for (DisambiguationPatternRule patternRule : getAntiPatterns()) {
        try {
          immunizedSentence = patternRule.replace(immunizedSentence);
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
      return immunizedSentence;
    }
    return sentence;
  }
689111
public List<Object> match() {
        final IntMatchResults result = new IntMatchResults();
        if (matches(result)) {
            return result.getIntResultList();
        } else {
            return null;
        }
    }
1309726
public boolean isMatchedByPreviousException(AnalyzedToken token) {
    if (exceptionValidPrevious) {
      for (PatternToken testException : previousExceptionList) {
        if (!testException.exceptionValidNext) {
          if (testException.isMatched(token)) {
            return true;
          }
        }
      }
    }
    return false;
  }
862862
@Override
	public PType caseACaseAlternativeStm(ACaseAlternativeStm node,
			TypeCheckInfo question) throws AnalysisException
	{

		if (node.getDefs().size() == 0)
		{
			node.setDefs(new LinkedList<PDefinition>());
			question.assistantFactory.createPPatternAssistant().typeResolve(node.getPattern(), THIS, question);

			if (node.getPattern() instanceof AExpressionPattern)
			{
				// Only expression patterns need type checking...
				AExpressionPattern ep = (AExpressionPattern) node.getPattern();
				PType ptype = ep.getExp().apply(THIS, question);

				if (!question.assistantFactory.getTypeComparator().compatible(ptype, node.getCtype()))
				{
					TypeCheckerErrors.report(3311, "Pattern cannot match", node.getPattern().getLocation(), node.getPattern());
				}
			}

			question.assistantFactory.createPPatternAssistant().typeResolve(node.getPattern(), THIS, question);

			ACasesStm stm = (ACasesStm) node.parent();
			node.getDefs().addAll(question.assistantFactory.createPPatternAssistant().getDefinitions(node.getPattern(), stm.getExp().getType(), NameScope.LOCAL));
		}

		question.assistantFactory.createPDefinitionListAssistant().typeCheck(node.getDefs(), THIS, question);

		if (!question.assistantFactory.createPPatternAssistant().matches(node.getPattern(), node.getCtype()))
		{
			TypeCheckerErrors.report(3311, "Pattern cannot match", node.getPattern().getLocation(), node.getPattern());
		}

		Environment local = new FlatCheckedEnvironment(question.assistantFactory, node.getDefs(), question.env, question.scope);
		PType r = node.getResult().apply(THIS, new TypeCheckInfo(question.assistantFactory, local, question.scope, null, null, question.returnType));
		local.unusedCheck();

		return r;
	}
976394
@NotNull
  List<RuleMatch> getFilteredExtensionMatches(List<RuleMatch> matches, List<RemoteRuleMatch> extensionMatches) {
    List<RuleMatch> filteredExtMatches = new ArrayList<>();
    for (RemoteRuleMatch extensionMatch : extensionMatches) {
      if (!extensionMatch.isTouchedByOneOf(matches)) {
        AnalyzedSentence sentence = new AnalyzedSentence(new AnalyzedTokenReadings[]{});
        HiddenRule hiddenRule = new HiddenRule(extensionMatch.getLocQualityIssueType().orElse(null), extensionMatch.estimatedContextForSureMatch());
        RuleMatch hiddenRuleMatch = new RuleMatch(hiddenRule, sentence, extensionMatch.getErrorOffset(),
                extensionMatch.getErrorOffset()+extensionMatch.getErrorLength(), "(hidden message)");
        filteredExtMatches.add(hiddenRuleMatch);
      }
    }
    return filteredExtMatches;
  }
1223306
public int matches(Replaceable text,
                       int[] offset,
                       int limit,
                       boolean incremental) {
        int start = offset[0];
        int count = 0;
        while (count < maxCount) {
            int pos = offset[0];
            int m = matcher.matches(text, offset, limit, incremental);
            if (m == U_MATCH) {
                ++count;
                if (pos == offset[0]) {
                    // If offset has not moved we have a zero-width match.
                    // Don't keep matching it infinitely.
                    break;
                }
            } else if (incremental && m == U_PARTIAL_MATCH) {
                return U_PARTIAL_MATCH;
            } else {
                break;
            }
        }
        if (incremental && offset[0] == limit) {
            return U_PARTIAL_MATCH;
        }
        if (count >= minCount) {
            return U_MATCH;
        }
        offset[0] = start;
        return U_MISMATCH;
    }
138054
public boolean assessMatch(final OgnlContext ognlContext) throws OgnlException
	{

		if (! inputRun)
		{
			throw new IllegalArgumentException("Attempted to match on a rule whose rulesets input has not yet been produced");
		}

		final Object result = condition.run(ognlContext, ognlContext);

		if (result == null || !Boolean.class.isAssignableFrom(result.getClass()))
		{
			throw new IllegalArgumentException("Expression " + condition.getOriginalExpression() +
			                                   " did not return a boolean value");
		}

		matches = (Boolean) result;

		return matches;
	}
363954
@Override
    @Path("/{assetPath}")
    @ApiOperation(value="Apply rules identified by assetPath.", notes="Query may contain runtime values")
    @ApiImplicitParams({
        @ApiImplicitParam(name="FactsObject", paramType="body", required=true, value="Input to apply rules against"),
        @ApiImplicitParam(name="assetPath", paramType="path", required=true, value="Identifies a .drl or .xlsx asset"),
        @ApiImplicitParam(name="rules-executor", paramType="header", required=false, value="Default is Drools")})
    public JSONObject post(String path, JSONObject content, Map<String,String> headers)
            throws ServiceException, JSONException {

        Asset rules = getRulesAsset(path);

        Operand input = new Operand(content);
        input.setContext(getContext(path));
        Query query = getQuery(path, headers);
        input.setParams(query.getFilters());
        input.setMeta(headers);

        JSONObject response = invokeRules(rules, input, getExecutor(headers));

        Status status = input.getStatus();
        if (status != null) {
            headers.put(Listener.METAINFO_HTTP_STATUS_CODE, String.valueOf(status.getCode()));
            if (response == null)
                return status.getJson();
        }

        return response;
    }
222696
@Override
	public void caseAForAllExp(AForAllExp node) throws AnalysisException
	{
		if (!proceed(node))
		{
			return;
		}

		handleMultipleBindConstruct(node, node.getBindList(), null, node.getPredicate());
	}
1364563
@Override
	public boolean matches(ITraceEvent traceData) {
		boolean ynMatches = false;
		for( ITraceEvent criteria : m_criteriaList) {
			if (LOG.isDebugEnabled())  LOG.debug("Comparing [" + traceData.getRawEventData() + "] to [" + m_criteriaList.size() + "] criteria [" + criteria.toString() +  "]");

//			if (criteria.getEventType()==traceData.getEventType()
////					&& criteria.getClassName().equals(traceData.getClassName())
//					&& criteria.getMethodName().equals(traceData.getMethodName())
//					) 
			
			if (criteria.getMethodName().equals(traceData.getMethodName() )) {
						if (LOG.isDebugEnabled())  LOG.debug("Found match for [" + traceData.getRawEventData() + "] to [" + m_criteriaList.size() + "] criteria ");
						return true;
					} 
		}
		return ynMatches;
	}
1306893
@Override
	void analyzeKeywords(AnalyzedText aText) {
		if (kwMatcher != null){
			aText.setMatchedKeywords(kwMatcher.match(aText.getText()));
		}
	}
456252
@Override
    public MethodGen analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
        Method method = getMethod(analysisCache, descriptor);

        if (method.getCode() == null) {
            return null;
        }
        XMethod xmethod =  XFactory.createXMethod(descriptor);
        if (xmethod.usesInvokeDynamic() && false) {
            AnalysisContext.currentAnalysisContext().analysisSkippedDueToInvokeDynamic(xmethod);
            return null;
        }

        try {
            AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext();
            JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor());
            ConstantPoolGen cpg = getConstantPoolGen(analysisCache, descriptor.getClassDescriptor());

            String methodName = method.getName();
            int codeLength = method.getCode().getCode().length;
            String superclassName = jclass.getSuperclassName();
            if (codeLength > 6000 && Const.STATIC_INITIALIZER_NAME.equals(methodName) && "java.lang.Enum".equals(superclassName)) {
                analysisContext.getLookupFailureCallback().reportSkippedAnalysis(
                        new JavaClassAndMethod(jclass, method).toMethodDescriptor());
                return null;
            }
            if (analysisContext.getBoolProperty(AnalysisFeatures.SKIP_HUGE_METHODS)) {
                if (codeLength > 6000 || (Const.STATIC_INITIALIZER_NAME.equals(methodName) || "getContents".equals(methodName)) && codeLength > 2000) {
                    analysisContext.getLookupFailureCallback().reportSkippedAnalysis(
                            new JavaClassAndMethod(jclass, method).toMethodDescriptor());
                    return null;
                }
            }

            return new MethodGen(method, jclass.getClassName(), cpg);
        } catch (Exception e) {
            AnalysisContext.logError("Error constructing methodGen", e);
            return null;
        }
    }
157599
private static boolean checkPureColumnIndex(Index index, int aggCol, List<AbstractExpression> filterExprs) {

        boolean found = false;

        // all left child of filterExprs must be of type TupleValueExpression in equality comparison
        for (AbstractExpression expr : filterExprs) {
            if (expr.getExpressionType() != ExpressionType.COMPARE_EQUAL) {
                return false;
            }
            if (!(expr.getLeft() instanceof TupleValueExpression)) {
                return false;
            }
            if (((TupleValueExpression)expr.getLeft()).getColumnIndex() == aggCol) {
                found = true;
            }
        }

        if (found) {
            return true;
        }
        if (index.getColumns().size() > filterExprs.size()) {
            List<ColumnRef> indexedColRefs = CatalogUtil.getSortedCatalogItems(index.getColumns(), "index");

            if (indexedColRefs.get(filterExprs.size()).getColumn().getIndex() == aggCol) {
                return true;
            }
        }

        return false;
    }
767691
public AnalyzedSentence getAnalyzedSentence(String sentence) throws IOException {
    SimpleInputSentence cacheKey = new SimpleInputSentence(sentence, language);
    AnalyzedSentence cachedSentence = cache != null ? cache.getIfPresent(cacheKey) : null;
    if (cachedSentence != null) {
      return cachedSentence;
    } else {
      AnalyzedSentence raw = getRawAnalyzedSentence(sentence);
      AnalyzedSentence disambig = language.getDisambiguator().disambiguate(raw);
      AnalyzedSentence analyzedSentence = new AnalyzedSentence(disambig.getTokens(), raw.getTokens());
      if (language.getPostDisambiguationChunker() != null) {
        language.getPostDisambiguationChunker().addChunkTags(Arrays.asList(analyzedSentence.getTokens()));
      }
      if (cache != null) {
        cache.put(cacheKey, analyzedSentence);
      }
      return analyzedSentence;
    }
  }
390846
public static void match(DatabaseClient client) throws IOException {
    // create a manager for document search criteria
    QueryManager queryMgr = client.newQueryManager();

    // specify the search criteria for the documents
    String criteria = "neighborhoods";
    StringQueryDefinition querydef = queryMgr.newStringDefinition();
    querydef.setCriteria(criteria);

    // create a manager for matching rules
    RuleManager ruleMgr = client.newRuleManager();

    // match the rules against the documents qualified by the criteria
    RuleDefinitionList matchedRules = ruleMgr.match(querydef, new RuleDefinitionList());

    // iterate over the matched rules
    Iterator<RuleDefinition> ruleItr = matchedRules.iterator();
    while (ruleItr.hasNext()) {
      RuleDefinition rule = ruleItr.next();
      System.out.println(
        "document criteria "+criteria+" matched rule "+
          rule.getName()+" with metadata "+rule.getMetadata()
      );
    }
  }
678445
@SuppressWarnings("fallthrough")
    ParensResult analyzeParens() {
        int depth = 0;
        boolean type = false;
        outer: for (int lookahead = 0 ; ; lookahead++) {
            TokenKind tk = S.token(lookahead).kind;
            switch (tk) {
                case COMMA:
                    type = true;
                case EXTENDS: case SUPER: case DOT: case AMP:
                    //skip
                    break;
                case QUES:
                    if (peekToken(lookahead, EXTENDS) ||
                            peekToken(lookahead, SUPER)) {
                        //wildcards
                        type = true;
                    }
                    break;
                case BYTE: case SHORT: case INT: case LONG: case FLOAT:
                case DOUBLE: case BOOLEAN: case CHAR:
                    if (peekToken(lookahead, RPAREN)) {
                        //Type, ')' -> cast
                        return ParensResult.CAST;
                    } else if (peekToken(lookahead, LAX_IDENTIFIER)) {
                        //Type, Identifier/'_'/'assert'/'enum' -> explicit lambda
                        return ParensResult.EXPLICIT_LAMBDA;
                    }
                    break;
                case LPAREN:
                    if (lookahead != 0) {
                        // '(' in a non-starting position -> parens
                        return ParensResult.PARENS;
                    } else if (peekToken(lookahead, RPAREN)) {
                        // '(', ')' -> explicit lambda
                        return ParensResult.EXPLICIT_LAMBDA;
                    }
                    break;
                case RPAREN:
                    // if we have seen something that looks like a type,
                    // then it's a cast expression
                    if (type) return ParensResult.CAST;
                    // otherwise, disambiguate cast vs. parenthesized expression
                    // based on subsequent token.
                    switch (S.token(lookahead + 1).kind) {
                        /*case PLUSPLUS: case SUBSUB: */
                        case BANG: case TILDE:
                        case LPAREN: case THIS: case SUPER:
                        case INTLITERAL: case LONGLITERAL: case FLOATLITERAL:
                        case DOUBLELITERAL: case CHARLITERAL: case STRINGLITERAL:
                        case TRUE: case FALSE: case NULL:
                        case NEW: case IDENTIFIER: case ASSERT: case ENUM: case UNDERSCORE:
                        case BYTE: case SHORT: case CHAR: case INT:
                        case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case VOID:
                            return ParensResult.CAST;
                        default:
                            return ParensResult.PARENS;
                    }
                case UNDERSCORE:
                case ASSERT:
                case ENUM:
                case IDENTIFIER:
                    if (peekToken(lookahead, LAX_IDENTIFIER)) {
                        // Identifier, Identifier/'_'/'assert'/'enum' -> explicit lambda
                        return ParensResult.EXPLICIT_LAMBDA;
                    } else if (peekToken(lookahead, RPAREN, ARROW)) {
                        // Identifier, ')' '->' -> implicit lambda
                        return ParensResult.IMPLICIT_LAMBDA;
                    }
                    type = false;
                    break;
                case FINAL:
                case ELLIPSIS:
                    //those can only appear in explicit lambdas
                    return ParensResult.EXPLICIT_LAMBDA;
                case MONKEYS_AT:
                    type = true;
                    lookahead += 1; //skip '@'
                    while (peekToken(lookahead, DOT)) {
                        lookahead += 2;
                    }
                    if (peekToken(lookahead, LPAREN)) {
                        lookahead++;
                        //skip annotation values
                        int nesting = 0;
                        for (; ; lookahead++) {
                            TokenKind tk2 = S.token(lookahead).kind;
                            switch (tk2) {
                                case EOF:
                                    return ParensResult.PARENS;
                                case LPAREN:
                                    nesting++;
                                    break;
                                case RPAREN:
                                    nesting--;
                                    if (nesting == 0) {
                                        continue outer;
                                    }
                                break;
                            }
                        }
                    }
                    break;
                case LBRACKET:
                    if (peekToken(lookahead, RBRACKET, LAX_IDENTIFIER)) {
                        // '[', ']', Identifier/'_'/'assert'/'enum' -> explicit lambda
                        return ParensResult.EXPLICIT_LAMBDA;
                    } else if (peekToken(lookahead, RBRACKET, RPAREN) ||
                            peekToken(lookahead, RBRACKET, AMP)) {
                        // '[', ']', ')' -> cast
                        // '[', ']', '&' -> cast (intersection type)
                        return ParensResult.CAST;
                    } else if (peekToken(lookahead, RBRACKET)) {
                        //consume the ']' and skip
                        type = true;
                        lookahead++;
                        break;
                    } else {
                        return ParensResult.PARENS;
                    }
                case LT:
                    depth++; break;
                case GTGTGT:
                    depth--;
                case GTGT:
                    depth--;
                case GT:
                    depth--;
                    if (depth == 0) {
                        if (peekToken(lookahead, RPAREN) ||
                                peekToken(lookahead, AMP)) {
                            // '>', ')' -> cast
                            // '>', '&' -> cast
                            return ParensResult.CAST;
                        } else if (peekToken(lookahead, LAX_IDENTIFIER, COMMA) ||
                                peekToken(lookahead, LAX_IDENTIFIER, RPAREN, ARROW) ||
                                peekToken(lookahead, ELLIPSIS)) {
                            // '>', Identifier/'_'/'assert'/'enum', ',' -> explicit lambda
                            // '>', Identifier/'_'/'assert'/'enum', ')', '->' -> explicit lambda
                            // '>', '...' -> explicit lambda
                            return ParensResult.EXPLICIT_LAMBDA;
                        }
                        //it looks a type, but could still be (i) a cast to generic type,
                        //(ii) an unbound method reference or (iii) an explicit lambda
                        type = true;
                        break;
                    } else if (depth < 0) {
                        //unbalanced '<', '>' - not a generic type
                        return ParensResult.PARENS;
                    }
                    break;
                default:
                    //this includes EOF
                    return ParensResult.PARENS;
            }
        }
    }
232525
private boolean matches(EvaluationContext ctx, Object[] params, DTDecisionRule rule) {
        for( int i = 0; i < params.length; i++ ) {
            CompiledExpression compiledInput = inputs.get(i).getCompiledInput();
            if ( compiledInput instanceof CompiledFEELExpression) {
                ctx.setValue("?", ((CompiledFEELExpression) compiledInput).apply(ctx));
            }
            if( ! satisfies( ctx, params[i], rule.getInputEntry().get( i ) ) ) {
                return false;
            }
        }
        return true;
    }