1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 
6 #include <utility>
7 
8 #include "mozilla/HashFunctions.h"
9 #include "nsGkAtoms.h"
10 #include "nsReadableUtils.h"
11 #include "txExecutionState.h"
12 #include "txKey.h"
13 #include "txNamespaceMap.h"
14 #include "txSingleNodeContext.h"
15 #include "txXSLTFunctions.h"
16 #include "txXSLTPatterns.h"
17 
18 using namespace mozilla;
19 
20 /*
21  * txKeyFunctionCall
22  * A representation of the XSLT additional function: key()
23  */
24 
25 /*
26  * Creates a new key function call
27  */
txKeyFunctionCall(txNamespaceMap * aMappings)28 txKeyFunctionCall::txKeyFunctionCall(txNamespaceMap* aMappings)
29     : mMappings(aMappings) {}
30 
31 /*
32  * Evaluates a key() xslt-function call. First argument is name of key
33  * to use, second argument is value to look up.
34  * @param aContext the context node for evaluation of this Expr
35  * @param aCs      the ContextState containing the stack information needed
36  *                 for evaluation
37  * @return the result of the evaluation
38  */
evaluate(txIEvalContext * aContext,txAExprResult ** aResult)39 nsresult txKeyFunctionCall::evaluate(txIEvalContext* aContext,
40                                      txAExprResult** aResult) {
41   if (!aContext || !requireParams(2, 2, aContext))
42     return NS_ERROR_XPATH_BAD_ARGUMENT_COUNT;
43 
44   txExecutionState* es =
45       static_cast<txExecutionState*>(aContext->getPrivateContext());
46 
47   nsAutoString keyQName;
48   nsresult rv = mParams[0]->evaluateToString(aContext, keyQName);
49   NS_ENSURE_SUCCESS(rv, rv);
50 
51   txExpandedName keyName;
52   rv = keyName.init(keyQName, mMappings, false);
53   NS_ENSURE_SUCCESS(rv, rv);
54 
55   RefPtr<txAExprResult> exprResult;
56   rv = mParams[1]->evaluate(aContext, getter_AddRefs(exprResult));
57   NS_ENSURE_SUCCESS(rv, rv);
58 
59   txXPathTreeWalker walker(aContext->getContextNode());
60   walker.moveToRoot();
61 
62   RefPtr<txNodeSet> res;
63   txNodeSet* nodeSet;
64   if (exprResult->getResultType() == txAExprResult::NODESET &&
65       (nodeSet =
66            static_cast<txNodeSet*>(static_cast<txAExprResult*>(exprResult)))
67               ->size() > 1) {
68     rv = aContext->recycler()->getNodeSet(getter_AddRefs(res));
69     NS_ENSURE_SUCCESS(rv, rv);
70 
71     int32_t i;
72     for (i = 0; i < nodeSet->size(); ++i) {
73       nsAutoString val;
74       txXPathNodeUtils::appendNodeValue(nodeSet->get(i), val);
75 
76       RefPtr<txNodeSet> nodes;
77       rv = es->getKeyNodes(keyName, walker.getCurrentPosition(), val, i == 0,
78                            getter_AddRefs(nodes));
79       NS_ENSURE_SUCCESS(rv, rv);
80 
81       res->add(*nodes);
82     }
83   } else {
84     nsAutoString val;
85     exprResult->stringValue(val);
86     rv = es->getKeyNodes(keyName, walker.getCurrentPosition(), val, true,
87                          getter_AddRefs(res));
88     NS_ENSURE_SUCCESS(rv, rv);
89   }
90 
91   *aResult = res;
92   NS_ADDREF(*aResult);
93 
94   return NS_OK;
95 }
96 
getReturnType()97 Expr::ResultType txKeyFunctionCall::getReturnType() { return NODESET_RESULT; }
98 
isSensitiveTo(ContextSensitivity aContext)99 bool txKeyFunctionCall::isSensitiveTo(ContextSensitivity aContext) {
100   return (aContext & NODE_CONTEXT) || argsSensitiveTo(aContext);
101 }
102 
103 #ifdef TX_TO_STRING
appendName(nsAString & aDest)104 void txKeyFunctionCall::appendName(nsAString& aDest) {
105   aDest.Append(nsGkAtoms::key->GetUTF16String());
106 }
107 #endif
108 
109 /**
110  * Hash functions
111  */
112 
KeyEquals(KeyTypePointer aKey) const113 bool txKeyValueHashEntry::KeyEquals(KeyTypePointer aKey) const {
114   return mKey.mKeyName == aKey->mKeyName &&
115          mKey.mRootIdentifier == aKey->mRootIdentifier &&
116          mKey.mKeyValue.Equals(aKey->mKeyValue);
117 }
118 
HashKey(KeyTypePointer aKey)119 PLDHashNumber txKeyValueHashEntry::HashKey(KeyTypePointer aKey) {
120   const txKeyValueHashKey* key = static_cast<const txKeyValueHashKey*>(aKey);
121 
122   return AddToHash(HashString(key->mKeyValue), key->mKeyName.mNamespaceID,
123                    key->mRootIdentifier, key->mKeyName.mLocalName.get());
124 }
125 
KeyEquals(KeyTypePointer aKey) const126 bool txIndexedKeyHashEntry::KeyEquals(KeyTypePointer aKey) const {
127   return mKey.mKeyName == aKey->mKeyName &&
128          mKey.mRootIdentifier == aKey->mRootIdentifier;
129 }
130 
HashKey(KeyTypePointer aKey)131 PLDHashNumber txIndexedKeyHashEntry::HashKey(KeyTypePointer aKey) {
132   const txIndexedKeyHashKey* key =
133       static_cast<const txIndexedKeyHashKey*>(aKey);
134   return HashGeneric(key->mKeyName.mNamespaceID, key->mRootIdentifier,
135                      key->mKeyName.mLocalName.get());
136 }
137 
138 /*
139  * Class managing XSLT-keys
140  */
141 
getKeyNodes(const txExpandedName & aKeyName,const txXPathNode & aRoot,const nsAString & aKeyValue,bool aIndexIfNotFound,txExecutionState & aEs,txNodeSet ** aResult)142 nsresult txKeyHash::getKeyNodes(const txExpandedName& aKeyName,
143                                 const txXPathNode& aRoot,
144                                 const nsAString& aKeyValue,
145                                 bool aIndexIfNotFound, txExecutionState& aEs,
146                                 txNodeSet** aResult) {
147   *aResult = nullptr;
148 
149   int32_t identifier = txXPathNodeUtils::getUniqueIdentifier(aRoot);
150 
151   txKeyValueHashKey valueKey(aKeyName, identifier, aKeyValue);
152   txKeyValueHashEntry* valueEntry = mKeyValues.GetEntry(valueKey);
153   if (valueEntry) {
154     *aResult = valueEntry->mNodeSet;
155     NS_ADDREF(*aResult);
156 
157     return NS_OK;
158   }
159 
160   // We didn't find a value. This could either mean that that key has no
161   // nodes with that value or that the key hasn't been indexed using this
162   // document.
163 
164   if (!aIndexIfNotFound) {
165     // If aIndexIfNotFound is set then the caller knows this key is
166     // indexed, so don't bother investigating.
167     *aResult = mEmptyNodeSet;
168     NS_ADDREF(*aResult);
169 
170     return NS_OK;
171   }
172 
173   txIndexedKeyHashKey indexKey(aKeyName, identifier);
174   txIndexedKeyHashEntry* indexEntry = mIndexedKeys.PutEntry(indexKey);
175   NS_ENSURE_TRUE(indexEntry, NS_ERROR_OUT_OF_MEMORY);
176 
177   if (indexEntry->mIndexed) {
178     // The key was indexed and apparently didn't contain this value so
179     // return the empty nodeset.
180     *aResult = mEmptyNodeSet;
181     NS_ADDREF(*aResult);
182 
183     return NS_OK;
184   }
185 
186   // The key needs to be indexed.
187   txXSLKey* xslKey = mKeys.get(aKeyName);
188   if (!xslKey) {
189     // The key didn't exist, so bail.
190     return NS_ERROR_INVALID_ARG;
191   }
192 
193   nsresult rv = xslKey->indexSubtreeRoot(aRoot, mKeyValues, aEs);
194   NS_ENSURE_SUCCESS(rv, rv);
195 
196   indexEntry->mIndexed = true;
197 
198   // Now that the key is indexed we can get its value.
199   valueEntry = mKeyValues.GetEntry(valueKey);
200   if (valueEntry) {
201     *aResult = valueEntry->mNodeSet;
202     NS_ADDREF(*aResult);
203   } else {
204     *aResult = mEmptyNodeSet;
205     NS_ADDREF(*aResult);
206   }
207 
208   return NS_OK;
209 }
210 
init()211 nsresult txKeyHash::init() {
212   mEmptyNodeSet = new txNodeSet(nullptr);
213 
214   return NS_OK;
215 }
216 
217 /**
218  * Adds a match/use pair.
219  * @param aMatch  match-pattern
220  * @param aUse    use-expression
221  * @return false if an error occurred, true otherwise
222  */
addKey(UniquePtr<txPattern> && aMatch,UniquePtr<Expr> && aUse)223 bool txXSLKey::addKey(UniquePtr<txPattern>&& aMatch, UniquePtr<Expr>&& aUse) {
224   if (!aMatch || !aUse) return false;
225 
226   Key* key = mKeys.AppendElement();
227   if (!key) return false;
228 
229   key->matchPattern = std::move(aMatch);
230   key->useExpr = std::move(aUse);
231 
232   return true;
233 }
234 
235 /**
236  * Indexes a document and adds it to the hash of key values
237  * @param aRoot         Subtree root to index and add
238  * @param aKeyValueHash Hash to add values to
239  * @param aEs           txExecutionState to use for XPath evaluation
240  */
indexSubtreeRoot(const txXPathNode & aRoot,txKeyValueHash & aKeyValueHash,txExecutionState & aEs)241 nsresult txXSLKey::indexSubtreeRoot(const txXPathNode& aRoot,
242                                     txKeyValueHash& aKeyValueHash,
243                                     txExecutionState& aEs) {
244   txKeyValueHashKey key(mName, txXPathNodeUtils::getUniqueIdentifier(aRoot),
245                         u""_ns);
246   return indexTree(aRoot, key, aKeyValueHash, aEs);
247 }
248 
249 /**
250  * Recursively searches a node, its attributes and its subtree for
251  * nodes matching any of the keys match-patterns.
252  * @param aNode         Node to search
253  * @param aKey          Key to use when adding into the hash
254  * @param aKeyValueHash Hash to add values to
255  * @param aEs           txExecutionState to use for XPath evaluation
256  */
indexTree(const txXPathNode & aNode,txKeyValueHashKey & aKey,txKeyValueHash & aKeyValueHash,txExecutionState & aEs)257 nsresult txXSLKey::indexTree(const txXPathNode& aNode, txKeyValueHashKey& aKey,
258                              txKeyValueHash& aKeyValueHash,
259                              txExecutionState& aEs) {
260   nsresult rv = testNode(aNode, aKey, aKeyValueHash, aEs);
261   NS_ENSURE_SUCCESS(rv, rv);
262 
263   // check if the node's attributes match
264   txXPathTreeWalker walker(aNode);
265   if (walker.moveToFirstAttribute()) {
266     do {
267       rv = testNode(walker.getCurrentPosition(), aKey, aKeyValueHash, aEs);
268       NS_ENSURE_SUCCESS(rv, rv);
269     } while (walker.moveToNextAttribute());
270     walker.moveToParent();
271   }
272 
273   // check if the node's descendants match
274   if (walker.moveToFirstChild()) {
275     do {
276       rv = indexTree(walker.getCurrentPosition(), aKey, aKeyValueHash, aEs);
277       NS_ENSURE_SUCCESS(rv, rv);
278     } while (walker.moveToNextSibling());
279   }
280 
281   return NS_OK;
282 }
283 
284 /**
285  * Tests one node if it matches any of the keys match-patterns. If
286  * the node matches its values are added to the index.
287  * @param aNode         Node to test
288  * @param aKey          Key to use when adding into the hash
289  * @param aKeyValueHash Hash to add values to
290  * @param aEs           txExecutionState to use for XPath evaluation
291  */
testNode(const txXPathNode & aNode,txKeyValueHashKey & aKey,txKeyValueHash & aKeyValueHash,txExecutionState & aEs)292 nsresult txXSLKey::testNode(const txXPathNode& aNode, txKeyValueHashKey& aKey,
293                             txKeyValueHash& aKeyValueHash,
294                             txExecutionState& aEs) {
295   nsAutoString val;
296   uint32_t currKey, numKeys = mKeys.Length();
297   for (currKey = 0; currKey < numKeys; ++currKey) {
298     bool matched;
299     nsresult rv = mKeys[currKey].matchPattern->matches(aNode, &aEs, matched);
300     NS_ENSURE_SUCCESS(rv, rv);
301 
302     if (matched) {
303       txSingleNodeContext* evalContext = new txSingleNodeContext(aNode, &aEs);
304       NS_ENSURE_TRUE(evalContext, NS_ERROR_OUT_OF_MEMORY);
305 
306       nsresult rv = aEs.pushEvalContext(evalContext);
307       NS_ENSURE_SUCCESS(rv, rv);
308 
309       RefPtr<txAExprResult> exprResult;
310       rv = mKeys[currKey].useExpr->evaluate(evalContext,
311                                             getter_AddRefs(exprResult));
312 
313       delete aEs.popEvalContext();
314       NS_ENSURE_SUCCESS(rv, rv);
315 
316       if (exprResult->getResultType() == txAExprResult::NODESET) {
317         txNodeSet* res =
318             static_cast<txNodeSet*>(static_cast<txAExprResult*>(exprResult));
319         int32_t i;
320         for (i = 0; i < res->size(); ++i) {
321           val.Truncate();
322           txXPathNodeUtils::appendNodeValue(res->get(i), val);
323 
324           aKey.mKeyValue.Assign(val);
325           txKeyValueHashEntry* entry = aKeyValueHash.PutEntry(aKey);
326           NS_ENSURE_TRUE(entry && entry->mNodeSet, NS_ERROR_OUT_OF_MEMORY);
327 
328           if (entry->mNodeSet->isEmpty() ||
329               entry->mNodeSet->get(entry->mNodeSet->size() - 1) != aNode) {
330             entry->mNodeSet->append(aNode);
331           }
332         }
333       } else {
334         exprResult->stringValue(val);
335 
336         aKey.mKeyValue.Assign(val);
337         txKeyValueHashEntry* entry = aKeyValueHash.PutEntry(aKey);
338         NS_ENSURE_TRUE(entry && entry->mNodeSet, NS_ERROR_OUT_OF_MEMORY);
339 
340         if (entry->mNodeSet->isEmpty() ||
341             entry->mNodeSet->get(entry->mNodeSet->size() - 1) != aNode) {
342           entry->mNodeSet->append(aNode);
343         }
344       }
345     }
346   }
347 
348   return NS_OK;
349 }
350