Qt 4.8
Public Functions | Static Private Functions | Properties | List of all members
QPatternist::EvaluationCache< IsForGlobal > Class Template Reference

Evaluates to the same result as its operand, but ensures the operand is evaluated once even if this Expression is evaluated several times. More...

#include <qevaluationcache_p.h>

Inheritance diagram for QPatternist::EvaluationCache< IsForGlobal >:
QPatternist::SingleContainer QPatternist::Expression QSharedData QPatternist::CppCastingHelper< Expression > QPatternist::SourceLocationReflection

Public Functions

virtual ExpressionVisitorResult::Ptr accept (const ExpressionVisitor::Ptr &visitor) const
 
virtual const SourceLocationReflectionactualReflection () const
 Returns this. More...
 
virtual Expression::Ptr compress (const StaticContext::Ptr &context)
 
virtual Item::Iterator::Ptr evaluateSequence (const DynamicContext::Ptr &context) const
 
virtual Item evaluateSingleton (const DynamicContext::Ptr &context) const
 
 EvaluationCache (const Expression::Ptr &operand, const VariableDeclaration *varDecl, const VariableSlotID slot)
 
virtual SequenceType::List expectedOperandTypes () const
 
virtual Properties properties () const
 
VariableSlotID slot () const
 
virtual SequenceType::Ptr staticType () const
 
virtual Expression::Ptr typeCheck (const StaticContext::Ptr &context, const SequenceType::Ptr &reqType)
 
- Public Functions inherited from QPatternist::SingleContainer
virtual bool compressOperands (const StaticContext::Ptr &)
 
virtual Expression::List operands () const
 
virtual void setOperands (const Expression::List &operands)
 
- Public Functions inherited from QPatternist::Expression
virtual void announceFocusType (const ItemType::Ptr &itemType)
 
Properties deepProperties () const
 Computes the union of properties for this Expression and all its descending children. More...
 
virtual Properties dependencies () const
 
virtual QString description () const
 
virtual bool evaluateEBV (const DynamicContext::Ptr &context) const
 
virtual void evaluateToSequenceReceiver (const DynamicContext::Ptr &context) const
 
virtual ItemType::Ptr expectedContextItemType () const
 
 Expression ()
 
bool has (const Property prop) const
 
bool hasDependency (const Property prop) const
 
virtual ID id () const
 
bool is (const ID id) const
 
bool isEvaluated () const
 
virtual ItemType::Ptr newFocusType () const
 
virtual QList< QExplicitlySharedDataPointer< OptimizationPass > > optimizationPasses () const
 
virtual PatternPriority patternPriority () const
 
const Expression::Ptrrewrite (const Expression::Ptr &to, const StaticContext::Ptr &context) const
 Rewrites this Expression to to, and return to. More...
 
virtual ~Expression ()
 
- Public Functions inherited from QSharedData
 QSharedData ()
 Constructs a QSharedData object with a reference count of 0. More...
 
 QSharedData (const QSharedData &)
 Constructs a QSharedData object with reference count 0. More...
 
- Public Functions inherited from QPatternist::CppCastingHelper< Expression >
const TCastTarget * as () const
 
TCastTarget * as ()
 
- Public Functions inherited from QPatternist::SourceLocationReflection
virtual QSourceLocation sourceLocation () const
 
 SourceLocationReflection ()
 
virtual ~SourceLocationReflection ()
 

Static Private Functions

static DynamicContext::Ptr topFocusContext (const DynamicContext::Ptr &context)
 

Properties

const VariableDeclarationm_declaration
 
bool m_declarationUsedByMany
 
const VariableSlotID m_varSlot
 

Additional Inherited Members

- Public Types inherited from QPatternist::Expression
typedef QExplicitlySharedDataPointer< const ExpressionConstPtr
 A smart pointer wrapping const Expression instances. More...
 
