private Declaration[] getUsedDeclarations(
      Map<String, Declaration> decls, AnalysisResult analysis) {
    final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();
    List<Declaration> usedDeclarations = new ArrayList<Declaration>();
    for (String id : usedIdentifiers.getDeclrClasses().keySet()) {
      if (decls.containsKey(id)) {
        usedDeclarations.add(decls.get(id));
      }
    }

    if (!usedDeclarations.isEmpty()) {
      Collections.sort(usedDeclarations, SortDeclarations.instance);
    }

    return usedDeclarations.toArray(new Declaration[usedDeclarations.size()]);
  }
  @SuppressWarnings("unchecked")
  public RuleConditionElement build(
      final RuleBuildContext context, final BaseDescr descr, final Pattern prefixPattern) {
    boolean typesafe = context.isTypesafe();
    try {
      final AccumulateDescr accumDescr = (AccumulateDescr) descr;

      if (!accumDescr.hasValidInput()) {
        return null;
      }

      final RuleConditionBuilder builder =
          (RuleConditionBuilder) context.getDialect().getBuilder(accumDescr.getInput().getClass());

      // create source CE
      final RuleConditionElement source = builder.build(context, accumDescr.getInput());

      if (source == null) {
        return null;
      }

      MVELDialect dialect = (MVELDialect) context.getDialect();

      Map<String, Declaration> decls =
          context.getDeclarationResolver().getDeclarations(context.getRule());
      Map<String, Declaration> sourceOuterDeclr = source.getOuterDeclarations();

      Map<String, Declaration> mergedDecl = new HashMap(decls);
      mergedDecl.putAll(sourceOuterDeclr);

      Map<String, Class<?>> declarationClasses =
          DeclarationScopeResolver.getDeclarationClasses(decls);
      declarationClasses.putAll(DeclarationScopeResolver.getDeclarationClasses(sourceOuterDeclr));

      BoundIdentifiers boundIds =
          new BoundIdentifiers(declarationClasses, context.getKnowledgeBuilder().getGlobals());
      boundIds.setDeclarations(mergedDecl);

      Accumulator[] accumulators;

      final boolean readLocalsFromTuple =
          PackageBuilderUtil.isReadLocalsFromTuple(context, accumDescr, source);

      if (accumDescr.isExternalFunction()) {
        // uses accumulate functions
        accumulators =
            buildExternalFunctions(
                context,
                accumDescr,
                dialect,
                decls,
                sourceOuterDeclr,
                boundIds,
                readLocalsFromTuple);
      } else {
        // it is a custom accumulate
        accumulators =
            buildCustomAccumulate(
                context,
                accumDescr,
                dialect,
                decls,
                sourceOuterDeclr,
                boundIds,
                readLocalsFromTuple);
      }

      List<Declaration> requiredDeclarations = new ArrayList<Declaration>();
      for (Accumulator acc : accumulators) {
        MvelAccumulator mvelAcc = (MvelAccumulator) acc;
        Collections.addAll(requiredDeclarations, mvelAcc.getRequiredDeclarations());
      }

      MVELDialectRuntimeData data =
          (MVELDialectRuntimeData)
              context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");

      Accumulate accumulate;
      if (accumDescr.isMultiFunction()) {
        accumulate =
            new MultiAccumulate(
                source,
                requiredDeclarations.toArray(new Declaration[requiredDeclarations.size()]),
                accumulators);
        int index = 0;
        for (Accumulator accumulator : accumulators) {
          data.addCompileable(
              ((MultiAccumulate) accumulate).new Wirer(index++), (MVELCompileable) accumulator);
          ((MVELCompileable) accumulator).compile(data, context.getRule());
        }
      } else {
        accumulate =
            new SingleAccumulate(
                source,
                requiredDeclarations.toArray(new Declaration[requiredDeclarations.size()]),
                accumulators[0]);
        data.addCompileable(
            ((SingleAccumulate) accumulate).new Wirer(), (MVELCompileable) accumulators[0]);
        ((MVELCompileable) accumulators[0]).compile(data, context.getRule());
      }

      return accumulate;
    } catch (Exception e) {
      DialectUtil.copyErrorLocation(e, descr);
      context.addError(
          new DescrBuildError(
              context.getParentDescr(),
              descr,
              e,
              "Unable to build expression for 'accumulate' : " + e.getMessage()));
      return null;
    } finally {
      context.setTypesafe(typesafe);
    }
  }
  public void build(final RuleBuildContext context, String consequenceName) {

    // pushing consequence LHS into the stack for variable resolution
    context.getBuildStack().push(context.getRule().getLhs());

    try {
      MVELDialect dialect = (MVELDialect) context.getDialect(context.getDialect().getId());

      final RuleDescr ruleDescr = context.getRuleDescr();

      String text =
          (Rule.DEFAULT_CONSEQUENCE_NAME.equals(consequenceName))
              ? (String) ruleDescr.getConsequence()
              : (String) ruleDescr.getNamedConsequences().get(consequenceName);

      text = processMacros(text);

      Map<String, Declaration> decls =
          context.getDeclarationResolver().getDeclarations(context.getRule());

      AnalysisResult analysis =
          dialect.analyzeBlock(
              context,
              context.getRuleDescr(),
              dialect.getInterceptors(),
              text,
              new BoundIdentifiers(
                  DeclarationScopeResolver.getDeclarationClasses(decls),
                  context.getPackageBuilder().getGlobals(),
                  null,
                  KnowledgeHelper.class),
              null,
              "drools",
              KnowledgeHelper.class);

      if (analysis == null) {
        // something bad happened, issue already logged in errors
        return;
      }

      final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();

      final Declaration[] declarations = new Declaration[usedIdentifiers.getDeclrClasses().size()];
      String[] declrStr = new String[declarations.length];
      int j = 0;
      for (String str : usedIdentifiers.getDeclrClasses().keySet()) {
        declrStr[j] = str;
        declarations[j++] = decls.get(str);
      }
      Arrays.sort(declarations, SortDeclarations.instance);
      for (int i = 0; i < declrStr.length; i++) {
        declrStr[i] = declarations[i].getIdentifier();
      }
      context.getRule().setRequiredDeclarationsForConsequence(consequenceName, declrStr);
      MVELCompilationUnit unit =
          dialect.getMVELCompilationUnit(
              text,
              analysis,
              declarations,
              null,
              null,
              context,
              "drools",
              KnowledgeHelper.class,
              false);

      MVELConsequence expr = new MVELConsequence(unit, dialect.getId());

      if (Rule.DEFAULT_CONSEQUENCE_NAME.equals(consequenceName)) {
        context.getRule().setConsequence(expr);
      } else {
        context.getRule().addNamedConsequence(consequenceName, expr);
      }

      MVELDialectRuntimeData data =
          (MVELDialectRuntimeData)
              context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
      data.addCompileable(context.getRule(), expr);

      expr.compile(data);
    } catch (final Exception e) {
      copyErrorLocation(e, context.getRuleDescr());
      context.addError(
          new DescrBuildError(
              context.getParentDescr(),
              context.getRuleDescr(),
              null,
              "Unable to build expression for 'consequence': "
                  + e.getMessage()
                  + " '"
                  + context.getRuleDescr().getConsequence()
                  + "'"));
    }
  }