summaryrefslogtreecommitdiffstats
path: root/dom/xslt/xslt/txStylesheet.cpp
blob: b680da01f94aa27b76788137ae45c1217d68a721 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/FloatingPoint.h"
#include "mozilla/Move.h"

#include "txStylesheet.h"
#include "txExpr.h"
#include "txXSLTPatterns.h"
#include "txToplevelItems.h"
#include "txInstructions.h"
#include "txXSLTFunctions.h"
#include "txLog.h"
#include "txKey.h"
#include "txXPathTreeWalker.h"

using mozilla::LogLevel;
using mozilla::Move;

txStylesheet::txStylesheet()
    : mRootFrame(nullptr)
{
}

nsresult
txStylesheet::init()
{
    mRootFrame = new ImportFrame;
    
    // Create default templates
    // element/root template
    mContainerTemplate = new txPushParams;

    nsAutoPtr<txNodeTest> nt(new txNodeTypeTest(txNodeTypeTest::NODE_TYPE));
    nsAutoPtr<Expr> nodeExpr(new LocationStep(nt, LocationStep::CHILD_AXIS));
    nt.forget();

    txPushNewContext* pushContext = new txPushNewContext(Move(nodeExpr));
    mContainerTemplate->mNext = pushContext;

    txApplyDefaultElementTemplate* applyTemplates =
        new txApplyDefaultElementTemplate;
    pushContext->mNext = applyTemplates;

    txLoopNodeSet* loopNodeSet = new txLoopNodeSet(applyTemplates);
    applyTemplates->mNext = loopNodeSet;

    txPopParams* popParams = new txPopParams;
    pushContext->mBailTarget = loopNodeSet->mNext = popParams;

    popParams->mNext = new txReturn();

    // attribute/textnode template
    nt = new txNodeTypeTest(txNodeTypeTest::NODE_TYPE);
    nodeExpr = new LocationStep(nt, LocationStep::SELF_AXIS);
    nt.forget();

    mCharactersTemplate = new txValueOf(Move(nodeExpr), false);
    mCharactersTemplate->mNext = new txReturn();

    // pi/comment/namespace template
    mEmptyTemplate = new txReturn();

    return NS_OK;
}

txStylesheet::~txStylesheet()
{
    // Delete all ImportFrames
    delete mRootFrame;
    txListIterator frameIter(&mImportFrames);
    while (frameIter.hasNext()) {
        delete static_cast<ImportFrame*>(frameIter.next());
    }

    txListIterator instrIter(&mTemplateInstructions);
    while (instrIter.hasNext()) {
        delete static_cast<txInstruction*>(instrIter.next());
    }
    
    // We can't make the map own its values because then we wouldn't be able
    // to merge attributesets of the same name
    txExpandedNameMap<txInstruction>::iterator attrSetIter(mAttributeSets);
    while (attrSetIter.next()) {
        delete attrSetIter.value();
    }
}