enum  ID {
  IDBooleanValue = 1, IDCountFN, IDEmptyFN, IDExistsFN,
  IDExpressionSequence, IDGeneralComparison, IDIfThenClause, IDIgnorableExpression,
  IDIntegerValue, IDPositionFN, IDStringValue, IDValueComparison,
  IDRangeVariableReference, IDContextItem, IDUserFunctionCallsite, IDExpressionVariableReference,
  IDAttributeConstructor, IDUpperCaseFN, IDLowerCaseFN, IDFirstItemPredicate,
  IDEmptySequence, IDReturnOrderBy, IDLetClause, IDForClause,
  IDPath, IDNamespaceConstructor, IDArgumentReference, IDGenericPredicate,
  IDAxisStep, IDFloat, IDCombineNodes, IDUnresolvedVariableReference,
  IDCardinalityVerifier
}
 
typedef QList< Expression::PtrList
 
typedef QFlags< PropertyProperties
 
enum  Property {
  UseContextItem = 1, DisableElimination = 1 << 1, IsEvaluated = 1 << 2, DisableTypingDeduction = 1 << 3,
  EmptynessFollowsChild = 1 << 4, RewriteToEmptyOnEmpty = 1 << 5, RequiresFocus = 1 << 6, AffectsOrderOnly = 1 << 7,
  RequiresContextItem = (1 << 8) | RequiresFocus, CreatesFocusForLast = 1 << 9, LastOperandIsCollation = 1 << 10, DependsOnLocalVariable = (1 << 11) | DisableElimination,
  EvaluationCacheRedundant = (1 << 12), IsNodeConstructor = 1 << 13, RequiresCurrentItem = 1 << 14
}
 
typedef QExplicitlySharedDataPointer< ExpressionPtr
 A smart pointer wrapping mutable Expression instances. More...
 
typedef ::QAbstractXmlForwardIterator< Expression::PtrQAbstractXmlForwardIterator
 
typedef QVector< Expression::PtrVector
 
- Static Public Functions inherited from QPatternist::Expression
static void rewrite (Expression::Ptr &old, const Expression::Ptr &New, const StaticContext::Ptr &context)
 
- Public Variables inherited from QSharedData
QAtomicInt ref
 
- Protected Functions inherited from QPatternist::SingleContainer
 SingleContainer (const Expression::Ptr &operand)
 
- Protected Functions inherited from QPatternist::Expression
void typeCheckOperands (const StaticContext::Ptr &context)
 
- Protected Functions inherited from QPatternist::CppCastingHelper< Expression >
 CppCastingHelper ()
 
- Protected Variables inherited from QPatternist::SingleContainer
Expression::Ptr m_operand
 

Detailed Description

template<bool IsForGlobal>
class QPatternist::EvaluationCache< IsForGlobal >

Evaluates to the same result as its operand, but ensures the operand is evaluated once even if this Expression is evaluated several times.

EvaluationCache does this in a pipelined way, by delivering items from its cache, which is stored in the DynamicContext. If the cache has less items than what the caller requests, EvaluationCache continues to deliver but this time from the source, which it also populates into the cache.

EvaluationCache is used as an optimization in order to avoid running expensive code paths multiple times, but also is sometimes a necessity: for instance, when objects must be unique, such as potentially in the case of node identity.

EvaluationCache is in particular used for variables, whose sole purpose is to store it once(at least conceptually) and then use it in multiple places.

In some cases an EvaluationCache isn't necessary. For instance, when a variable is only referenced once. In those cases EvaluationCache removes itself as an optimization; implemented in compress().

Author
Frans Englich frans.nosp@m..eng.nosp@m.lich@.nosp@m.noki.nosp@m.a.com

Definition at line 96 of file qevaluationcache_p.h.

Constructors and Destructors

◆ EvaluationCache()

template<bool IsForGlobal>
QPatternist::EvaluationCache< IsForGlobal >::EvaluationCache ( const Expression::Ptr operand,
const VariableDeclaration varDecl,
const VariableSlotID  slot 
)

