void dynamic_context::get_variable(
    ulong varid,
    const store::Item_t& varname,
    const QueryLoc& loc,
    store::Item_t& itemValue,
    store::TempSeq_t& seqValue) const
{
  itemValue = NULL;
  seqValue = NULL;

  if (varid >= theVarValues.size() ||
      theVarValues[varid].theState == VarValue::undeclared)
  {
    zstring varName = static_context::var_name(varname.getp());

    if (varid >= theVarValues.size() ||
        theVarValues[varid].theIsExternalOrLocal ||
        (varid > 0 && varid < MAX_IDVARS_RESERVED))
    {
      RAISE_ERROR(err::XPDY0002, loc,
      ERROR_PARAMS(ZED(XPDY0002_VariableUndeclared_2), varName));
    }
    else
    {
      RAISE_ERROR(err::XQDY0054, loc, ERROR_PARAMS(varName));
    }
  }

  const VarValue& var = theVarValues[varid];

  if (var.theState == VarValue::declared)
  {
    zstring varName = static_context::var_name(varname.getp());

    if (var.theIsExternalOrLocal)
    {
      RAISE_ERROR(err::XPDY0002, loc,
      ERROR_PARAMS(ZED(XPDY0002_VariableHasNoValue_2), varName));
    }
    else
    {
      RAISE_ERROR(err::XQDY0054, loc, ERROR_PARAMS(varName));
    }
  }

  if (var.theState == VarValue::item)
    itemValue = var.theValue.item;
  else
    seqValue = var.theValue.temp_seq;
}
void processOptions(store::Item_t item, store::LoadProperties& props, static_context* theSctx, const QueryLoc& loc)
{
  URI lValidatedBaseUri;
  store::Item_t child, tempItem;

  if (item.getp() == NULL)
    return;

#ifndef ZORBA_NO_XMLSCHEMA
  if (item->isValidated())
  {
    if (item->getNodeName() == NULL
        ||
        item->getNodeName()->getNamespace() != static_context::ZORBA_XML_FN_OPTIONS_NS)
    {
      throw XQUERY_EXCEPTION(zerr::ZXQD0003_INCONSISTENT_PARSE_FRAGMENT_OPTIONS,
                             ERROR_PARAMS(ZED(ParseFragmentInvalidOptions)), ERROR_LOC( loc ));
    }
  }
  else
  {
    tempItem = NULL; // used as the effectiveValidationValue()'s typeName
    Validator::effectiveValidationValue(
        item,
        item,
        tempItem,
        theSctx->get_typemanager(),
        ParseConstants::val_strict,
        theSctx,
        loc);
  }
#endif

  store::Iterator_t children = item->getChildren();
  children->open();

  while (children->next(child))
  {
    if (child->getNodeKind() != store::StoreConsts::elementNode)
      continue;

    if (child->getNodeName()->getLocalName() == "base-uri")
    {
      store::Item_t attr = getFirstAttribute(child);

      try {
        lValidatedBaseUri = URI(attr->getStringValue());
      } catch (ZorbaException const& /* e */) {
        throw XQUERY_EXCEPTION(
          err::FODC0007,
          ERROR_PARAMS( attr->getStringValue() ),
          ERROR_LOC( loc )
        );
      }

      if (!lValidatedBaseUri.is_absolute()) {
        throw XQUERY_EXCEPTION(
          err::FODC0007,
          ERROR_PARAMS( lValidatedBaseUri.toString() ),
          ERROR_LOC( loc )
        );
      }

      props.setBaseUri(attr->getStringValue());
    }
    else if (child->getNodeName()->getLocalName() == "no-error")
      props.setNoError(true);
    else if (child->getNodeName()->getLocalName() == "strip-boundary-space")
      props.setStripWhitespace(true);
    else if (child->getNodeName()->getLocalName() == "schema-validate")
    {
      store::Item_t attr = getFirstAttribute(child);
      if (attr->getStringValue() == "strict")
        props.setSchemaStrictValidate(true);
      else
        props.setSchemaLaxValidate(true);
    }
    else if (child->getNodeName()->getLocalName() == "DTD-validate")
      props.setDTDValidate(true);
    else if (child->getNodeName()->getLocalName() == "DTD-load")
      props.setDTDLoad(true);
    else if (child->getNodeName()->getLocalName() == "default-DTD-attributes")
      props.setDefaultDTDAttributes(true);
    else if (child->getNodeName()->getLocalName() == "parse-external-parsed-entity")
    {
      props.setParseExternalParsedEntity(true);
      store::Item_t attr;
      store::Iterator_t attribs = child->getAttributes();
      attribs->open();
      while (attribs->next(attr))
      {
        if (attr->getNodeName()->getLocalName() == "skip-root-nodes")
          props.setSkipRootNodes(ztd::aton<xs_int>(attr->getStringValue().c_str()));
        else if (attr->getNodeName()->getLocalName() == "skip-top-level-text-nodes")
          props.setSkipTopLevelTextNodes(true);
        else if (attr->getNodeName()->getLocalName() == "error-on-doctype")
          props.setErrorOnDoctype(true);
      }
      attribs->close();
    }
    else if (child->getNodeName()->getLocalName() == "substitute-entities")
      props.setSubstituteEntities(true);
    else if (child->getNodeName()->getLocalName() == "xinclude-substitutions")
      props.setXincludeSubstitutions(true);
    else if (child->getNodeName()->getLocalName() == "remove-redundant-ns")
      props.setRemoveRedundantNS(true);
    else if (child->getNodeName()->getLocalName() == "no-CDATA")
      props.setNoCDATA(true);
    else if (child->getNodeName()->getLocalName() == "no-xinclude-nodes")
      props.setNoXIncludeNodes(true);
    else if (child->getNodeName()->getLocalName() == "no-network-access")
      props.setNoNetworkAccess(true);
  }

  children->close();

  if (props.getSchemaLaxValidate() + props.getSchemaStrictValidate() +
      props.getDTDValidate() + props.getParseExternalParsedEntity() > 1)
  {
    throw XQUERY_EXCEPTION(zerr::ZXQD0003_INCONSISTENT_PARSE_FRAGMENT_OPTIONS,
                           ERROR_PARAMS(ZED(ParseFragmentOptionCombinationNotAllowed)), ERROR_LOC( loc ));
  }
}
bool FunctionLookupIterator::nextImpl(
    store::Item_t& result,
    PlanState& planState) const
{
  CompilerCB* ccb = planState.theCompilerCB;
  store::ItemFactory* factory = GENV_ITEMFACTORY;

  store::Item_t qname;
  store::Item_t arityItem;
  store::Item_t ctxItem;
  store::Item_t ctxPosItem;
  store::Item_t ctxSizeItem;
  csize arity;
  function* f;

  result = NULL;
  
  PlanIteratorState* state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  consumeNext(qname, theChildren[0], planState);
  consumeNext(arityItem, theChildren[1], planState);

  try
  {
    arity = static_cast<zorba::csize>(to_xs_unsignedLong(arityItem->getIntegerValue()));
  }
  catch ( std::range_error const& )
  {
    RAISE_ERROR(err::XPST0017, loc,
    ERROR_PARAMS(arityItem->getIntegerValue(), ZED(NoParseFnArity)));
  }

  f = theSctx->lookup_fn(qname, arity);

  if (f != NULL && f->isContextual())
  {
    try
    {
      consumeNext(ctxItem, theChildren[2], planState);
      consumeNext(ctxPosItem, theChildren[3], planState);
      consumeNext(ctxSizeItem, theChildren[4], planState);
    }
    catch (const ZorbaException& e)
    {
      if (e.diagnostic() != err::XPDY0002)
        throw;
    }
  }
  
  try
  {
    static_context_t impSctx = theSctx->create_child_context();
    ccb->theSctxMap[ccb->theSctxMap.size() + 1] = impSctx;

    std::unique_ptr<dynamic_context> fiDctx;
    fiDctx.reset(new dynamic_context(planState.theGlobalDynCtx));

    if (ctxItem)
    {
      store::Item_t ctxItemName;
      factory->createQName(ctxItemName, "", "", static_context::DOT_VAR_NAME);

      var_expr* ve = ccb->theEM->
      create_var_expr(impSctx, NULL, loc, var_expr::local_var, ctxItemName);

      ve->set_unique_id(dynamic_context::IDVAR_CONTEXT_ITEM);

      impSctx->bind_var(ve, loc);

      fiDctx->add_variable(dynamic_context::IDVAR_CONTEXT_ITEM, ctxItem);
    }

    if (ctxPosItem)
    {
      store::Item_t ctxPosName;
      factory->createQName(ctxPosName, "", "", static_context::DOT_POS_VAR_NAME);

      var_expr* ve = ccb->theEM->
      create_var_expr(impSctx, NULL, loc, var_expr::local_var, ctxPosName);

      ve->set_unique_id(dynamic_context::IDVAR_CONTEXT_ITEM_POSITION);

      impSctx->bind_var(ve, loc);

      fiDctx->add_variable(dynamic_context::IDVAR_CONTEXT_ITEM_POSITION, ctxPosItem);
    }

    if (ctxSizeItem)
    {
      store::Item_t ctxSizeName;
      factory->createQName(ctxSizeName, "", "", static_context::DOT_SIZE_VAR_NAME);

      var_expr* ve = ccb->theEM->
      create_var_expr(impSctx, NULL, loc, var_expr::local_var, ctxSizeName);

      ve->set_unique_id(dynamic_context::IDVAR_CONTEXT_ITEM_SIZE);

      impSctx->bind_var(ve, loc);

      fiDctx->add_variable(dynamic_context::IDVAR_CONTEXT_ITEM_SIZE, ctxSizeItem);
    }

    expr* fiExpr = 
    Translator::translate_literal_function(qname, arity, ccb, impSctx, loc);
    
    FunctionItemInfo_t fiInfo =
    static_cast<function_item_expr*>(fiExpr)->get_fi_info();

    fiInfo->theCCB = ccb;

    if (fiInfo->numInScopeVars() > 0)
    {
      result = new FunctionItem(fiInfo, fiDctx.get());
      fiDctx.release();
    }
    else
    {
      result = new FunctionItem(fiInfo, NULL);
    }
  }
  catch (const ZorbaException& e)
  {
    if (e.diagnostic() != err::XPST0017)
      throw;
  }
  
  if (result.getp() != NULL)
    STACK_PUSH(true, state); 
    
  STACK_END(state);
}