txInstruction*
txStylesheet::findTemplate(const txXPathNode& aNode,
                           const txExpandedName& aMode,
                           txIMatchContext* aContext,
                           ImportFrame* aImportedBy,
                           ImportFrame** aImportFrame)
{
    NS_ASSERTION(aImportFrame, "missing ImportFrame pointer");

    *aImportFrame = nullptr;
    txInstruction* matchTemplate = nullptr;
    ImportFrame* endFrame = nullptr;
    txListIterator frameIter(&mImportFrames);

    if (aImportedBy) {
        ImportFrame* curr = static_cast<ImportFrame*>(frameIter.next());
        while (curr != aImportedBy) {
               curr = static_cast<ImportFrame*>(frameIter.next());
        }
        endFrame = aImportedBy->mFirstNotImported;
    }

#if defined(TX_TO_STRING)
    txPattern* match = 0;
#endif

    ImportFrame* frame;
    while (!matchTemplate &&
           (frame = static_cast<ImportFrame*>(frameIter.next())) &&
           frame != endFrame) {

        // get templatelist for this mode
        nsTArray<MatchableTemplate>* templates =
            frame->mMatchableTemplates.get(aMode);

        if (templates) {
            // Find template with highest priority
            uint32_t i, len = templates->Length();
            for (i = 0; i < len && !matchTemplate; ++i) {
                MatchableTemplate& templ = (*templates)[i];
                if (templ.mMatch->matches(aNode, aContext)) {
                    matchTemplate = templ.mFirstInstruction;
                    *aImportFrame = frame;
#if defined(TX_TO_STRING)
                    match = templ.mMatch;
#endif
                }
            }
        }
    }

    if (MOZ_LOG_TEST(txLog::xslt, LogLevel::Debug)) {
      nsAutoString mode, nodeName;
      if (aMode.mLocalName) {
          aMode.mLocalName->ToString(mode);
      }
      txXPathNodeUtils::getNodeName(aNode, nodeName);
      if (matchTemplate) {
          nsAutoString matchAttr;
#ifdef TX_TO_STRING
          match->toString(matchAttr);
#endif
          MOZ_LOG(txLog::xslt, LogLevel::Debug,
                 ("MatchTemplate, Pattern %s, Mode %s, Node %s\n",
                  NS_LossyConvertUTF16toASCII(matchAttr).get(),
                  NS_LossyConvertUTF16toASCII(mode).get(),
                  NS_LossyConvertUTF16toASCII(nodeName).get()));
      }
      else {
          MOZ_LOG(txLog::xslt, LogLevel::Debug,
                 ("No match, Node %s, Mode %s\n", 
                  NS_LossyConvertUTF16toASCII(nodeName).get(),
                  NS_LossyConvertUTF16toASCII(mode).get()));
      }
    }

    if (!matchTemplate) {
        // Test for these first since a node can be both a text node
        // and a root (if it is orphaned)
        if (txXPathNodeUtils::isAttribute(aNode) ||
            txXPathNodeUtils::isText(aNode)) {
            matchTemplate = mCharactersTemplate;
        }
        else if (txXPathNodeUtils::isElement(aNode) ||
                 txXPathNodeUtils::isRoot(aNode)) {
            matchTemplate = mContainerTemplate;
        }
        else {
            matchTemplate = mEmptyTemplate;
        }
    }

    return matchTemplate;
}

txDecimalFormat*
txStylesheet::getDecimalFormat(const txExpandedName& aName)
{
    return mDecimalFormats.get(aName);
}

txInstruction*
txStylesheet::getAttributeSet(const txExpandedName& aName)
{
    return mAttributeSets.get(aName);
}

txInstruction*
txStylesheet::getNamedTemplate(const txExpandedName& aName)
{
    return mNamedTemplates.get(aName);
}

txOutputFormat*
txStylesheet::getOutputFormat()
{
    return &mOutputFormat;
}

txStylesheet::GlobalVariable*
txStylesheet::getGlobalVariable(const txExpandedName& aName)
{
    return mGlobalVariables.get(aName);
}

const txOwningExpandedNameMap<txXSLKey>&
txStylesheet::getKeyMap()
{
    return mKeys;
}

bool
txStylesheet::isStripSpaceAllowed(const txXPathNode& aNode, txIMatchContext* aContext)
{
    int32_t frameCount = mStripSpaceTests.Length();
    if (frameCount == 0) {
        return false;
    }

    txXPathTreeWalker walker(aNode);

    if (txXPathNodeUtils::isText(walker.getCurrentPosition()) &&
        (!txXPathNodeUtils::isWhitespace(aNode) || !walker.moveToParent())) {
        return false;
    }

    const txXPathNode& node = walker.getCurrentPosition();

    if (!txXPathNodeUtils::isElement(node)) {
        return false;
    }

    // check Whitespace stipping handling list against given Node
    int32_t i;
    for (i = 0; i < frameCount; ++i) {
        txStripSpaceTest* sst = mStripSpaceTests[i];
        if (sst->matches(node, aContext)) {
            return sst->stripsSpace() && !XMLUtils::getXMLSpacePreserve(node);
        }
    }

    return false;
}