Definition at line 49 of file qevaluationcache.cpp.

51  : SingleContainer(op)
52  , m_declarationUsedByMany(varDecl->usedByMany())
53  , m_varSlot(aSlot)
54 {
55  Q_ASSERT(m_varSlot > -1);
56 }
const VariableSlotID m_varSlot
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
SingleContainer(const Expression::Ptr &operand)

Functions

◆ accept()

template<bool IsForGlobal>
ExpressionVisitorResult::Ptr QPatternist::EvaluationCache< IsForGlobal >::accept ( const ExpressionVisitor::Ptr visitor) const
virtual

Implements QPatternist::Expression.

Definition at line 263 of file qevaluationcache.cpp.

264 {
265  return visitor->visit(this);
266 }

◆ actualReflection()

template<bool IsForGlobal>
const SourceLocationReflection * QPatternist::EvaluationCache< IsForGlobal >::actualReflection ( ) const
virtual

Returns this.

Reimplemented from QPatternist::Expression.

Definition at line 269 of file qevaluationcache.cpp.

270 {
271  return m_operand->actualReflection();
272 }

◆ compress()

template<bool IsForGlobal>
Expression::Ptr QPatternist::EvaluationCache< IsForGlobal >::compress ( const StaticContext::Ptr context)
virtual

compress() is the last stage performs in compiling an expression, done after the initial AST build and calling typeCheck(). compress() performs crucial simplifications, either by having drastic performance implications or that some expressions depend on it for proper behavior.

The default implementation performs a sparse conditional constant propagation. In short, a recursive process is performed in the AST which examines if the Expression's operands are constant values, and if so, performs a const fold(AST rewrite) into the result of evaluating the expression in question. This default behavior can be disabled by letting properties() return DisableElimination.

This compress() stage can be relative effective due to the design of XPath, in part because intrinsic functions are heavily used. Many Expressions override compress() and do optimizations specific to what they do. Also, many Expressions performs optimizations in their typeCheck().

Parameters
contextthe static context. Supplies compile time information, and is the channel for communicating error messages.
See also
Wikipedia, the free encyclopedia, Sparse conditional constant propagation
Wikipedia, the free encyclopedia, Intrinsic function
Wikipedia, the free encyclopedia, Compiler optimization

Reimplemented from QPatternist::Expression.

Definition at line 191 of file qevaluationcache.cpp.

192 {
193  const Expression::Ptr me(SingleContainer::compress(context));
194 
195  if(me != this)
196  return me;
197 
199  return m_operand;
200 
202  {
203  /* If it's only an atomic value an EvaluationCache is overkill. However,
204  * it's still needed for functions like fn:current-time() that must adhere to
205  * query stability. */
206  const Properties props(m_operand->properties());
207 
208  if(props.testFlag(EvaluationCacheRedundant) ||
209  ((props.testFlag(IsEvaluated)) &&
210  !props.testFlag(DisableElimination) &&
211  CommonSequenceTypes::ExactlyOneAtomicType->matches(m_operand->staticType())))
212  {
213  return m_operand;
214  }
215  else
216  return me;
217  }
218  else
219  {
220  /* If we're only used once, there's no need for an EvaluationCache. */
221  return m_operand;
222  }
223 }
static const SequenceType::Ptr ExactlyOneAtomicType
virtual Expression::Ptr compress(const StaticContext::Ptr &context)
QExplicitlySharedDataPointer< Expression > Ptr
A smart pointer wrapping mutable Expression instances.
QFlags< Property > Properties

◆ evaluateSequence()

template<bool IsForGlobal>
Item::Iterator::Ptr QPatternist::EvaluationCache< IsForGlobal >::evaluateSequence ( const DynamicContext::Ptr context) const
virtual

Evaluate this Expression by iterating over it. This is a central function for evaluating expressions.

Expressions must always always return a valid QAbstractXmlForwardIterator and may never return 0. If an empty result is of interest to be returned, the EmptyIterator should be returned.

