1 /*
2  * Copyright 2006-2008 The FLWOR Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "stdafx.h"
17 
18 #include "common/common.h"
19 #include "api/staticcontextimpl.h"
20 
21 #include <zorba/error.h>
22 #include <zorba/external_module.h>
23 #include <zorba/diagnostic_handler.h>
24 #include <zorba/static_context_consts.h>
25 #include <zorba/typeident.h>
26 #include <zorba/util/path.h>
27 #include <zorba/empty_sequence.h>
28 #include <zorba/singleton_item_sequence.h>
29 
30 #include "store/api/item_factory.h"
31 #include "store/api/temp_seq.h"
32 
33 #include "api/unmarshaller.h"
34 #include "api/zorbaimpl.h"
35 #include "api/functionimpl.h"
36 #include "api/annotationimpl.h"
37 #include "api/xqueryimpl.h"
38 #include "api/invoke_item_sequence.h"
39 #include "api/staticcollectionmanagerimpl.h"
40 #include "api/vectoriterator.h"
41 
42 #include "context/static_context.h"
43 #include "context/static_context_consts.h"
44 #ifndef ZORBA_NO_FULL_TEXT
45 #include "stemmer_wrappers.h"
46 #include "thesaurus_wrappers.h"
47 #endif /* ZORBA_NO_FULL_TEXT */
48 #include "uri_resolver_wrappers.h"
49 
50 #include "compiler/parser/query_loc.h"
51 #include "compiler/api/compilercb.h"
52 #include "compiler/expression/var_expr.h"
53 
54 #include "functions/function.h"
55 
56 #include "system/globalenv.h"
57 
58 #include "types/casting.h"
59 #include "types/typeops.h"
60 
61 #include "diagnostics/xquery_diagnostics.h"
62 
63 #include "runtime/util/flowctl_exception.h"
64 
65 
66 namespace zorba {
67 
68 /*******************************************************************************
69   Create a StaticContextImpl obj as well as an internal static_context obj S.
70   S is created as a child of the zorba root sctx. This constructor is used
71   when the application wants to create its own static context to pass it as
72   input to one or more queries.
73 ********************************************************************************/
StaticContextImpl(DiagnosticHandler * aDiagnosticHandler)74 StaticContextImpl::StaticContextImpl(DiagnosticHandler* aDiagnosticHandler)
75   :
76   theCompilerCB(NULL),
77   theMaxVarId(dynamic_context::MAX_IDVARS_RESERVED),
78   theDiagnosticHandler(aDiagnosticHandler),
79   theUserDiagnosticHandler(true),
80   theCollectionMgr(0)
81 {
82   theCtx = GENV.getRootStaticContext().create_child_context();
83 
84   if ( ! theDiagnosticHandler )
85   {
86     theDiagnosticHandler = new DiagnosticHandler();
87     theUserDiagnosticHandler = false;
88   }
89 }
90 
91 
92 /*******************************************************************************
93   Create a StaticContextImpl obj to wrap a given internal static_context obj S.
94   This constructor is used when the static context of a query is returned to
95   the application (see XQueryImpl::getStaticContext()).
96 ********************************************************************************/
StaticContextImpl(static_context * aCtx,DiagnosticHandler * aDiagnosticHandler)97 StaticContextImpl::StaticContextImpl(
98     static_context* aCtx,
99     DiagnosticHandler* aDiagnosticHandler)
100   :
101   theCtx(aCtx),
102   theCompilerCB(NULL),
103   theMaxVarId(dynamic_context::MAX_IDVARS_RESERVED),
104   theDiagnosticHandler(aDiagnosticHandler),
105   theUserDiagnosticHandler(true),
106   theCollectionMgr(0)
107 {
108   if ( ! theDiagnosticHandler )
109   {
110     theDiagnosticHandler = new DiagnosticHandler();
111     theUserDiagnosticHandler = false;
112   }
113 }
114 
115 
116 /*******************************************************************************
117   Create a StaticContextImpl obj as well as an internal static_context obj S.
118   S is created as a child of the static_context obj associated with the given
119   StaticContextImpl obj. This is a private constructor that is invoked by the
120   StaticContextImpl::createChildContext() method.
121 ********************************************************************************/
StaticContextImpl(const StaticContextImpl & aStaticContext)122 StaticContextImpl::StaticContextImpl(const StaticContextImpl& aStaticContext)
123   :
124   StaticContext(),
125   theCompilerCB(NULL),
126   theMaxVarId(dynamic_context::MAX_IDVARS_RESERVED),
127   theDiagnosticHandler(aStaticContext.theDiagnosticHandler),
128   theUserDiagnosticHandler(aStaticContext.theUserDiagnosticHandler),
129   theCollectionMgr(0)
130 {
131   // hierarchy of contexts
132   theCtx = aStaticContext.theCtx->create_child_context();
133 
134   // bugfix
135   // if it's a default error handler, we need to create a new
136   // one since every context has it's own non-user error handler
137   // which he also needs to delete
138   if ( ! theUserDiagnosticHandler )
139   {
140     theDiagnosticHandler = new DiagnosticHandler();
141   }
142 }
143 
144 
145 /*******************************************************************************
146 
147 ********************************************************************************/
~StaticContextImpl()148 StaticContextImpl::~StaticContextImpl()
149 {
150   if ( ! theUserDiagnosticHandler )
151     delete theDiagnosticHandler;
152 
153   if ( theCollectionMgr )
154   {
155     delete theCollectionMgr;
156   }
157 
158   theCtx = NULL;
159 
160   if (theCompilerCB)
161     delete theCompilerCB;
162 }
163 
164 
165 /*******************************************************************************
166 
167 ********************************************************************************/
createChildContext() const168 StaticContext_t StaticContextImpl::createChildContext() const
169 {
170   try
171   {
172     StaticContext_t lContext(new StaticContextImpl(*this));
173     return lContext;
174   }
175   catch (ZorbaException const& e)
176   {
177     ZorbaImpl::notifyError(theDiagnosticHandler, e);
178   }
179   catch (std::exception const& e)
180   {
181     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
182   }
183   return StaticContext_t();
184 }
185 
186 
187 /*******************************************************************************
188 
189 ********************************************************************************/
190 bool
addNamespace(const String & aPrefix,const String & aURI)191 StaticContextImpl::addNamespace( const String& aPrefix, const String& aURI )
192 {
193   ZORBA_TRY
194     const zstring& lPrefix = Unmarshaller::getInternalString(aPrefix);
195     const zstring& lURI = Unmarshaller::getInternalString(aURI);
196     QueryLoc loc;
197     theCtx->bind_ns(lPrefix, lURI, loc);
198     return true;
199   ZORBA_CATCH
200   return false;
201 }
202 
203 
204 /*******************************************************************************
205 
206 ********************************************************************************/
207 String
getNamespaceURIByPrefix(const String & aPrefix) const208 StaticContextImpl::getNamespaceURIByPrefix(const String& aPrefix) const
209 {
210   try
211   {
212     QueryLoc loc;
213     const zstring& lPrefix = Unmarshaller::getInternalString(aPrefix);
214     zstring ns;
215     theCtx->lookup_ns(ns, lPrefix, loc);
216     return Unmarshaller::newString( ns );
217   }
218   catch (ZorbaException const& e)
219   {
220     ZorbaImpl::notifyError(theDiagnosticHandler, e);
221   }
222   catch (std::exception const& e)
223   {
224     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
225   }
226   return "";
227 }
228 
229 /*******************************************************************************
230 
231 ********************************************************************************/
232 void
getNamespaceBindings(NsBindings & aBindings) const233 StaticContextImpl::getNamespaceBindings( NsBindings& aBindings ) const
234 {
235   try
236   {
237     store::NsBindings lBindings;
238     theCtx->get_namespace_bindings(lBindings);
239     aBindings.reserve(aBindings.size() + lBindings.size());
240 
241     for (store::NsBindings::const_iterator lIter = lBindings.begin();
242          lIter != lBindings.end(); ++lIter)
243     {
244       aBindings.push_back(
245         std::pair<zorba::String, zorba::String>(
246           Unmarshaller::newString(lIter->first),
247           Unmarshaller::newString(lIter->second)
248         )
249       );
250     }
251   }
252   catch (ZorbaException const& e)
253   {
254     ZorbaImpl::notifyError(theDiagnosticHandler, e);
255   }
256   catch (std::exception const& e)
257   {
258     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
259   }
260 }
261 
262 /*******************************************************************************
263 
264 ********************************************************************************/
265 bool
setDefaultElementAndTypeNamespace(const String & aURI)266 StaticContextImpl::setDefaultElementAndTypeNamespace(const String& aURI)
267 {
268   ZORBA_TRY
269     const zstring& lURI = Unmarshaller::getInternalString(aURI);
270     theCtx->set_default_elem_type_ns(lURI, false, QueryLoc::null);
271     return true;
272   ZORBA_CATCH
273   return false;
274 }
275 
276 
277 /*******************************************************************************
278 
279 ********************************************************************************/
280 String
getDefaultElementAndTypeNamespace() const281 StaticContextImpl::getDefaultElementAndTypeNamespace() const
282 {
283   try
284   {
285     return theCtx->default_elem_type_ns().str();
286   }
287   catch (ZorbaException const& e)
288   {
289     ZorbaImpl::notifyError(theDiagnosticHandler, e);
290   }
291   catch (std::exception const& e)
292   {
293     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
294   }
295   return "";
296 }
297 
298 
299 /*******************************************************************************
300 
301 ********************************************************************************/
302 bool
setDefaultFunctionNamespace(const String & aURI)303 StaticContextImpl::setDefaultFunctionNamespace(const String& aURI)
304 {
305   ZORBA_TRY
306     const zstring& lURI = Unmarshaller::getInternalString(aURI);
307     QueryLoc loc;
308     theCtx->set_default_function_ns(lURI, false, loc);
309     return true;
310   ZORBA_CATCH
311   return false;
312 }
313 
314 
315 /*******************************************************************************
316 
317 ********************************************************************************/
318 String
getDefaultFunctionNamespace() const319 StaticContextImpl::getDefaultFunctionNamespace( ) const
320 {
321   try
322   {
323     return theCtx->default_function_ns().str();
324   }
325   catch (ZorbaException const& e)
326   {
327     ZorbaImpl::notifyError(theDiagnosticHandler, e);
328   }
329   catch (std::exception const& e)
330   {
331     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
332   }
333   return "";
334 }
335 
336 
337 /*******************************************************************************
338 
339 ********************************************************************************/
340 void
addCollation(const String & URI)341 StaticContextImpl::addCollation( const String& URI )
342 {
343   ZORBA_TRY
344     const zstring& lURI = Unmarshaller::getInternalString(URI);
345     theCtx->add_collation(lURI.str(), QueryLoc::null);
346   ZORBA_CATCH
347 }
348 
349 
350 /*******************************************************************************
351 
352 ********************************************************************************/
setDefaultCollation(const String & URI)353 void StaticContextImpl::setDefaultCollation( const String& URI )
354 {
355   ZORBA_TRY
356     const zstring& lURI = Unmarshaller::getInternalString(URI);
357     theCtx->set_default_collation(lURI.str(), QueryLoc::null);
358   ZORBA_CATCH
359 }
360 
361 
362 /*******************************************************************************
363 
364 ********************************************************************************/
getDefaultCollation() const365 String StaticContextImpl::getDefaultCollation() const
366 {
367   try
368   {
369     return theCtx->get_default_collation(QueryLoc::null);
370   }
371   catch (ZorbaException const& e)
372   {
373     ZorbaImpl::notifyError(theDiagnosticHandler, e);
374   }
375   catch (std::exception const& e)
376   {
377     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
378   }
379   return "";
380 }
381 
382 
383 /*******************************************************************************
384 
385 ********************************************************************************/
setXQueryVersion(xquery_version_t version)386 bool StaticContextImpl::setXQueryVersion(xquery_version_t version)
387 {
388   ZORBA_TRY
389     if ( version == xquery_version_1_0)
390       theCtx->set_xquery_version(StaticContextConsts::xquery_version_1_0);
391     else
392       theCtx->set_xquery_version(StaticContextConsts::xquery_version_3_0);
393     return true;
394   ZORBA_CATCH
395   return false;
396 }
397 
398 
399 /*******************************************************************************
400 
401 ********************************************************************************/
getXQueryVersion() const402 xquery_version_t StaticContextImpl::getXQueryVersion() const
403 {
404   try {
405     return theCtx->xquery_version()==StaticContextConsts::xquery_version_1_0?
406       xquery_version_1_0:xquery_version_3_0;
407   } catch (ZorbaException const& e) {
408     ZorbaImpl::notifyError(theDiagnosticHandler, e);
409   } catch (std::exception const& e) {
410     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
411   }
412   return xquery_version_1_0;
413 }
414 
415 
416 /*******************************************************************************
417 
418 ********************************************************************************/
setXPath1_0CompatibMode(xpath1_0compatib_mode_t mode)419 bool StaticContextImpl::setXPath1_0CompatibMode( xpath1_0compatib_mode_t mode )
420 {
421   ZORBA_TRY
422     if ( mode == xpath1_0)
423       theCtx->set_xpath_compatibility(StaticContextConsts::xpath1_0_only);
424     else
425       theCtx->set_xpath_compatibility(StaticContextConsts::xpath2_0);
426     return true;
427   ZORBA_CATCH
428   return false;
429 }
430 
431 
432 /*******************************************************************************
433 
434 ********************************************************************************/
getXPath1_0CompatibMode() const435 xpath1_0compatib_mode_t StaticContextImpl::getXPath1_0CompatibMode( ) const
436 {
437   try
438   {
439     return (theCtx->xpath_compatibility() == StaticContextConsts::xpath1_0_only?
440             xpath1_0 :
441             xpath2_0);
442   }
443   catch (ZorbaException const& e)
444   {
445     ZorbaImpl::notifyError(theDiagnosticHandler, e);
446   }
447   catch (std::exception const& e)
448   {
449     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
450   }
451   return xpath2_0;
452 }
453 
454 
455 /*******************************************************************************
456 
457 ********************************************************************************/
458 bool
setConstructionMode(construction_mode_t mode)459 StaticContextImpl::setConstructionMode( construction_mode_t mode )
460 {
461   ZORBA_TRY
462       if ( mode == preserve_cons)
463         theCtx->set_construction_mode(StaticContextConsts::cons_preserve);
464       else
465         theCtx->set_construction_mode(StaticContextConsts::cons_strip);
466       return true;
467   ZORBA_CATCH
468   return false;
469 }
470 
471 
472 construction_mode_t
getConstructionMode() const473 StaticContextImpl::getConstructionMode( ) const
474 {
475   try {
476     return theCtx->construction_mode()==StaticContextConsts::cons_preserve?
477       preserve_cons:strip_cons;
478   } catch (ZorbaException const& e) {
479     ZorbaImpl::notifyError(theDiagnosticHandler, e);
480   } catch (std::exception const& e) {
481     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
482   }
483   return preserve_cons;
484 }
485 
486 
487 bool
setOrderingMode(ordering_mode_t mode)488 StaticContextImpl::setOrderingMode( ordering_mode_t mode )
489 {
490   ZORBA_TRY
491     if ( mode == ordered)
492       theCtx->set_ordering_mode(StaticContextConsts::ordered);
493     else
494       theCtx->set_ordering_mode(StaticContextConsts::unordered);
495     return true;
496   ZORBA_CATCH
497   return false;
498 }
499 
500 
501 ordering_mode_t
getOrderingMode() const502 StaticContextImpl::getOrderingMode( ) const
503 {
504   try {
505     return theCtx->ordering_mode()==StaticContextConsts::ordered?ordered:unordered;
506   } catch (ZorbaException const& e) {
507     ZorbaImpl::notifyError(theDiagnosticHandler, e);
508   } catch (std::exception const& e) {
509     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
510   }
511   return ordered;
512 }
513 
514 
515 bool
setDefaultOrderForEmptySequences(order_empty_mode_t mode)516 StaticContextImpl::setDefaultOrderForEmptySequences(order_empty_mode_t mode )
517 {
518   ZORBA_TRY
519     if ( mode == empty_greatest)
520       theCtx->set_empty_order_mode(StaticContextConsts::empty_greatest);
521     else
522       theCtx->set_empty_order_mode(StaticContextConsts::empty_least);
523       return true;
524   ZORBA_CATCH
525   return false;
526 }
527 
528 
529 order_empty_mode_t
getDefaultOrderForEmptySequences() const530 StaticContextImpl::getDefaultOrderForEmptySequences( ) const
531 {
532   try {
533     return theCtx->empty_order_mode()==StaticContextConsts::empty_greatest?
534       empty_greatest:empty_least;
535   } catch (ZorbaException const& e) {
536     ZorbaImpl::notifyError(theDiagnosticHandler, e);
537   } catch (std::exception const& e) {
538     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
539   }
540   return empty_greatest;
541 }
542 
543 
544 bool
setBoundarySpacePolicy(boundary_space_mode_t mode)545 StaticContextImpl::setBoundarySpacePolicy( boundary_space_mode_t mode )
546 {
547   ZORBA_TRY
548     if ( mode == preserve_space)
549       theCtx->set_boundary_space_mode(StaticContextConsts::preserve_space);
550     else
551       theCtx->set_boundary_space_mode(StaticContextConsts::strip_space);
552     return true;
553   ZORBA_CATCH
554   return false;
555 }
556 
557 
558 boundary_space_mode_t
getBoundarySpacePolicy() const559 StaticContextImpl::getBoundarySpacePolicy( ) const
560 {
561   try
562   {
563     return theCtx->boundary_space_mode()==StaticContextConsts::preserve_space?
564       preserve_space:strip_space;
565   }
566   catch (ZorbaException const& e)
567   {
568     ZorbaImpl::notifyError(theDiagnosticHandler, e);
569   }
570   catch (std::exception const& e)
571   {
572     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
573   }
574   return preserve_space;
575 }
576 
577 
578 bool
setCopyNamespacesMode(preserve_mode_t preserve,inherit_mode_t inherit)579 StaticContextImpl::setCopyNamespacesMode(
580     preserve_mode_t preserve,
581     inherit_mode_t inherit)
582 {
583   ZORBA_TRY
584   {
585     if (preserve == preserve_ns)
586       theCtx->set_preserve_ns(true);
587     else
588       theCtx->set_preserve_ns(false);
589 
590     if (inherit == inherit_ns)
591       theCtx->set_inherit_ns(true);
592     else
593       theCtx->set_inherit_ns(true);
594 
595     return true;
596   }
597   ZORBA_CATCH
598   return false;
599 }
600 
601 
602 void
getCopyNamespacesMode(preserve_mode_t & preserve,inherit_mode_t & inherit) const603 StaticContextImpl::getCopyNamespacesMode(
604     preserve_mode_t& preserve,
605     inherit_mode_t& inherit) const
606 {
607   ZORBA_TRY
608   {
609     preserve = (theCtx->preserve_ns() ? preserve_ns : no_preserve_ns);
610     inherit = (theCtx->inherit_ns() ? inherit_ns : no_inherit_ns);
611   }
612   ZORBA_CATCH
613 }
614 
615 
616 bool
setBaseURI(const String & aBaseURI)617 StaticContextImpl::setBaseURI( const String& aBaseURI )
618 {
619   try
620   {
621     const zstring& baseURI = Unmarshaller::getInternalString(aBaseURI);
622     zstring baseURI2 = baseURI;
623 
624     if(!GenericCast::instance()->isCastable(baseURI2,
625                                             &*GENV_TYPESYSTEM.ANY_URI_TYPE_ONE,
626                                             &GENV_TYPESYSTEM))
627     {
628       throw ZORBA_EXCEPTION(
629         zerr::ZXQP0020_INVALID_URI, ERROR_PARAMS( baseURI )
630       );
631     }
632 
633     theCtx->set_base_uri(baseURI, false);
634   }
635   catch (ZorbaException const& e)
636   {
637     ZorbaImpl::notifyError(theDiagnosticHandler, e);
638     return false;
639   }
640   catch (std::exception const& e)
641   {
642     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
643     return false;
644   }
645   return true;
646 }
647 
648 
649 /*******************************************************************************
650 
651 ********************************************************************************/
652 String
getBaseURI() const653 StaticContextImpl::getBaseURI( ) const
654 {
655   try
656   {
657     zstring lBaseURI = theCtx->get_base_uri();
658     return lBaseURI.str();
659   }
660   catch (ZorbaException const& e)
661   {
662     ZorbaImpl::notifyError(theDiagnosticHandler, e);
663   }
664   catch (std::exception const& e)
665   {
666     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
667   }
668   return "";
669 }
670 
671 
672 /*******************************************************************************
673 
674 ********************************************************************************/
675 validation_mode_t
getRevalidationMode() const676 StaticContextImpl::getRevalidationMode() const
677 {
678   return validate_lax;
679 }
680 
681 
682 /*******************************************************************************
683 
684 ********************************************************************************/
685 void
setRevalidationMode(validation_mode_t aMode)686 StaticContextImpl::setRevalidationMode(validation_mode_t aMode)
687 {
688   ZORBA_TRY
689     if (aMode == validate_skip)
690       theCtx->set_validation_mode(StaticContextConsts::skip_validation);
691     else if (aMode == validate_lax)
692       theCtx->set_validation_mode(StaticContextConsts::lax_validation);
693     else
694       theCtx->set_validation_mode(StaticContextConsts::strict_validation);
695   ZORBA_CATCH
696 }
697 
698 
699 /*******************************************************************************
700 
701 ********************************************************************************/
702 bool
registerModule(ExternalModule * aModule)703 StaticContextImpl::registerModule(ExternalModule* aModule)
704 {
705   try
706   {
707     theCtx->bind_external_module(aModule);
708   }
709   catch (ZorbaException const& e)
710   {
711     ZorbaImpl::notifyError(theDiagnosticHandler, e);
712     return false;
713   }
714   return true;
715 }
716 
717 
718 /*******************************************************************************
719  URI Mapper
720 *******************************************************************************/
721 void
registerURIMapper(URIMapper * aMapper)722 StaticContextImpl::registerURIMapper(URIMapper* aMapper)
723 {
724   // QQQ memory management?
725   theCtx->add_uri_mapper(new URIMapperWrapper(*aMapper));
726 }
727 
728 /*******************************************************************************
729  URL Resolver
730 *******************************************************************************/
731 void
registerURLResolver(URLResolver * aResolver)732 StaticContextImpl::registerURLResolver(URLResolver* aResolver)
733 {
734   // QQQ memory management?
735   theCtx->add_url_resolver(new URLResolverWrapper(*aResolver));
736 }
737 
738 
739 
740 /*******************************************************************************
741 
742 ********************************************************************************/
743 void
setDocumentType(const String & aDocUri,TypeIdentifier_t type)744 StaticContextImpl::setDocumentType(const String& aDocUri, TypeIdentifier_t type)
745 {
746   xqtref_t xqType = NULL;
747   if (type != NULL) {
748     xqType = theCtx->get_typemanager()->create_type(*type);
749   }
750 
751   const zstring& uri = Unmarshaller::getInternalString(aDocUri);
752   theCtx->bind_document(uri, xqType);
753 }
754 
755 
756 /*******************************************************************************
757 
758 ********************************************************************************/
759 TypeIdentifier_t
getDocumentType(const String & aDocUri) const760 StaticContextImpl::getDocumentType(const String& aDocUri) const
761 {
762   const zstring& uri = Unmarshaller::getInternalString(aDocUri);
763   xqtref_t xqType = theCtx->lookup_document(uri);
764   TypeIdentifier_t type = NULL;
765   if (xqType == NULL)
766   {
767     return NULL;
768   }
769 
770   return TypeOps::get_type_identifier(theCtx->get_typemanager(), *xqType);
771 }
772 
773 
774 /*******************************************************************************
775 
776 ********************************************************************************/
777 void
setCollectionType(const String & aCollectionUri,TypeIdentifier_t type)778 StaticContextImpl::setCollectionType(const String& aCollectionUri, TypeIdentifier_t type)
779 {
780   xqtref_t xqType = NULL;
781   if (type != NULL)
782   {
783     xqType = theCtx->get_typemanager()->create_type(*type);
784   }
785   zstring& uri = Unmarshaller::getInternalString(aCollectionUri);
786   theCtx->bind_w3c_collection(uri, xqType);
787 }
788 
789 
790 /*******************************************************************************
791 
792 ********************************************************************************/
793 TypeIdentifier_t
getCollectionType(const String & aCollectionUri) const794 StaticContextImpl::getCollectionType(const String& aCollectionUri) const
795 {
796 
797   const zstring& uri = Unmarshaller::getInternalString(aCollectionUri);
798   const XQType* xqType = theCtx->lookup_w3c_collection(uri);
799   TypeIdentifier_t type = NULL;
800   if (xqType == NULL)
801   {
802     return NULL;
803   }
804   return TypeOps::get_type_identifier(theCtx->get_typemanager(), *xqType);
805 }
806 
807 /*******************************************************************************
808 
809 ********************************************************************************/
containsFunction(const String & aFnNameUri,const String & aFnNameLocal,int arity) const810 bool StaticContextImpl::containsFunction(
811     const String& aFnNameUri,
812     const String& aFnNameLocal,
813     int arity) const
814 {
815   store::Item_t qnameItem;
816   GENV_ITEMFACTORY->createQName(qnameItem,
817                                 Unmarshaller::getInternalString(aFnNameUri),
818                                 zstring(),
819                                 Unmarshaller::getInternalString(aFnNameLocal));
820 
821   const function* fn = theCtx->lookup_fn(qnameItem, arity);
822 
823   return fn != NULL;
824 }
825 
826 
827 /*******************************************************************************
828 
829 ********************************************************************************/
findFunctions(const Item & aQName,std::vector<Function_t> & aFunctions) const830 void StaticContextImpl::findFunctions(
831     const Item& aQName,
832     std::vector<Function_t>& aFunctions) const
833 {
834   try
835   {
836     store::Item* lQName = Unmarshaller::getInternalItem(aQName);
837 
838     std::vector<function*> lInternalFunctions;
839 
840     theCtx->find_functions(lQName, lInternalFunctions);
841 
842     for (std::vector<function*>::const_iterator lIter = lInternalFunctions.begin();
843          lIter != lInternalFunctions.end(); ++lIter)
844     {
845       Function_t lFunc(new FunctionImpl(*lIter, theDiagnosticHandler));
846       aFunctions.push_back(lFunc);
847     }
848 
849     assert ( aFunctions.size() == lInternalFunctions.size() );
850   }
851   catch (ZorbaException const& e)
852   {
853     ZorbaImpl::notifyError(theDiagnosticHandler, e);
854   }
855 }
856 
857 
858 void
disableFunction(const Function_t & aFunction)859 StaticContextImpl::disableFunction(const Function_t& aFunction)
860 {
861   disableFunction(aFunction->getQName(), aFunction->getArity());
862 }
863 
864 
865 void
disableFunction(const Item & aQName,int arity)866 StaticContextImpl::disableFunction(const Item& aQName, int arity)
867 {
868   theCtx->unbind_fn(Unmarshaller::getInternalItem(aQName), arity);
869 }
870 
871 
872 void
getFunctions(std::vector<Function_t> & aFunctions) const873 StaticContextImpl::getFunctions(std::vector<Function_t>& aFunctions) const
874 {
875   try
876   {
877     std::vector<function*> lInternalFunctions;
878 
879     theCtx->get_functions(lInternalFunctions);
880 
881     for (std::vector<function*>::const_iterator lIter = lInternalFunctions.begin();
882          lIter != lInternalFunctions.end(); ++lIter)
883     {
884       Function_t lFunc(new FunctionImpl(*lIter, theDiagnosticHandler));
885       aFunctions.push_back(lFunc);
886     }
887   }
888   catch (ZorbaException const& e)
889   {
890     ZorbaImpl::notifyError(theDiagnosticHandler, e);
891   }
892 }
893 
894 
895 void
getFunctions(const String & aFnNameUri,uint32_t arity,std::vector<Function_t> & aFunctions) const896 StaticContextImpl::getFunctions(
897     const String& aFnNameUri,
898     uint32_t arity,
899     std::vector<Function_t>& aFunctions) const
900 {
901   try
902   {
903     std::vector<function*> lInternalFunctions;
904 
905     theCtx->get_functions(lInternalFunctions);
906 
907     for (std::vector<function*>::const_iterator lIter = lInternalFunctions.begin();
908          lIter != lInternalFunctions.end(); ++lIter)
909     {
910       const zstring& lNamespace = (*lIter)->getName()->getNamespace();
911       if (lNamespace == aFnNameUri.c_str() && (*lIter)->getArity() == arity)
912       {
913         Function_t lFunc(new FunctionImpl(*lIter, theDiagnosticHandler));
914         aFunctions.push_back(lFunc);
915       }
916     }
917   }
918   catch (ZorbaException const& e)
919   {
920     ZorbaImpl::notifyError(theDiagnosticHandler, e);
921   }
922 }
923 
924 
925 void
getFunctionAnnotations(const Item & aQName,int arity,std::vector<Annotation_t> & aAnnotations) const926 StaticContextImpl::getFunctionAnnotations(
927     const Item& aQName,
928     int arity,
929     std::vector<Annotation_t>& aAnnotations) const
930 {
931   aAnnotations.clear();
932 
933   const function* f = theCtx->lookup_fn(Unmarshaller::getInternalItem(aQName), arity);
934   if (f == NULL)
935     return;
936 
937   const AnnotationList* ann_list = f->getAnnotationList();
938   if (ann_list == NULL)
939     return;
940 
941   try
942   {
943     for (csize i = 0; i < ann_list->size(); ++i)
944       aAnnotations.push_back(new AnnotationImpl(ann_list->get(i)));
945   }
946   catch (ZorbaException const& e)
947   {
948     ZorbaImpl::notifyError(theDiagnosticHandler, e);
949   }
950 }
951 
952 
953 void
setContextItemStaticType(TypeIdentifier_t type)954 StaticContextImpl::setContextItemStaticType(TypeIdentifier_t type)
955 {
956   xqtref_t xqType = NULL;
957   if (type != NULL)
958   {
959     xqType = theCtx->get_typemanager()->create_type(*type);
960   }
961   theCtx->set_context_item_type(xqType, QueryLoc::null);
962 }
963 
964 
965 TypeIdentifier_t
getContextItemStaticType() const966 StaticContextImpl::getContextItemStaticType() const
967 {
968   xqtref_t type = theCtx->get_context_item_type();
969   if (type == NULL)
970   {
971     return NULL;
972   }
973   return TypeOps::get_type_identifier(theCtx->get_typemanager(), *type);
974 }
975 
976 
977 void
setTraceStream(std::ostream & os)978 StaticContextImpl::setTraceStream(std::ostream& os)
979 {
980   theCtx->set_trace_stream(os);
981 }
982 
983 
984 void
resetTraceStream()985 StaticContextImpl::resetTraceStream()
986 {
987   theCtx->set_trace_stream(std::cerr);
988 }
989 
990 
991 bool
getOption(const Item & aQName,String & aOptionValue) const992 StaticContextImpl::getOption(const Item& aQName, String& aOptionValue) const
993 {
994   try
995   {
996     const store::Item* lQName = Unmarshaller::getInternalItem(aQName);
997     zstring lOption;
998     if (theCtx->lookup_option(lQName, lOption))
999     {
1000       aOptionValue = lOption.str();
1001       return true;
1002     }
1003     else
1004     {
1005       return false;
1006     }
1007   }
1008   catch (ZorbaException const& e)
1009   {
1010     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1011   }
1012   return false;
1013 }
1014 
1015 
1016 void
declareOption(const Item & aQName,const String & aOptionValue)1017 StaticContextImpl::declareOption(const Item& aQName, const String& aOptionValue)
1018 {
1019   try
1020   {
1021     const store::Item* lQName = Unmarshaller::getInternalItem(aQName);
1022     const zstring& lOptionValue = Unmarshaller::getInternalString(aOptionValue);
1023     theCtx->bind_option(lQName, lOptionValue, QueryLoc::null);
1024   }
1025   catch (ZorbaException const& e)
1026   {
1027     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1028   }
1029 }
1030 
1031 
loadProlog(const String & prolog,const Zorba_CompilerHints_t & hints)1032 void StaticContextImpl::loadProlog(
1033     const String& prolog,
1034     const Zorba_CompilerHints_t& hints)
1035 {
1036   ZORBA_ASSERT(theCompilerCB == NULL);
1037 
1038   // Create and compile an internal query whose prolog is the given prolog and
1039   // its body is just the emtpy sequence expression: "()".
1040   XQueryImpl impl;
1041   impl.loadProlog(prolog, this, hints);
1042 
1043   // Copy theSctxMap of the internal query into "this". When "this" is then passed
1044   // as an input to a user query Q, theSctxMap of Q will be initialized as a copy
1045   // of this->theSctxMap.
1046   //theSctxMap = impl.theCompilerCB->theSctxMap;
1047   theCompilerCB = impl.theCompilerCB;
1048   impl.theCompilerCB = NULL;
1049 }
1050 
1051 
1052 static void
toInternalPath(const std::vector<String> & aPublicStrings,std::vector<zstring> & aInternalStrings)1053 toInternalPath(
1054     const std::vector<String>& aPublicStrings,
1055     std::vector<zstring>& aInternalStrings)
1056 {
1057   for (std::vector<String>::const_iterator lIter = aPublicStrings.begin();
1058        lIter != aPublicStrings.end(); ++lIter)
1059   {
1060     if (lIter->length() != 0)
1061     {
1062       aInternalStrings.push_back(Unmarshaller::getInternalString(*lIter).c_str());
1063       zstring& lPath = aInternalStrings.back();
1064       if (lPath[lPath.length() - 1] != *filesystem_path::get_directory_separator())
1065       {
1066         lPath.append(filesystem_path::get_directory_separator());
1067       }
1068     }
1069   }
1070 }
1071 
1072 
1073 static void
toPublicPath(const std::vector<zstring> & aInternalStrings,std::vector<String> & aPublicStrings)1074 toPublicPath(
1075     const std::vector<zstring>& aInternalStrings,
1076     std::vector<String>& aPublicStrings)
1077 {
1078   for (std::vector<zstring>::const_iterator lIter = aInternalStrings.begin();
1079        lIter != aInternalStrings.end(); ++lIter)
1080   {
1081     aPublicStrings.push_back(lIter->c_str());
1082   }
1083 }
1084 
1085 
1086 void
setURIPath(const std::vector<String> & aURIPath)1087 StaticContextImpl::setURIPath(const std::vector<String> &aURIPath)
1088 {
1089   try
1090   {
1091     std::vector<zstring> lInternalURIPath;
1092     toInternalPath(aURIPath, lInternalURIPath);
1093     theCtx->set_uri_path(lInternalURIPath);
1094   }
1095   catch (ZorbaException const& e)
1096   {
1097     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1098   }
1099 }
1100 
1101 void
getURIPath(std::vector<String> & aURIPath) const1102 StaticContextImpl::getURIPath(std::vector<String> &aURIPath) const
1103 {
1104   try
1105   {
1106     std::vector<zstring> lInternalURIPath;
1107     theCtx->get_uri_path(lInternalURIPath);
1108     toPublicPath(lInternalURIPath, aURIPath);
1109   }
1110   catch (ZorbaException const& e)
1111   {
1112     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1113   }
1114 }
1115 
1116 void
getFullURIPath(std::vector<String> & aURIPath) const1117 StaticContextImpl::getFullURIPath(std::vector<String> &aURIPath) const
1118 {
1119   try
1120   {
1121     std::vector<zstring> lInternalURIPath;
1122     theCtx->get_full_uri_path(lInternalURIPath);
1123     toPublicPath(lInternalURIPath, aURIPath);
1124   }
1125   catch (ZorbaException const& e)
1126   {
1127     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1128   }
1129 }
1130 
1131 void
setLibPath(const std::vector<String> & aLibPath)1132 StaticContextImpl::setLibPath(const std::vector<String> &aLibPath)
1133 {
1134   try
1135   {
1136     std::vector<zstring> lInternalLibPath;
1137     toInternalPath(aLibPath, lInternalLibPath);
1138     theCtx->set_lib_path(lInternalLibPath);
1139   }
1140   catch (ZorbaException const& e)
1141   {
1142     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1143   }
1144 }
1145 
1146 void
getLibPath(std::vector<String> & aLibPath) const1147 StaticContextImpl::getLibPath(std::vector<String> &aLibPath) const
1148 {
1149   try
1150   {
1151     std::vector<zstring> lInternalLibPath;
1152     theCtx->get_lib_path(lInternalLibPath);
1153     toPublicPath(lInternalLibPath, aLibPath);
1154   }
1155   catch (ZorbaException const& e)
1156   {
1157     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1158   }
1159 }
1160 
1161 void
getFullLibPath(std::vector<String> & aLibPath) const1162 StaticContextImpl::getFullLibPath(std::vector<String> &aLibPath) const
1163 {
1164   try
1165   {
1166     std::vector<zstring> lInternalLibPath;
1167     theCtx->get_full_lib_path(lInternalLibPath);
1168     toPublicPath(lInternalLibPath, aLibPath);
1169   }
1170   catch (ZorbaException const& e)
1171   {
1172     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1173   }
1174 }
1175 
setModulePaths(const std::vector<String> & aModulePaths)1176 void StaticContextImpl::setModulePaths(const std::vector<String>& aModulePaths)
1177 {
1178   try
1179   {
1180     std::vector<zstring> lInternalModulePath;
1181     toInternalPath(aModulePaths, lInternalModulePath);
1182     theCtx->set_lib_path(lInternalModulePath);
1183     theCtx->set_uri_path(lInternalModulePath);
1184   }
1185   catch (ZorbaException const& e)
1186   {
1187     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1188   }
1189 }
1190 
getModulePaths(std::vector<String> & aModulePaths) const1191 void StaticContextImpl::getModulePaths(std::vector<String>& aModulePaths) const
1192 {
1193   try
1194   {
1195     std::vector<zstring> lInternalModulePath;
1196     theCtx->get_lib_path(lInternalModulePath);
1197     toPublicPath(lInternalModulePath, aModulePaths);
1198     lInternalModulePath.clear();
1199     theCtx->get_uri_path(lInternalModulePath);
1200     toPublicPath(lInternalModulePath, aModulePaths);
1201   }
1202   catch (ZorbaException const& e)
1203   {
1204     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1205   }
1206 }
1207 
1208 
1209 void
getFullModulePaths(std::vector<String> & aFullModulePaths) const1210 StaticContextImpl::getFullModulePaths( std::vector<String>& aFullModulePaths ) const
1211 {
1212   try
1213   {
1214     std::vector<zstring> lInternalModulePath;
1215     theCtx->get_full_lib_path(lInternalModulePath);
1216     toPublicPath(lInternalModulePath, aFullModulePaths);
1217     lInternalModulePath.clear();
1218     theCtx->get_full_uri_path(lInternalModulePath);
1219     toPublicPath(lInternalModulePath, aFullModulePaths);
1220   }
1221   catch (ZorbaException const& e)
1222   {
1223     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1224   }
1225 }
1226 
1227 
1228 String
resolve(const String & aRelativeUri) const1229 StaticContextImpl::resolve(const String& aRelativeUri) const
1230 {
1231   zstring lResolved;
1232   try
1233   {
1234     const zstring& lRelativeUri = Unmarshaller::getInternalString(aRelativeUri);
1235     lResolved = theCtx->resolve_relative_uri(lRelativeUri, true);
1236   }
1237   catch (ZorbaException const& e)
1238   {
1239     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1240     return "";
1241   }
1242   return lResolved.str();
1243 }
1244 
1245 
1246 String
resolve(const String & aRelativeUri,const String & aBaseUri) const1247 StaticContextImpl::resolve(const String& aRelativeUri, const String& aBaseUri) const
1248 {
1249   zstring lResolved;
1250   try
1251   {
1252     const zstring& lRelativeUri = Unmarshaller::getInternalString(aRelativeUri);
1253     const zstring& lBaseUri = Unmarshaller::getInternalString(aBaseUri);
1254     lResolved = theCtx->resolve_relative_uri(lRelativeUri, lBaseUri, true);
1255   }
1256   catch (ZorbaException const& e)
1257   {
1258     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1259     return "";
1260   }
1261   return lResolved.str();
1262 }
1263 
1264 
1265 bool
validate(const Item & rootElement,Item & validatedResult,validation_mode_t validationMode) const1266 StaticContextImpl::validate(
1267     const Item& rootElement,
1268     Item& validatedResult,
1269     validation_mode_t validationMode) const
1270 {
1271   try
1272   {
1273     StaticContextConsts::validation_mode_t valMode;
1274 
1275     switch( validationMode)
1276     {
1277       case validate_lax:
1278         valMode = StaticContextConsts::lax_validation;
1279         break;
1280       case validate_lax_dtd:
1281         valMode = StaticContextConsts::lax_dtd_validation;
1282         break;
1283       case validate_skip:
1284         valMode = StaticContextConsts::skip_validation;
1285         break;
1286       case validate_strict:
1287       default:
1288         valMode = StaticContextConsts::strict_validation;
1289         break;
1290     }
1291 
1292     store::Item_t lRes(Unmarshaller::getInternalItem(validatedResult));
1293     bool lResBool = theCtx->validate(Unmarshaller::getInternalItem(rootElement),
1294                             lRes,
1295                             valMode);
1296     validatedResult = lRes;
1297     return lResBool;
1298   }
1299   catch (ZorbaException const& e)
1300   {
1301     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1302     return false;
1303   }
1304 }
1305 
1306 
1307 bool
validate(const Item & rootElement,Item & validatedResult,const String & targetNamespace,validation_mode_t validationMode) const1308 StaticContextImpl::validate(
1309     const Item& rootElement,
1310     Item& validatedResult,
1311     const String& targetNamespace,
1312     validation_mode_t validationMode) const
1313 {
1314   try
1315   {
1316     StaticContextConsts::validation_mode_t valMode;
1317 
1318     switch( validationMode)
1319     {
1320       case validate_lax:
1321         valMode = StaticContextConsts::lax_validation;
1322         break;
1323       case validate_skip:
1324         valMode = StaticContextConsts::skip_validation;
1325         break;
1326       case validate_strict:
1327       default:
1328         valMode = StaticContextConsts::strict_validation;
1329         break;
1330     }
1331 
1332     store::Item_t lRes(Unmarshaller::getInternalItem(validatedResult));
1333     zstring lTns = Unmarshaller::getInternalString(targetNamespace);
1334     bool lResBool = theCtx->validate(
1335         Unmarshaller::getInternalItem(rootElement),
1336         lRes, lTns, valMode);
1337     validatedResult = lRes;
1338     return lResBool;
1339   }
1340   catch (ZorbaException const& e)
1341   {
1342     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1343     return false;
1344   }
1345 }
1346 
1347 
1348 bool
validateSimpleContent(const String & stringValue,const Item & typeQName,std::vector<Item> & resultList) const1349 StaticContextImpl::validateSimpleContent(
1350     const String& stringValue,
1351     const Item& typeQName,
1352     std::vector<Item>& resultList) const
1353 {
1354   try {
1355     bool res;
1356     std::vector<store::Item_t> tmpResList;
1357     zstring lTextValue = Unmarshaller::getInternalString(stringValue);
1358 
1359     res = theCtx->validateSimpleContent(lTextValue,
1360                                         Unmarshaller::getInternalItem(typeQName),
1361                                         tmpResList);
1362 
1363     if (!res)
1364       return false;
1365 
1366     for(std::vector<Item>::size_type i = 0; i < tmpResList.size(); ++i)
1367     {
1368       store::Item_t item = tmpResList[i];
1369       resultList.push_back(Item(item));
1370     }
1371 
1372     return true;
1373   }
1374   catch (ZorbaException const& e)
1375   {
1376     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1377     return false;
1378   }
1379 }
1380 
1381 
1382 /**
1383  * construct the query to call invoke
1384  * for the QName of the function and for each argument,
1385  * the query declares an external variable ($qname, $arg_1, ..., $arg_n)
1386  * which needs to be bound before execution.
1387  */
1388 String
createInvokeQuery(const Function_t & aFunc,size_t aArity) const1389 StaticContextImpl::createInvokeQuery(const Function_t& aFunc, size_t aArity) const
1390 {
1391   std::ostringstream lOut;
1392 
1393   // prolog
1394   lOut
1395     << "import module namespace ref = 'http://www.zorba-xquery.com/modules/reflection';"
1396     << std::endl
1397     << "declare variable $xxx-func-name as xs:QName" << " external;" << std::endl;
1398 
1399   for (size_t i = 0; i < aArity; ++i)
1400   {
1401     lOut << "declare variable $arg" << i << " external;" << std::endl;
1402   }
1403 
1404   // body
1405 
1406   // call updating, sequential, or simple invoke function
1407   lOut << "ref:invoke";
1408 
1409   if (aFunc->isUpdating())
1410     lOut << "-u";
1411   else if (aFunc->isSequential())
1412     lOut << "-s";
1413   else if (!aFunc->isDeterministic())
1414     lOut << "-n";
1415 
1416   // args
1417   lOut << "($xxx-func-name";
1418   for (size_t i = 0; i < aArity; ++i)
1419   {
1420     lOut << ", $arg" << i;
1421   }
1422   lOut << ")";
1423   return lOut.str();
1424 }
1425 
1426 
1427 Function_t
checkInvokable(const Item & aQName,size_t aNumArgs) const1428 StaticContextImpl::checkInvokable(const Item& aQName, size_t aNumArgs) const
1429 {
1430   Item lType = aQName.getType();
1431   if (lType.getStringValue() != "xs:QName")
1432   {
1433     throw XQUERY_EXCEPTION(
1434       err::XPTY0004, ERROR_PARAMS( ZED( BadType_23o ), "xs:QName" )
1435     );
1436   }
1437 
1438   // test if function with given #args exists
1439   Function_t lFunc;
1440   std::vector<Function_t> lFunctions;
1441   findFunctions(aQName, lFunctions);
1442   if (lFunctions.empty())
1443   {
1444     throw XQUERY_EXCEPTION(
1445       err::XPST0017,
1446       ERROR_PARAMS(
1447         aQName.getStringValue(), ZED( FunctionUndeclared_3 ), aNumArgs
1448       )
1449     );
1450   }
1451 
1452   for (std::vector<Function_t>::const_iterator lIter = lFunctions.begin();
1453        lIter != lFunctions.end(); ++lIter)
1454   {
1455     if ((*lIter)->isVariadic() || (*lIter)->getArity() == aNumArgs)
1456     {
1457       lFunc = (*lIter);
1458       break;
1459     }
1460   }
1461 
1462   if (!lFunc)
1463   {
1464     throw XQUERY_EXCEPTION(
1465       err::XPST0017,
1466       ERROR_PARAMS(
1467         aQName.getStringValue(), ZED( FunctionUndeclared_3 ), aNumArgs
1468       )
1469     );
1470   }
1471 
1472   return lFunc;
1473 }
1474 
1475 
1476 ItemSequence_t
invoke(const Item & aQName,const std::vector<ItemSequence_t> & aArgs) const1477 StaticContextImpl::invoke(
1478     const Item& aQName,
1479     const std::vector<ItemSequence_t>& aArgs) const
1480 {
1481   try
1482   {
1483     Function_t lFunc = checkInvokable(aQName, aArgs.size());
1484 
1485     String lStr = createInvokeQuery(lFunc, aArgs.size());
1486 
1487     std::auto_ptr<XQueryImpl> impl(new XQueryImpl());
1488 
1489     // compile without any hints
1490     Zorba_CompilerHints_t lHints;
1491     StaticContext_t lSctx = new StaticContextImpl(*this);
1492 
1493     impl->compile(lStr, lSctx, lHints);
1494 
1495     // bind qname and params
1496     DynamicContext* lDCtx = impl->getDynamicContext();
1497     lDCtx->setVariable("xxx-func-name", aQName);
1498     for (size_t i = 0; i < aArgs.size(); ++i)
1499     {
1500       std::ostringstream lArgName;
1501       lArgName << "arg" << i;
1502       lDCtx->setVariable(lArgName.str(), aArgs[i]->getIterator());
1503     }
1504 
1505     // the XQueryImpl object needs to live as long as its iterator
1506     // because the iterator returned as a result of the query
1507     // contains a reference to the query in order to do cleanup work.
1508     // The same is true for this sctx
1509     Iterator_t lIter = impl->iterator();
1510     return new InvokeItemSequence(impl.release(), lIter, const_cast<StaticContextImpl*>(this));
1511   }
1512   catch (ZorbaException const& e)
1513   {
1514     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1515     return 0;
1516   }
1517 }
1518 
1519 
1520 StaticCollectionManager*
getStaticCollectionManager() const1521 StaticContextImpl::getStaticCollectionManager() const
1522 {
1523   // assumption: Zorba is already initialized
1524   // otherwise there was no chance for the user to get this XQuery object
1525   Zorba* lZorba = Zorba::getInstance(0);
1526   ItemFactory* lFactory = lZorba->getItemFactory();
1527 
1528   if (!theCollectionMgr)
1529   {
1530     theCollectionMgr = new StaticCollectionManagerImpl(this,
1531                                                        lFactory,
1532                                                        theDiagnosticHandler);
1533   }
1534   return theCollectionMgr;
1535 }
1536 
1537 
1538 void
setAuditEvent(audit::Event * anEvent)1539 StaticContextImpl::setAuditEvent(audit::Event* anEvent)
1540 {
1541   theCtx->set_audit_event(anEvent);
1542 }
1543 
1544 
1545 audit::Event*
getAuditEvent() const1546 StaticContextImpl::getAuditEvent() const
1547 {
1548   return theCtx->get_audit_event();
1549 }
1550 
1551 
1552 void
getExternalVariables(Iterator_t & aVarsIter) const1553 StaticContextImpl::getExternalVariables(Iterator_t& aVarsIter) const
1554 {
1555   ZORBA_TRY
1556   std::vector<VarInfo*> vars;
1557   theCtx->getVariables(vars, true, false, true);
1558 
1559   std::vector<VarInfo*>::const_iterator ite = vars.begin();
1560   std::vector<VarInfo*>::const_iterator end = vars.end();
1561   std::vector<store::Item_t> extVars;
1562 
1563   for (; ite != end; ++ite)
1564   {
1565     zstring varName = (*ite)->getName()->getStringValue();
1566 
1567     if (varName == static_context::DOT_VAR_NAME ||
1568         varName == static_context::DOT_POS_VAR_NAME ||
1569         varName == static_context::DOT_SIZE_VAR_NAME)
1570       continue;
1571 
1572     extVars.push_back((*ite)->getName());
1573   }
1574 
1575   Iterator_t vIter = new VectorIterator(extVars, theDiagnosticHandler);
1576   aVarsIter = vIter;
1577   ZORBA_CATCH
1578 }
1579 
1580 
1581 Item
fetch(const String & aURI) const1582 StaticContextImpl::fetch(const String& aURI) const
1583 {
1584   return fetch(aURI, "SOME_CONTENT", "UTF-8");
1585 }
1586 
1587 
1588 Item
fetch(const String & aURI,const String & aEntityKind) const1589 StaticContextImpl::fetch(
1590     const String& aURI,
1591     const String& aEntityKind) const
1592 {
1593   return fetch(aURI, aEntityKind, "UTF-8");
1594 }
1595 
1596 Item
fetch(const String & aURI,const String & aEntityKind,const String & aEncoding) const1597 StaticContextImpl::fetch(
1598     const String& aURI,
1599     const String& aEntityKind,
1600     const String& aEncoding) const
1601 {
1602   ZORBA_TRY
1603   {
1604     Zorba* lZorba = Zorba::getInstance(0);
1605     ItemFactory* lFactory = lZorba->getItemFactory();
1606 
1607     Item lQName = lFactory->createQName(static_context::ZORBA_FETCH_FN_NS,
1608                                           "content");
1609 
1610     // create a streamable string item
1611     std::vector<ItemSequence_t> lArgs;
1612     lArgs.push_back(new SingletonItemSequence(lFactory->createString(aURI)));
1613     lArgs.push_back(
1614         new SingletonItemSequence(lFactory->createString(aEntityKind)));
1615     lArgs.push_back(
1616         new SingletonItemSequence(lFactory->createString(aEncoding)));
1617 
1618     StaticContext_t lCtx = createChildContext();
1619 
1620     Zorba_CompilerHints_t lHints;
1621     std::ostringstream lProlog;
1622     lProlog
1623       << "import module namespace d = '" << static_context::ZORBA_FETCH_FN_NS  << "';";
1624 
1625     lCtx->loadProlog(lProlog.str(), lHints);
1626 
1627     ItemSequence_t lSeq = lCtx->invoke(lQName, lArgs);
1628     Iterator_t lIter = lSeq->getIterator();
1629     lIter->open();
1630     Item lRes;
1631     lIter->next(lRes);
1632     return lRes;
1633   }
1634   ZORBA_CATCH
1635   return 0;
1636 }
1637 
1638 Item
fetchBinary(const String & aURI) const1639 StaticContextImpl::fetchBinary(const String& aURI) const
1640 {
1641   return fetchBinary(aURI, "SOME_CONTENT");
1642 }
1643 
1644 Item
fetchBinary(const String & aURI,const String & aEntityKind) const1645 StaticContextImpl::fetchBinary(
1646     const String& aURI,
1647     const String& aEntityKind) const
1648 {
1649   ZORBA_TRY
1650   {
1651     Zorba* lZorba = Zorba::getInstance(0);
1652     ItemFactory* lFactory = lZorba->getItemFactory();
1653 
1654     Item lQName = lFactory->createQName(static_context::ZORBA_FETCH_FN_NS,
1655                                           "content-binary");
1656 
1657     // create a streamable string item
1658     std::vector<ItemSequence_t> lArgs;
1659     lArgs.push_back(new SingletonItemSequence(lFactory->createString(aURI)));
1660     lArgs.push_back(
1661         new SingletonItemSequence(lFactory->createString(aEntityKind)));
1662 
1663     StaticContext_t lCtx = createChildContext();
1664 
1665     Zorba_CompilerHints_t lHints;
1666     std::ostringstream lProlog;
1667     lProlog
1668       << "import module namespace d = '" << static_context::ZORBA_FETCH_FN_NS  << "';";
1669 
1670     lCtx->loadProlog(lProlog.str(), lHints);
1671 
1672     ItemSequence_t lSeq = lCtx->invoke(lQName, lArgs);
1673     Iterator_t lIter = lSeq->getIterator();
1674     lIter->open();
1675     Item lRes;
1676     lIter->next(lRes);
1677     return lRes;
1678   }
1679   ZORBA_CATCH
1680   return 0;
1681 }
1682 
1683 void
clearBaseURI()1684 StaticContextImpl::clearBaseURI()
1685 {
1686   try
1687   {
1688     theCtx->clear_base_uri();
1689   }
1690   catch (ZorbaException const& e)
1691   {
1692     ZorbaImpl::notifyError(theDiagnosticHandler, e);
1693   }
1694   catch (std::exception const& e)
1695   {
1696     ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
1697   }
1698 }
1699 
1700 } /* namespace zorba */
1701 /* vim:set et sw=2 ts=2: */
1702