nsresult
txStylesheet::doneCompiling()
{
    nsresult rv = NS_OK;
    // Collect all importframes into a single ordered list
    txListIterator frameIter(&mImportFrames);
    rv = frameIter.addAfter(mRootFrame);
    NS_ENSURE_SUCCESS(rv, rv);
    
    mRootFrame = nullptr;
    frameIter.next();
    rv = addFrames(frameIter);
    NS_ENSURE_SUCCESS(rv, rv);

    // Loop through importframes in decreasing-precedence-order and process
    // all items
    frameIter.reset();
    ImportFrame* frame;
    while ((frame = static_cast<ImportFrame*>(frameIter.next()))) {
        nsTArray<txStripSpaceTest*> frameStripSpaceTests;

        txListIterator itemIter(&frame->mToplevelItems);
        itemIter.resetToEnd();
        txToplevelItem* item;
        while ((item = static_cast<txToplevelItem*>(itemIter.previous()))) {
            switch (item->getType()) {
                case txToplevelItem::attributeSet:
                {
                    rv = addAttributeSet(static_cast<txAttributeSetItem*>
                                                    (item));
                    NS_ENSURE_SUCCESS(rv, rv);
                    break;
                }
                case txToplevelItem::dummy:
                case txToplevelItem::import:
                {
                    break;
                }
                case txToplevelItem::output:
                {
                    mOutputFormat.merge(static_cast<txOutputItem*>(item)->mFormat);
                    break;
                }
                case txToplevelItem::stripSpace:
                {
                    rv = addStripSpace(static_cast<txStripSpaceItem*>(item),
                                       frameStripSpaceTests);
                    NS_ENSURE_SUCCESS(rv, rv);
                    break;
                }
                case txToplevelItem::templ:
                {
                    rv = addTemplate(static_cast<txTemplateItem*>(item),
                                     frame);
                    NS_ENSURE_SUCCESS(rv, rv);

                    break;
                }
                case txToplevelItem::variable:
                {
                    rv = addGlobalVariable(static_cast<txVariableItem*>
                                                      (item));
                    NS_ENSURE_SUCCESS(rv, rv);

                    break;
                }
            }
            delete item;
            itemIter.remove(); //remove() moves to the previous
            itemIter.next();
        }
        if (!mStripSpaceTests.AppendElements(frameStripSpaceTests)) {
            return NS_ERROR_OUT_OF_MEMORY;
        }
        
        frameStripSpaceTests.Clear();
    }

    if (!mDecimalFormats.get(txExpandedName())) {
        nsAutoPtr<txDecimalFormat> format(new txDecimalFormat);
        rv = mDecimalFormats.add(txExpandedName(), format);
        NS_ENSURE_SUCCESS(rv, rv);
        
        format.forget();
    }

    return NS_OK;
}

nsresult
txStylesheet::addTemplate(txTemplateItem* aTemplate,
                          ImportFrame* aImportFrame)
{
    NS_ASSERTION(aTemplate, "missing template");

    txInstruction* instr = aTemplate->mFirstInstruction;
    nsresult rv = mTemplateInstructions.add(instr);
    NS_ENSURE_SUCCESS(rv, rv);

    // mTemplateInstructions now owns the instructions
    aTemplate->mFirstInstruction.forget();

    if (!aTemplate->mName.isNull()) {
        rv = mNamedTemplates.add(aTemplate->mName, instr);
        NS_ENSURE_TRUE(NS_SUCCEEDED(rv) || rv == NS_ERROR_XSLT_ALREADY_SET,
                       rv);
    }

    if (!aTemplate->mMatch) {
        // This is no error, see section 6 Named Templates

        return NS_OK;
    }

    // get the txList for the right mode
    nsTArray<MatchableTemplate>* templates =
        aImportFrame->mMatchableTemplates.get(aTemplate->mMode);

    if (!templates) {
        nsAutoPtr< nsTArray<MatchableTemplate> > newList(
            new nsTArray<MatchableTemplate>);
        rv = aImportFrame->mMatchableTemplates.set(aTemplate->mMode, newList);
        NS_ENSURE_SUCCESS(rv, rv);

        templates = newList.forget();
    }

    // Add the simple patterns to the list of matchable templates, according
    // to default priority
    nsAutoPtr<txPattern> simple = Move(aTemplate->mMatch);
    nsAutoPtr<txPattern> unionPattern;
    if (simple->getType() == txPattern::UNION_PATTERN) {
        unionPattern = Move(simple);
        simple = unionPattern->getSubPatternAt(0);
        unionPattern->setSubPatternAt(0, nullptr);
    }

    uint32_t unionPos = 1; // only used when unionPattern is set
    while (simple) {
        double priority = aTemplate->mPrio;
        if (mozilla::IsNaN(priority)) {
            priority = simple->getDefaultPriority();
            NS_ASSERTION(!mozilla::IsNaN(priority),
                         "simple pattern without default priority");
        }

        uint32_t i, len = templates->Length();
        for (i = 0; i < len; ++i) {
            if (priority > (*templates)[i].mPriority) {
                break;
            }
        }

        MatchableTemplate* nt = templates->InsertElementAt(i);
        NS_ENSURE_TRUE(nt, NS_ERROR_OUT_OF_MEMORY);

        nt->mFirstInstruction = instr;
        nt->mMatch = Move(simple);
        nt->mPriority = priority;

        if (unionPattern) {
            simple = unionPattern->getSubPatternAt(unionPos);
            if (simple) {
                unionPattern->setSubPatternAt(unionPos, nullptr);
            }
            ++unionPos;
        }
    }

    return NS_OK;
}

nsresult
txStylesheet::addFrames(txListIterator& aInsertIter)
{
    ImportFrame* frame = static_cast<ImportFrame*>(aInsertIter.current());
    nsresult rv = NS_OK;
    txListIterator iter(&frame->mToplevelItems);
    txToplevelItem* item;
    while ((item = static_cast<txToplevelItem*>(iter.next()))) {
        if (item->getType() == txToplevelItem::import) {
            txImportItem* import = static_cast<txImportItem*>(item);
            import->mFrame->mFirstNotImported =
                static_cast<ImportFrame*>(aInsertIter.next());
            rv = aInsertIter.addBefore(import->mFrame);
            NS_ENSURE_SUCCESS(rv, rv);

            import->mFrame.forget();
            aInsertIter.previous();
            rv = addFrames(aInsertIter);
            NS_ENSURE_SUCCESS(rv, rv);
            aInsertIter.previous();
        }
    }
    
    return NS_OK;
}

nsresult
txStylesheet::addStripSpace(txStripSpaceItem* aStripSpaceItem,
                            nsTArray<txStripSpaceTest*>& aFrameStripSpaceTests)
{
    int32_t testCount = aStripSpaceItem->mStripSpaceTests.Length();
    for (; testCount > 0; --testCount) {
        txStripSpaceTest* sst = aStripSpaceItem->mStripSpaceTests[testCount-1];
        double priority = sst->getDefaultPriority();
        int32_t i, frameCount = aFrameStripSpaceTests.Length();
        for (i = 0; i < frameCount; ++i) {
            if (aFrameStripSpaceTests[i]->getDefaultPriority() < priority) {
                break;
            }
        }
        if (!aFrameStripSpaceTests.InsertElementAt(i, sst)) {
            return NS_ERROR_OUT_OF_MEMORY;
        }

        aStripSpaceItem->mStripSpaceTests.RemoveElementAt(testCount-1);
    }

    return NS_OK;
}

nsresult
txStylesheet::addAttributeSet(txAttributeSetItem* aAttributeSetItem)
{
    nsresult rv = NS_OK;
    txInstruction* oldInstr = mAttributeSets.get(aAttributeSetItem->mName);
    if (!oldInstr) {
        rv = mAttributeSets.add(aAttributeSetItem->mName,
                                aAttributeSetItem->mFirstInstruction);
        NS_ENSURE_SUCCESS(rv, rv);
        
        aAttributeSetItem->mFirstInstruction.forget();
        
        return NS_OK;
    }
    
    // We need to prepend the new instructions before the existing ones.
    txInstruction* instr = aAttributeSetItem->mFirstInstruction;
    txInstruction* lastNonReturn = nullptr;
    while (instr->mNext) {
        lastNonReturn = instr;
        instr = instr->mNext;
    }
    
    if (!lastNonReturn) {
        // The new attributeset is empty, so lets just ignore it.
        return NS_OK;
    }

    rv = mAttributeSets.set(aAttributeSetItem->mName,
                            aAttributeSetItem->mFirstInstruction);
    NS_ENSURE_SUCCESS(rv, rv);

    aAttributeSetItem->mFirstInstruction.forget();

    lastNonReturn->mNext = oldInstr;  // ...and link up the old instructions.

    return NS_OK;
}

nsresult
txStylesheet::addGlobalVariable(txVariableItem* aVariable)
{
    if (mGlobalVariables.get(aVariable->mName)) {
        return NS_OK;
    }
    nsAutoPtr<GlobalVariable> var(
        new GlobalVariable(Move(aVariable->mValue),
                           Move(aVariable->mFirstInstruction),
                           aVariable->mIsParam));
    nsresult rv = mGlobalVariables.add(aVariable->mName, var);
    NS_ENSURE_SUCCESS(rv, rv);
    
    var.forget();
    
    return NS_OK;
    
}

nsresult
txStylesheet::addKey(const txExpandedName& aName,
                     nsAutoPtr<txPattern> aMatch, nsAutoPtr<Expr> aUse)
{
    nsresult rv = NS_OK;

    txXSLKey* xslKey = mKeys.get(aName);
    if (!xslKey) {
        xslKey = new txXSLKey(aName);
        rv = mKeys.add(aName, xslKey);
        if (NS_FAILED(rv)) {
            delete xslKey;
            return rv;
        }
    }
    if (!xslKey->addKey(Move(aMatch), Move(aUse))) {
        return NS_ERROR_OUT_OF_MEMORY;
    }
    return NS_OK;
}

nsresult
txStylesheet::addDecimalFormat(const txExpandedName& aName,
                               nsAutoPtr<txDecimalFormat>&& aFormat)
{
    txDecimalFormat* existing = mDecimalFormats.get(aName);
    if (existing) {
        NS_ENSURE_TRUE(existing->isEqual(aFormat),
                       NS_ERROR_XSLT_PARSE_FAILURE);

        return NS_OK;
    }

    nsresult rv = mDecimalFormats.add(aName, aFormat);
    NS_ENSURE_SUCCESS(rv, rv);
    
    aFormat.forget();

    return NS_OK;
}

txStylesheet::ImportFrame::~ImportFrame()
{
    txListIterator tlIter(&mToplevelItems);
    while (tlIter.hasNext()) {
        delete static_cast<txToplevelItem*>(tlIter.next());
    }
}

txStylesheet::GlobalVariable::GlobalVariable(nsAutoPtr<Expr>&& aExpr,
                                             nsAutoPtr<txInstruction>&& aInstr,
                                             bool aIsParam)
    : mExpr(Move(aExpr)),
    mFirstInstruction(Move(aInstr)),
    mIsParam(aIsParam)
{
}