The default implementation returns a SingletonIterator over the item returned from evaluateSingleton().

Note
This function may raise an exception when calling, not only when QAbstractXmlForwardIterator::next() is called on the return value. This is because in some cases evaluateSingleton() is called directly.

We don't use makeListIterator() here because the MIPSPro compiler can't handle it.

We don't use makeListIterator() here because the MIPSPro compiler can't handle it.

Reimplemented from QPatternist::Expression.

Definition at line 108 of file qevaluationcache.cpp.

109 {
110  ItemSequenceCacheCell::Vector &cells = IsForGlobal ? context->globalItemSequenceCacheCells(m_varSlot) : context->itemSequenceCacheCells(m_varSlot);
111  ItemSequenceCacheCell &cell = cells[m_varSlot];
112 
113 
114  if(cell.inUse)
115  {
116  context->error(QtXmlPatterns::tr("Circularity detected"),
118  }
119 
120  switch(cell.cacheState)
121  {
123  {
127  return Item::Iterator::Ptr(new ListIterator<Item, Item::List>(cell.cachedItems));
128  }
130  {
131  cell.inUse = true;
132  cell.sourceIterator = m_operand->evaluateSequence(IsForGlobal ? topFocusContext(context) : context);
134  /* Fallthrough. */
135  }
137  {
138  cell.inUse = false;
139  Q_ASSERT_X(cells.at(m_varSlot).sourceIterator, Q_FUNC_INFO,
140  "This trigger for a cache bug which hasn't yet been analyzed.");
141  return Item::Iterator::Ptr(new CachingIterator(cells, m_varSlot, IsForGlobal ? topFocusContext(context) : context));
142  }
143  default:
144  {
145  Q_ASSERT_X(false, Q_FUNC_INFO, "This path is not supposed to be run.");
146  return Item::Iterator::Ptr();
147  }
148  }
149 }
const VariableSlotID m_varSlot
static DynamicContext::Ptr topFocusContext(const DynamicContext::Ptr &context)
QExplicitlySharedDataPointer< QAbstractXmlForwardIterator< Item > > Ptr
A smart pointer wrapping an instance of a QAbstractXmlForwardIterator subclass.
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
QVector< ItemSequenceCacheCell > Vector
#define Q_FUNC_INFO
Definition: qglobal.h:1871

◆ evaluateSingleton()

template<bool IsForGlobal>
Item QPatternist::EvaluationCache< IsForGlobal >::evaluateSingleton ( const DynamicContext::Ptr context) const
virtual

Reimplemented from QPatternist::Expression.

Definition at line 76 of file qevaluationcache.cpp.

77 {
78  ItemCacheCell &cell = IsForGlobal ? context->globalItemCacheCell(m_varSlot) : context->itemCacheCell(m_varSlot);
79 
80  if(cell.cacheState == ItemCacheCell::Full)
81  return cell.cachedItem;
82  else
83  {
84  Q_ASSERT(cell.cacheState == ItemCacheCell::Empty);
85  cell.cachedItem = m_operand->evaluateSingleton(IsForGlobal ? topFocusContext(context) : context);
86  cell.cacheState = ItemCacheCell::Full;
87  return cell.cachedItem;
88  }
89 }
const VariableSlotID m_varSlot
static DynamicContext::Ptr topFocusContext(const DynamicContext::Ptr &context)
#define Q_ASSERT(cond)
Definition: qglobal.h:1823

◆ expectedOperandTypes()

template<bool IsForGlobal>
SequenceType::List QPatternist::EvaluationCache< IsForGlobal >::expectedOperandTypes ( ) const
virtual

The first operand must be exactly one xs:string.

Implements QPatternist::Expression.

Definition at line 232 of file qevaluationcache.cpp.

233 {
234  /* Remember that EvaluationCache::typeCheck() will be called from multiple locations,
235  * which potentially have different type requirements. For instance, one wants a node,
236  * and another requires atomization and casting.
237  *
238  * Returning ZeroOrMoreItems is safe here because staticType() returns the operand's type
239  * and therefore the convertors like Atomizer will be parents to us, and hence only affect
240  * the relevant path.
241  *
242  * ZeroOrMoreItems also make sense logically since we're actually only used where the
243  * variable references reference us. */
244  SequenceType::List result;
246 
247  return result;
248 }
static const SequenceType::Ptr ZeroOrMoreItems
QList< SequenceType::Ptr > List

◆ properties()

template<bool IsForGlobal>
Expression::Properties QPatternist::EvaluationCache< IsForGlobal >::properties ( ) const
virtual
Returns
a bitwise OR'd value of properties, describing the characteristics of the expression. These properties affects how this Expression is treated in for example type checking stages.

The default implementation returns 0. Override and let the function return a different value, if that's of interest.

An important decision when re-implementing properties() is whether to OR in the properties() of ones operands. For instance, if an operand has RequiresFocus set, that flag nost likely applies to the apparent as well, since it depends on its operand.

See also
deepProperties()
Returns
Expression::None, meaning no special properties

Reimplemented from QPatternist::Expression.

Definition at line 251 of file qevaluationcache.cpp.

252 {
253  /* We cannot return the operand's properties unconditionally, because some
254  * doesn't hold for this Expression.
255  *
256  * However, some of the properties must propagate through, which are the ones being OR'd here.
257  */
258  return m_operand->properties() & (DisableElimination | IsEvaluated | DisableTypingDeduction);
259 }

◆ slot()

template<bool IsForGlobal>
VariableSlotID QPatternist::EvaluationCache< IsForGlobal >::slot ( ) const
inline

Definition at line 120 of file qevaluationcache_p.h.

121  {
122  return m_varSlot;
123  }
const VariableSlotID m_varSlot

◆ staticType()

template<bool IsForGlobal>
SequenceType::Ptr QPatternist::EvaluationCache< IsForGlobal >::staticType ( ) const
virtual
Returns
the static type of this Expression. For example, an 'and' expression have as static type xs:boolean

Implements QPatternist::Expression.

Definition at line 226 of file qevaluationcache.cpp.

227 {
228  return m_operand->staticType();
229 }

◆ topFocusContext()

template<bool IsForGlobal>
DynamicContext::Ptr QPatternist::EvaluationCache< IsForGlobal >::topFocusContext ( const DynamicContext::Ptr context)
staticprivate

Definition at line 59 of file qevaluationcache.cpp.

Referenced by QPatternist::EvaluationCache< IsForGlobal >::evaluateSequence(), QPatternist::EvaluationCache< IsForGlobal >::evaluateSingleton(), and QPatternist::EvaluationCache< IsForGlobal >::slot().

60 {
61  DynamicContext::Ptr result(context);
62 
63  while(true)
64  {
65  DynamicContext::Ptr candidate(result->previousContext());
66 
67  /* We want the top focus, not GenericDynamicContext. */
68  if(candidate && candidate->focusIterator())
69  result = candidate;
70  else
71  return result;
72  }
73 }
QExplicitlySharedDataPointer< DynamicContext > Ptr

◆ typeCheck()

template<bool IsForGlobal>
Expression::Ptr QPatternist::EvaluationCache< IsForGlobal >::typeCheck ( const StaticContext::Ptr context,
const SequenceType::Ptr reqType 
)
virtual

This implementation guarantees to never rewrite away this Expression, but at most rewrite it as a child of another expression(that presumably have a type checking role). It is therefore always safe to override this function and call this implementation and not worry about that this Expression becomes deleted.

Many Expressions override typeCheck() and performs optimizations, as opposed to doing it in the compress() stage. This is due to that the design of those Expressions often are tied to that certain simplifications are done at the typeCheck() stage of the compilation process or that it in some other way is related to what the typeCheck() do. Also, the earlier the AST can be simplified, the better the chances are for subsequent optimizations.

It is important that the super class's typeCheck() is called before doing any custom type checking, since the call can change the children(notably, the childrens' static types). For example, if the Expression, MyExpression in the example, does not match the required type, typeCheck returns the Expression wrapped in for example ItemVerifier, CardinalityVerifier, or both.

typeCheck() may be called many times. typeCheck() must either raise an error if this Expression is an invalid expression. Thus, it is guaranteed that an Expression is valid after typeCheck() is called.

Parameters
contextsupplies information, such as namespace bindings and available function signatures, that can be needed at compilation time. context is guaranteed by the caller to never null.
reqTypethe static type that this Expression must match when evaluated. reqType is guaranteed by the caller to never null.
Returns
an Expression that can be this Expression, or another expression, which somehow is necessary for making this Expression conforming to reqType

Reimplemented from QPatternist::Expression.

Definition at line 152 of file qevaluationcache.cpp.

154 {
155  /* It's important that we do the typeCheck() before checking for the use of local variables,
156  * because ExpressionVariableReference can reference an expression that is a local variable,
157  * so it must rewrite itself to it operand before, and it does that in EvaluationCache::typeCheck(). */
158  const Expression::Ptr me(SingleContainer::typeCheck(context, reqType));
159 
160  OperandsIterator it(me, OperandsIterator::ExcludeParent);
161  Expression::Ptr next(it.next());
162 
163  /* If our operand or any sub operand gets its value from a for-loop, we cannot
164  * cache it since then our cache would be filled -- but not invalidated -- on the
165  * first for-iteration. Consider this query:
166  *
167  * <tt>for $i in expr
168  * let $v := $i/p
169  * return ($v, $v)</tt>
170  *
171  * An evaluation cache is inserted for the two operands in the return clause. However,
172  * $i changes for each iteration so the cache can only be active on a per-iteration basis,
173  * it it's possible(which it isn't).
174  *
175  * This means that for some queries we don't cache what we really should, and hence evaluate
176  * in a sub-optimal way, since this DependsOnLocalVariable don't communicate whether it references
177  * a loop that affects us. The correct fix for this would be to let ForExpression reset the
178  * relevant caches only, but we don't know which ones that are. */
179  while(next)
180  {
181  if(next->has(DependsOnLocalVariable))
182  return m_operand->typeCheck(context, reqType);
183 
184  next = it.next();
185  }
186 
187  return me;
188 }
#define it(className, varName)
virtual Expression::Ptr typeCheck(const StaticContext::Ptr &context, const SequenceType::Ptr &reqType)
Definition: qexpression.cpp:70
QExplicitlySharedDataPointer< Expression > Ptr
A smart pointer wrapping mutable Expression instances.

Properties

◆ m_declaration

template<bool IsForGlobal>
const VariableDeclaration* QPatternist::EvaluationCache< IsForGlobal >::m_declaration
private

Definition at line 127 of file qevaluationcache_p.h.

◆ m_declarationUsedByMany

template<bool IsForGlobal>
bool QPatternist::EvaluationCache< IsForGlobal >::m_declarationUsedByMany
private

◆ m_varSlot

template<bool IsForGlobal>
const VariableSlotID QPatternist::EvaluationCache< IsForGlobal >::m_varSlot
private

This variable must not be called m_slot. If it so, a compiler bug on HP-UX-aCC-64 is triggered in the constructor initializor. See the preprocessor output.

Note that this is the cache slot, and is disjoint to any variable's regular slot.

Definition at line 137 of file qevaluationcache_p.h.

Referenced by QPatternist::EvaluationCache< IsForGlobal >::evaluateSequence(), QPatternist::EvaluationCache< IsForGlobal >::evaluateSingleton(), QPatternist::EvaluationCache< IsForGlobal >::EvaluationCache(), and QPatternist::EvaluationCache< IsForGlobal >::slot().


The documentation for this class was generated from the following files: