File: XslAstAnalyzer.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (1319 lines) | stat: -rw-r--r-- 58,839 bytes parent folder | download | duplicates (6)
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
//------------------------------------------------------------------------------
// <copyright file="XslAstAnalyzer.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
//------------------------------------------------------------------------------

using System.Globalization;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.XPath;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
using System.Xml.Xsl.XPath;

namespace System.Xml.Xsl.Xslt {
    using TypeFactory       = XmlQueryTypeFactory;
    using XPathFunctionInfo = XPathBuilder.FunctionInfo<XPathBuilder.FuncId>;
    using XsltFunctionInfo  = XPathBuilder.FunctionInfo<QilGenerator.FuncId>;

    // ------------------------------- XslAstAnalyzer -------------------------------

    internal class XslAstAnalyzer : XslVisitor<XslFlags> {
        private CompilerScopeManager<VarPar>  scope;
        private Compiler        compiler;
    #if DEBUG
        // List of all variables and parameters
        private List<VarPar>    allVarPars    = new List<VarPar>();
    #endif
        private int             forEachDepth  = 0;
        private XPathAnalyzer   xpathAnalyzer;
        private ProtoTemplate   currentTemplate;

        // Type donor of the last analyzed VarPar. Used for optimization of WithParam's.
        private VarPar          typeDonor;

        // Template dependencies
        // rev/fwd - Callee-to-Coller/Coller-to-Callee
        // 0/1     - for-each depth
        private Graph<ProtoTemplate> revCall0Graph = new Graph<ProtoTemplate>();
        private Graph<ProtoTemplate> revCall1Graph = new Graph<ProtoTemplate>();
        private Dictionary<Template, Stylesheet> fwdApplyImportsGraph = new Dictionary<Template, Stylesheet>();
        private Dictionary<QilName, List<ProtoTemplate>> revApplyTemplatesGraph = new Dictionary<QilName, List<ProtoTemplate>>();

        // Data flow graph
        private Graph<VarPar> dataFlow = new Graph<VarPar>();

        // Mapping (mode, param name) -> helper vertex in data flow graph
        private Dictionary<ModeName, VarPar> applyTemplatesParams = new Dictionary<ModeName, VarPar>();

        // ---------------------------------- Graph<V> ----------------------------------
        /// <summary>
        /// Represents a graph using hashtable of adjacency lists.
        /// </summary>
        /// <typeparam name="V">Vertex type</typeparam>
        internal class Graph<V> : Dictionary<V, List<V>>
            where V : XslNode
        {
            private static IList<V> empty = (new List<V>()).AsReadOnly();

            public IEnumerable<V> GetAdjList(V v) {
                List<V> adjList;
                if (TryGetValue(v, out adjList) && adjList != null) {
                    return adjList;
                }
                return empty;
            }

            public void AddEdge(V v1, V v2) {
                // Ignore loops
                if ((object)v1 == (object)v2) {
                    return;
                }

                List<V> adjList;
                if (!TryGetValue(v1, out adjList) || adjList == null) {
                    adjList = this[v1] = new List<V>();
                }

                // NOTE: We do not check for duplicate edges here
                adjList.Add(v2);
                if (!TryGetValue(v2, out adjList)) {
                    this[v2] = null;
                }

                Debug.WriteLineIf(DiagnosticsSwitches.XslTypeInference.TraceVerbose, v1.TraceName + " -> " + v2.TraceName);
            }

            public void PropagateFlag(XslFlags flag) {
                // Clean Stop flags
                foreach (V v in Keys) {
                    v.Flags &= ~XslFlags.Stop;
                }

                foreach (V v in Keys) {
                    if ((v.Flags & XslFlags.Stop) == 0) {
                        if ((v.Flags & flag) != 0) {
                            DepthFirstSearch(v, flag);
                        }
                    }
                }
            }

            private void DepthFirstSearch(V v, XslFlags flag) {
                Debug.Assert((v.Flags & XslFlags.Stop) == 0, "Already visited this vertex");
                v.Flags |= (flag | XslFlags.Stop);
                foreach (V u in GetAdjList(v)) {
                    if ((u.Flags & XslFlags.Stop) == 0) {
                        DepthFirstSearch(u, flag);
                    }
                    Debug.Assert((u.Flags & flag) == flag, "Flag was not set on an adjacent vertex");
                }
            }
        }

        internal struct ModeName {
            public QilName Mode;
            public QilName Name;

            public ModeName(QilName mode, QilName name) {
                this.Mode = mode;
                this.Name = name;
            }

            public override int GetHashCode() {
                return Mode.GetHashCode() ^ Name.GetHashCode();
            }
        }

        public XslFlags Analyze(Compiler compiler) {
            this.compiler       = compiler;
            this.scope          = new CompilerScopeManager<VarPar>();
            this.xpathAnalyzer  = new XPathAnalyzer(compiler, scope);

            // Add global parameters and variables to the scope, they are visible everywhere
            foreach (VarPar par in compiler.ExternalPars) {
                scope.AddVariable(par.Name, par);
            }
            foreach (VarPar var in compiler.GlobalVars) {
                scope.AddVariable(var.Name, var);
            }

            // Visit global parameters and variables, but ignore calculated flags
            foreach (VarPar par in compiler.ExternalPars) {
                Visit(par);
                par.Flags |= XslFlags.AnyType;
            }
            foreach (VarPar var in compiler.GlobalVars) {
                Visit(var);
            }

            // Global "----" current/position/last flags
            XslFlags result = XslFlags.None;

            // Visit templates and attribute sets
            foreach (ProtoTemplate tmpl in compiler.AllTemplates) {
                currentTemplate = tmpl;
                result |= Visit(tmpl);
            }

            // At this point for every local parameter we know whether its default value could be used
            // by one of the callers of its template. Update flags for local parameters accordingly.
            foreach (ProtoTemplate tmpl in compiler.AllTemplates) {
                foreach (XslNode instr in tmpl.Content) {
                    // Take care of a bizarre case <xsl:template match="/" xml:space="preserve">  <xsl:param name="par"/>
                    if (instr.NodeType == XslNodeType.Text) {
                        continue;
                    }
                    if (instr.NodeType != XslNodeType.Param) {
                        break;
                    }

                    VarPar par = (VarPar)instr;
                    if ((par.Flags & XslFlags.MayBeDefault) != 0) {
                        par.Flags |= par.DefValueFlags;
                    }
                }
            }

            // Infer XPath types for all variables and local parameters by propagating literal
            // types Rtf, Nodeset, Node, Boolean, Number, String through the data flow graph.
            for (int flag = (int)XslFlags.Rtf; flag != 0; flag >>= 1) {
                dataFlow.PropagateFlag((XslFlags)flag);
            }
            dataFlow = null;

            // We need to follow revCall0Graph graph to propagate focus flags. But first complete
            // dependency graph with fwdApplyImportsGraph
            foreach (KeyValuePair<Template, Stylesheet> pair in fwdApplyImportsGraph) {
                foreach (Stylesheet import in pair.Value.Imports) {
                    AddImportDependencies(import, /*focusDonor:*/pair.Key);
                }
            }
            fwdApplyImportsGraph = null; // Finaly done with this.

            if ((result & XslFlags.Current) != 0) {
                revCall0Graph.PropagateFlag(XslFlags.Current);
            }
            if ((result & XslFlags.Position) != 0) {
                revCall0Graph.PropagateFlag(XslFlags.Position);
            }
            if ((result & XslFlags.Last) != 0) {
                revCall0Graph.PropagateFlag(XslFlags.Last);
            }
            if ((result & XslFlags.SideEffects) != 0) {
                PropagateSideEffectsFlag();
            }
            revCall0Graph = null;
            revCall1Graph = null;
            revApplyTemplatesGraph = null;

            // We can do this only after all flags were propagated.
            // Otherwise we can miss case when flag comes to template from attribute-set
            FillModeFlags(compiler.Root.ModeFlags, compiler.Root.Imports[0]);

            TraceResults();
            return result;
        }

        private void AddImportDependencies(Stylesheet sheet, Template focusDonor) {
            foreach (Template tmpl in sheet.Templates) {
                if (tmpl.Mode.Equals(focusDonor.Mode)) {
                    revCall0Graph.AddEdge(tmpl, focusDonor);
                }
            }
            foreach (Stylesheet import in sheet.Imports) {
                AddImportDependencies(import, focusDonor);
            }
        }

        private void FillModeFlags(Dictionary<QilName, XslFlags> parentModeFlags, Stylesheet sheet) {
            // Recursion: Process all imports to calculate ModeFlags for apply-import in this sheet
            foreach (Stylesheet import in sheet.Imports) {
                FillModeFlags(sheet.ModeFlags, import);
            }
            // My parrent depend on my my templates and templates imported
            // 1. Copy ModeFlags of my imports to my parent
            foreach (KeyValuePair<QilName, XslFlags> modeFlag in sheet.ModeFlags) {
                XslFlags modeFlags;
                if (! parentModeFlags.TryGetValue(modeFlag.Key, out modeFlags)) {
                    modeFlags = 0;
                }
                parentModeFlags[modeFlag.Key] = modeFlags | modeFlag.Value;
            }
            // 2. Add ModeFlags of my templates to my parent
            foreach (Template tmpl in sheet.Templates) {
                Debug.Assert(tmpl.Match != null);
                XslFlags templateFlags = tmpl.Flags & (XslFlags.FocusFilter | XslFlags.SideEffects);
                if (templateFlags != 0) {
                    XslFlags modeFlags;
                    if (! parentModeFlags.TryGetValue(tmpl.Mode, out modeFlags)) {
                        modeFlags = 0;
                    }
                    parentModeFlags[tmpl.Mode] = modeFlags | templateFlags;
                }
            }
        }

        private void TraceResults() {
        #if DEBUG
            if (DiagnosticsSwitches.XslTypeInference.TraceVerbose) {
                Debug.WriteLine(string.Empty);
                foreach (ProtoTemplate tmpl in compiler.AllTemplates) {
                    Debug.WriteLine(tmpl.TraceName + " = " + (tmpl.Flags & XslFlags.FocusFilter));
                }

                Debug.WriteLine(string.Empty);
                foreach (VarPar varPar in allVarPars) {
                    Debug.WriteLine(varPar.TraceName + " = " + (varPar.Flags & XslFlags.TypeFilter));
                }
                Debug.WriteLine(string.Empty);
            }

            if (DiagnosticsSwitches.XslTypeInference.TraceInfo) {
                int current = 0, position = 0, last = 0;

                foreach (ProtoTemplate tmpl in compiler.AllTemplates) {
                    if ((tmpl.Flags & XslFlags.Current) != 0) {
                        current++;
                    }
                    if ((tmpl.Flags & XslFlags.Position) != 0) {
                        position++;
                    }
                    if ((tmpl.Flags & XslFlags.Last) != 0) {
                        last++;
                    }
                }

                int stringType = 0, numberType = 0, booleanType = 0, nodeNotRtfType = 0, nodesetNotRtfType = 0;
                int nodeType = 0, nodesetType = 0, noneType = 0, anyType = 0, totalVarPars = 0;

                foreach (VarPar varPar in allVarPars) {
                    switch (varPar.Flags & XslFlags.TypeFilter) {
                    case XslFlags.String  : stringType++; break;
                    case XslFlags.Number  : numberType++; break;
                    case XslFlags.Boolean : booleanType++; break;
                    case XslFlags.Node    : nodeNotRtfType++; break;
                    case XslFlags.Nodeset : nodesetNotRtfType++; break;
                    case XslFlags.Rtf     : nodeType++; break;
                    case XslFlags.Node    | XslFlags.Rtf     : nodeType++; break;
                    case XslFlags.Node    | XslFlags.Nodeset : nodesetNotRtfType++; break;
                    case XslFlags.Nodeset | XslFlags.Rtf     : nodesetType++; break;
                    case XslFlags.Node    | XslFlags.Nodeset | XslFlags.Rtf : nodesetType++; break;
                    case XslFlags.None    : noneType++; break;
                    default               : anyType++; break;
                    }
                    totalVarPars++;
                }

                Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
                    "Total => templates/attribute-sets: {0}, variables/parameters: {1}.",
                    compiler.AllTemplates.Count, totalVarPars
                ));

                Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
                    "Inferred focus => current: {0}, position: {1}, last: {2}.",
                    current, position, last
                ));

                Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
                    "Inferred types => string: {0}, number: {1}, boolean: {2}, node: {3}, node-set: {4}, " +
                    "node-or-rtf: {5}, node-set-or-rtf: {6}, none: {7}, any: {8}.",
                    stringType, numberType, booleanType, nodeNotRtfType, nodesetNotRtfType,
                    nodeType, nodesetType, noneType, anyType
                ));
            }
        #endif
        }

        protected override XslFlags Visit(XslNode node) {
            scope.EnterScope(node.Namespaces);
            XslFlags result = base.Visit(node);
            scope.ExitScope();

            // Local variables and parameters must be added to the outer scope
            if (currentTemplate != null && (node.NodeType == XslNodeType.Variable || node.NodeType == XslNodeType.Param)) {
                scope.AddVariable(node.Name, (VarPar)node);
            }
            Debug.Assert(
                (result & XslFlags.TypeFilter & ~XslFlags.Rtf) == 0,
                "Instructions always return Rtf. node=" + node.NodeType.ToString() + " result=" + result.ToString()
            );
            return result;
        }

        protected override XslFlags VisitChildren(XslNode node) {
            XslFlags result = XslFlags.None;
            foreach (var child in node.Content) {
                // Visit this child (recurses)
                result |= this.Visit(child);
            }
            return result;
        }

        protected override XslFlags VisitAttributeSet(AttributeSet node) {
            // @use-attribute-sets was processed into a sequence of UseAttributeSet nodes,
            // which were prepended to the content of node
            node.Flags = VisitChildren(node);
            return node.Flags;
        }

        protected override XslFlags VisitTemplate(Template node) {
            // @match does not affect any flags
            //ProcessPattern(match);
            node.Flags = VisitChildren(node);
            return node.Flags;
        }

        protected override XslFlags VisitApplyImports(XslNode node) {
            Debug.Assert(this.forEachDepth == 0, "xsl:apply-imports cannot be inside of xsl:for-each");
            Debug.Assert(currentTemplate is Template, "xsl:apply-imports can only occur within xsl:template");
            fwdApplyImportsGraph[(Template)currentTemplate] = (Stylesheet)node.Arg;
            // xsl:apply-imports uses context node and is not in context of any for-each so it requires current
            return XslFlags.HasCalls | XslFlags.Current | XslFlags.Rtf;
        }

        protected override XslFlags VisitApplyTemplates(XslNode node) {
            Debug.Assert(node.Select != null, "Absent @select should be replaced with 'node()' in XsltLoader");
            XslFlags result = ProcessExpr(node.Select);

            foreach (XslNode instr in node.Content) {
                result |= Visit(instr);
                if (instr.NodeType == XslNodeType.WithParam) {
                    ModeName mn = new ModeName(/*mode:*/node.Name, instr.Name);
                    VarPar modePar;

                    if (!applyTemplatesParams.TryGetValue(mn, out modePar)) {
                        modePar = applyTemplatesParams[mn] = AstFactory.WithParam(instr.Name);
                    }

                    if (typeDonor != null) {
                        dataFlow.AddEdge(typeDonor, modePar);
                    } else {
                        modePar.Flags |= instr.Flags & XslFlags.TypeFilter;
                    }
                }
            }

            if (currentTemplate != null) {
                AddApplyTemplatesEdge(/*mode:*/node.Name, currentTemplate);
            }

            return XslFlags.HasCalls | XslFlags.Rtf | result;
        }

        protected override XslFlags VisitAttribute(NodeCtor node) {
            return (
                XslFlags.Rtf |
                ProcessAvt(node.NameAvt) |
                ProcessAvt(node.NsAvt) |
                VisitChildren(node)
            );
        }

        protected override XslFlags VisitCallTemplate(XslNode node) {
            XslFlags result = XslFlags.None;
            Template target;

            if (!compiler.NamedTemplates.TryGetValue(node.Name, out target)) {
                Debug.WriteLineIf(DiagnosticsSwitches.XslTypeInference.TraceError, "Unknown template " + node.Name.QualifiedName, "Error");
            } else {
                Debug.Assert(target != null);
                if (currentTemplate != null) {
                    if (this.forEachDepth == 0) {
                        // ---- xsl:call-template, target would take its focus from currentTemplate
                        revCall0Graph.AddEdge(target, currentTemplate);
                    } else {
                        // in other cases we need it as donor for side effects flag
                        revCall1Graph.AddEdge(target, currentTemplate);
                    }
                }
            }

            VarPar[] typeDonors = new VarPar[node.Content.Count];
            int idx = 0;

            foreach (XslNode instr in node.Content) {
                Debug.Assert(instr.NodeType == XslNodeType.WithParam);
                result |= Visit(instr);
                typeDonors[idx++] = typeDonor;
            }

            // For each xsl:param in the target template find the corresponding xsl:with-param, and:
            //   a) if the type of xsl:with-param is known, add it to the type of xsl:param;
            //   b) if value of xsl:with-param is a VarPar reference, add an edge connecting it with xsl:param
            //      to the data flow graph.

            if (target != null) {
                foreach (XslNode instr in target.Content) {
                    // Take care of a bizarre case <xsl:template match="/" xml:space="preserve">  <xsl:param name="par"/>
                    if (instr.NodeType == XslNodeType.Text) {
                        continue;
                    }
                    if (instr.NodeType != XslNodeType.Param) {
                        break;
                    }

                    VarPar par   = (VarPar)instr;
                    VarPar found = null;
                    idx = 0;

                    foreach (XslNode withPar in node.Content) {
                        if (withPar.Name.Equals(par.Name)) {
                            found = (VarPar)withPar;
                            typeDonor = typeDonors[idx];
                            break;
                        }
                        idx++;
                    }

                    if (found != null) {
                        // Found corresponding xsl:with-param, check its type
                        if (typeDonor != null) {
                            // add an edge from its type donor to xsl:param
                            dataFlow.AddEdge(typeDonor, par);
                        } else {
                            par.Flags |= found.Flags & XslFlags.TypeFilter;
                        }
                    } else {
                        // No value was specified for this xsl:param, default value will be used for it
                        par.Flags |= XslFlags.MayBeDefault;
                    }
                }
            }

            return XslFlags.HasCalls | XslFlags.Rtf | result;
        }

        //protected override XslFlags VisitChoose(XslNode node) { return VisitChildren(node); }

        protected override XslFlags VisitComment(XslNode node) {
            return XslFlags.Rtf | VisitChildren(node);
        }

        protected override XslFlags VisitCopy(XslNode node) {
            // @use-attribute-sets was processed into a sequence of UseAttributeSet nodes,
            // which were prepended to the content of node
            return XslFlags.Current | XslFlags.Rtf | VisitChildren(node);
        }

        protected override XslFlags VisitCopyOf(XslNode node) {
            return XslFlags.Rtf | ProcessExpr(node.Select);
        }

        protected override XslFlags VisitElement(NodeCtor node) {
            // @use-attribute-sets was processed into a sequence of UseAttributeSet nodes,
            // which were prepended to the content of node
            return (
                XslFlags.Rtf |
                ProcessAvt(node.NameAvt) |
                ProcessAvt(node.NsAvt) |
                VisitChildren(node)
            );
        }

        protected override XslFlags VisitError(XslNode node) {
            return (VisitChildren(node) & ~XslFlags.TypeFilter) | XslFlags.SideEffects;
        }

        protected override XslFlags VisitForEach(XslNode node) {
            XslFlags result = ProcessExpr(node.Select);
            this.forEachDepth ++;
            foreach (XslNode child in node.Content) {
                if (child.NodeType == XslNodeType.Sort) {
                    result |= Visit(child);
                } else {
                    // Since for-each creates new focus, the focus flags of its children does not contribute into result
                    result |= Visit(child) & ~XslFlags.FocusFilter;
                }
            }
            this.forEachDepth --;
            return result;
        }

        protected override XslFlags VisitIf(XslNode node) {
            return ProcessExpr(node.Select) | VisitChildren(node);
        }

        /*
        protected override XslFlags VisitKey(Key node) {
            // @match and @use do not affect any flags
            //ProcessPattern(node.Match);
            //ProcessExpr(node.Use);
        }
        */

        //protected override XslFlags VisitList(XslNode node) { return VisitChildren(node); }

        protected override XslFlags VisitLiteralAttribute(XslNode node) {
            return (
                XslFlags.Rtf |
                ProcessAvt(node.Select) |
                VisitChildren(node)
            );
        }

        protected override XslFlags VisitLiteralElement(XslNode node) {
            return XslFlags.Rtf | VisitChildren(node);
        }

        protected override XslFlags VisitMessage(XslNode node) {
            return (VisitChildren(node) & ~XslFlags.TypeFilter) | XslFlags.SideEffects;
        }

        //protected override XslFlags VisitNop(XslNode node) { return VisitChildren(node); }

        protected override XslFlags VisitNumber(Number node) {
            return (
                XslFlags.Rtf |
                ProcessPattern(node.Count) |
                ProcessPattern(node.From) |
                (node.Value != null ? ProcessExpr(node.Value) : XslFlags.Current) |
                ProcessAvt(node.Format) |
                ProcessAvt(node.Lang) |
                ProcessAvt(node.LetterValue) |
                ProcessAvt(node.GroupingSeparator) |
                ProcessAvt(node.GroupingSize)
            );
        }

        //protected override XslFlags VisitOtherwise(XslNode node) { return VisitChildren(node); }

        protected override XslFlags VisitPI(XslNode node) {
            return (
                XslFlags.Rtf |
                ProcessAvt(node.Select) |
                VisitChildren(node)
            );
        }

        protected override XslFlags VisitSort(Sort node) {
            return (
                // @select is calculated in context of xsl:for-each or xsl:apply-templates,
                // so it does not affect focus flags
                ProcessExpr(node.Select) & ~XslFlags.FocusFilter |
                ProcessAvt(node.Lang) |
                ProcessAvt(node.DataType) |
                ProcessAvt(node.Order) |
                ProcessAvt(node.CaseOrder)
            );
        }

        protected override XslFlags VisitText(Text node) {
            return XslFlags.Rtf | VisitChildren(node);
        }

        protected override XslFlags VisitUseAttributeSet(XslNode node) {
            AttributeSet attSet;
            if (!compiler.AttributeSets.TryGetValue(node.Name, out attSet)) {
                Debug.WriteLineIf(DiagnosticsSwitches.XslTypeInference.TraceError, "Unknown attribute-set " + node.Name.QualifiedName, "Error");
            } else if (currentTemplate != null) {
                if (this.forEachDepth == 0) {
                    // ---- [xsl:]use-attribute-sets, attSet would take its focus from currentTemplate
                    revCall0Graph.AddEdge(attSet, currentTemplate);
                } else {
                    // in other cases we need it as donor for side effects flag
                    revCall1Graph.AddEdge(attSet, currentTemplate);
                }
            }
            return XslFlags.HasCalls | XslFlags.Rtf;
        }

        protected override XslFlags VisitValueOf(XslNode node) {
            return XslFlags.Rtf | ProcessExpr(node.Select);
        }

        protected override XslFlags VisitValueOfDoe(XslNode node) {
            return XslFlags.Rtf | ProcessExpr(node.Select);
        }

        protected override XslFlags VisitParam(VarPar node) {
            Template tmpl = currentTemplate as Template;
            if (tmpl != null && tmpl.Match != null) {
                // This template has 'match' attribute and might be called from built-in template rules,
                // all xsl:param's will be defaulted in that case
                node.Flags |= XslFlags.MayBeDefault;

                ModeName mn = new ModeName(tmpl.Mode, node.Name);
                VarPar par;

                if (!applyTemplatesParams.TryGetValue(mn, out par)) {
                    par = applyTemplatesParams[mn] = AstFactory.WithParam(node.Name);
                }
                dataFlow.AddEdge(par, node);
            }
            node.DefValueFlags = ProcessVarPar(node);
            return node.DefValueFlags & ~XslFlags.TypeFilter;
        }

        protected override XslFlags VisitVariable(VarPar node) {
            node.Flags = ProcessVarPar(node);
            return node.Flags & ~XslFlags.TypeFilter;
        }

        protected override XslFlags VisitWithParam(VarPar node) {
            node.Flags = ProcessVarPar(node);
            return node.Flags & ~XslFlags.TypeFilter;
        }

        private XslFlags ProcessVarPar(VarPar node) {
            XslFlags result;
        #if DEBUG
            if (node.NodeType != XslNodeType.WithParam) {
                allVarPars.Add(node);
            }
        #endif

            if (node.Select != null) {
                if (node.Content.Count != 0) {
                    // In case of incorrect stylesheet, variable or parameter may have both a 'select' attribute and non-empty content
                    // NOTE: This code must be in sync with recovery logic in QilGenerator
                    result = xpathAnalyzer.Analyze(node.Select) | VisitChildren(node) | XslFlags.AnyType;
                    typeDonor = null;
                } else {
                    result = xpathAnalyzer.Analyze(node.Select);
                    typeDonor = xpathAnalyzer.TypeDonor;
                    if (typeDonor != null && node.NodeType != XslNodeType.WithParam) {
                        dataFlow.AddEdge(typeDonor, node);
                    }
                }
            } else if (node.Content.Count != 0) {
                result = XslFlags.Rtf | VisitChildren(node);
                typeDonor = null;
            } else {
                result = XslFlags.String;
                typeDonor = null;
            }
            return result;
        }

        // Ignores XPath type flags
        private XslFlags ProcessExpr(string expr) {
            return xpathAnalyzer.Analyze(expr) & ~XslFlags.TypeFilter;
        }

        // Ignores XPath type flags
        private XslFlags ProcessAvt(string avt) {
            return xpathAnalyzer.AnalyzeAvt(avt) & ~XslFlags.TypeFilter;
        }

        // Ignores XPath type flags and focus flags
        private XslFlags ProcessPattern(string pattern) {
            // We need to analyze using of variables in the pattern
            return xpathAnalyzer.Analyze(pattern) & ~XslFlags.TypeFilter & ~XslFlags.FocusFilter;
        }

        private void AddApplyTemplatesEdge(QilName mode, ProtoTemplate dependentTemplate) {
            List<ProtoTemplate> templates;
            if (!revApplyTemplatesGraph.TryGetValue(mode, out templates)) {
                templates = new List<ProtoTemplate>();
                revApplyTemplatesGraph.Add(mode, templates);
            } else {
                if (templates[templates.Count - 1] == dependentTemplate) {
                    return; // this is a duplicate
                }
            }

            templates.Add(dependentTemplate);
        }

        private void PropagateSideEffectsFlag() {
            // Clean Stop flags
            foreach (ProtoTemplate t in revCall0Graph.Keys) {
                t.Flags &= ~XslFlags.Stop;
            }
            foreach (ProtoTemplate t in revCall1Graph.Keys) {
                t.Flags &= ~XslFlags.Stop;
            }

            foreach (ProtoTemplate t in revCall0Graph.Keys) {
                if ((t.Flags & XslFlags.Stop) == 0) {
                    if ((t.Flags & XslFlags.SideEffects) != 0) {
                        DepthFirstSearch(t);
                    }
                }
            }
            foreach (ProtoTemplate t in revCall1Graph.Keys) {
                if ((t.Flags & XslFlags.Stop) == 0) {
                    if ((t.Flags & XslFlags.SideEffects) != 0) {
                        DepthFirstSearch(t);
                    }
                }
            }
        }

        private void DepthFirstSearch(ProtoTemplate t) {
            Debug.Assert((t.Flags & XslFlags.Stop) == 0, "Already visited this vertex");
            t.Flags |= (XslFlags.SideEffects | XslFlags.Stop);
            List<ProtoTemplate> list;
            foreach (ProtoTemplate u in revCall0Graph.GetAdjList(t)) {
                if ((u.Flags & XslFlags.Stop) == 0) {
                    DepthFirstSearch(u);
                }
                Debug.Assert((u.Flags & XslFlags.SideEffects) == XslFlags.SideEffects, "Flag was not set on an adjacent vertex");
            }
            foreach (ProtoTemplate u in revCall1Graph.GetAdjList(t)) {
                if ((u.Flags & XslFlags.Stop) == 0) {
                    DepthFirstSearch(u);
                }
                Debug.Assert((u.Flags & XslFlags.SideEffects) == XslFlags.SideEffects, "Flag was not set on an adjacent vertex");
            }
            Template template = t as Template;
            if (
                template != null &&                                     // This ProteTemplate is Template
                revApplyTemplatesGraph.TryGetValue(template.Mode, out list)      // list - ProtoTemplates that have apply-templatess mode="{template.Mode}"
            ) {
                revApplyTemplatesGraph.Remove(template.Mode);                    // to prevent recursion remove this list from dictionary
                foreach (ProtoTemplate u in list) {
                    if ((u.Flags & XslFlags.Stop) == 0) {
                        DepthFirstSearch(u);
                    }
                    Debug.Assert((u.Flags & XslFlags.SideEffects) == XslFlags.SideEffects, "Flag was not set on an adjacent vertex");
                }
            }
        }

        // ------------------------------- XPathAnalyzer --------------------------------

        // Ignores all errors and warnings
        internal struct NullErrorHelper : IErrorHelper {
            public void ReportError(string res, params string[] args) { }
            public void ReportWarning(string res, params string[] args) { }
        }

        internal class XPathAnalyzer : IXPathBuilder<XslFlags> {
            private XPathParser<XslFlags> xpathParser = new XPathParser<XslFlags>();
            private CompilerScopeManager<VarPar> scope;
            private Compiler compiler;

            // True if the expression needs XSLT's current() node
            private bool xsltCurrentNeeded;

            // If the expression is just a reference to some VarPar, like "(($foo))",
            // then this field contains that VarPar, and null otherwise.
            private VarPar typeDonor;

            public VarPar TypeDonor {
                get { return typeDonor; }
            }

            public XPathAnalyzer(Compiler compiler, CompilerScopeManager<VarPar> scope) {
                this.compiler = compiler;
                this.scope = scope;
            }

            public XslFlags Analyze(string xpathExpr) {
                typeDonor = null;
                if (xpathExpr == null) {
                    return XslFlags.None;
                }
                try {
                    // Note that the constructor may throw an exception, for example, in case of the expression "'"
                    xsltCurrentNeeded = false;
                    XPathScanner scanner = new XPathScanner(xpathExpr);
                    XslFlags result = xpathParser.Parse(scanner, this, LexKind.Eof);
                    if (xsltCurrentNeeded) {
                        result |= XslFlags.Current;
                    }
                    return result;
                } catch (XslLoadException) {
                    return XslFlags.AnyType | XslFlags.FullFocus;
                }
            }

            public XslFlags AnalyzeAvt(string source) {
                typeDonor = null;
                if (source == null) {
                    return XslFlags.None;
                }
                try {
                    xsltCurrentNeeded = false;
                    XslFlags result = XslFlags.None;
                    int pos = 0;
                    while (pos < source.Length) {
                        pos = source.IndexOf('{', pos);
                        if (pos == -1) {
                            break; // no more AVTs
                        }
                        pos++;
                        if (pos < source.Length && source[pos] == '{') { // "{{"
                            pos++;
                            continue;
                        }
                        if (pos < source.Length) { // '{' encountered, parse an expression
                            XPathScanner scanner = new XPathScanner(source, pos);
                            result |= xpathParser.Parse(scanner, this, LexKind.RBrace);
                            pos = scanner.LexStart + 1;
                        }
                    }
                    if (xsltCurrentNeeded) {
                        result |= XslFlags.Current;
                    }
                    return result & ~XslFlags.TypeFilter;
                } catch (XslLoadException) {
                    return XslFlags.FullFocus;
                }
            }

            // Returns null in case of error
            private VarPar ResolveVariable(string prefix, string name) {
                string ns = ResolvePrefix(prefix);
                if (ns == null) {
                    return null;
                }
                return scope.LookupVariable(name, ns);
            }

            // Returns null in case of error
            private string ResolvePrefix(string prefix) {
                // ignoreDefaultNs == true
                if (prefix.Length == 0) {
                    return string.Empty;
                } else {
                    return scope.LookupNamespace(prefix);
                }
            }

            public virtual void StartBuild() {
            }

            public virtual XslFlags EndBuild(XslFlags result) {
                return result;
            }

            public virtual XslFlags String(string value) {
                typeDonor = null;
                return XslFlags.String;
            }

            public virtual XslFlags Number(double value) {
                typeDonor = null;
                return XslFlags.Number;
            }

            private static XslFlags[] OperatorType = {
                /*Unknown   */ XslFlags.AnyType,
                /*Or        */ XslFlags.Boolean,
                /*And       */ XslFlags.Boolean,
                /*Eq        */ XslFlags.Boolean,
                /*Ne        */ XslFlags.Boolean,
                /*Lt        */ XslFlags.Boolean,
                /*Le        */ XslFlags.Boolean,
                /*Gt        */ XslFlags.Boolean,
                /*Ge        */ XslFlags.Boolean,
                /*Plus      */ XslFlags.Number ,
                /*Minus     */ XslFlags.Number ,
                /*Multiply  */ XslFlags.Number ,
                /*Divide    */ XslFlags.Number ,
                /*Modulo    */ XslFlags.Number ,
                /*UnaryMinus*/ XslFlags.Number ,
                /*Union     */ XslFlags.Nodeset,
            };

            public virtual XslFlags Operator(XPathOperator op, XslFlags left, XslFlags right) {
                typeDonor = null;
                Debug.Assert(op != XPathOperator.Unknown);
                XslFlags result = (left | right) & ~XslFlags.TypeFilter;
                return result | OperatorType[(int)op];
            }

            public virtual XslFlags Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string prefix, string name) {
                typeDonor = null;
                if (xpathAxis == XPathAxis.Self && nodeType == XPathNodeType.All && prefix == null && name == null) {
                    return XslFlags.Current | XslFlags.Node;
                } else {
                    return XslFlags.Current | XslFlags.Nodeset;
                }
            }

            // "left/right"
            public virtual XslFlags JoinStep(XslFlags left, XslFlags right) {
                typeDonor = null;
                return (left & ~XslFlags.TypeFilter) | XslFlags.Nodeset; // "ex:Foo(position())/Bar"
            }

            // "nodeset[predicate]"
            public virtual XslFlags Predicate(XslFlags nodeset, XslFlags predicate, bool isReverseStep) {
                typeDonor = null;
                return (nodeset & ~XslFlags.TypeFilter) | XslFlags.Nodeset | (predicate & XslFlags.SideEffects); // "ex:Foo(position())[Bar]"
            }

            public virtual XslFlags Variable(string prefix, string name) {
                typeDonor = ResolveVariable(prefix, name);
                if (typeDonor == null) {
                    Debug.WriteLineIf(DiagnosticsSwitches.XslTypeInference.TraceError, "Unresolved variable " + Compiler.ConstructQName(prefix, name), "Error");
                    return XslFlags.AnyType;
                }
                return XslFlags.None;
            }

            public virtual XslFlags Function(string prefix, string name, IList<XslFlags> args) {
                typeDonor = null;

                XslFlags argsFlags = XslFlags.None;
                foreach (XslFlags t in args) {
                    argsFlags |= t;
                }

                XslFlags funcFlags = XslFlags.None;

                if (prefix.Length == 0) {
                    XPathFunctionInfo xpathFunc;
                    XsltFunctionInfo xsltFunc;

                    if (XPathBuilder.FunctionTable.TryGetValue(name, out xpathFunc)) {
                        XPathBuilder.FuncId funcId = xpathFunc.id;
                        funcFlags = XPathFunctionFlags[(int)funcId];
                        if (args.Count == 0 && (
                            funcId == XPathBuilder.FuncId.LocalName ||
                            funcId == XPathBuilder.FuncId.NamespaceUri ||
                            funcId == XPathBuilder.FuncId.Name ||
                            funcId == XPathBuilder.FuncId.String ||
                            funcId == XPathBuilder.FuncId.Number ||
                            funcId == XPathBuilder.FuncId.StringLength ||
                            funcId == XPathBuilder.FuncId.Normalize
                        )) {
                            funcFlags |= XslFlags.Current;
                        }
                    } else if (QilGenerator.FunctionTable.TryGetValue(name, out xsltFunc)) {
                        QilGenerator.FuncId funcId = xsltFunc.id;
                        funcFlags = XsltFunctionFlags[(int)funcId];
                        if (funcId == QilGenerator.FuncId.Current) {
                            xsltCurrentNeeded = true;
                        } else if (funcId == QilGenerator.FuncId.GenerateId && args.Count == 0) {
                            funcFlags |= XslFlags.Current;
                        }
                    }
                } else {
                    string ns = ResolvePrefix(prefix);
                    if (ns == XmlReservedNs.NsMsxsl) {
                        switch (name) {
                        case "node-set": funcFlags = XslFlags.Nodeset; break;
                        case "string-compare": funcFlags = XslFlags.Number; break;
                        case "utc": funcFlags = XslFlags.String; break;
                        case "format-date": funcFlags = XslFlags.String; break;
                        case "format-time": funcFlags = XslFlags.String; break;
                        case "local-name": funcFlags = XslFlags.String; break;
                        case "namespace-uri": funcFlags = XslFlags.String | XslFlags.Current; break;
                        case "number": funcFlags = XslFlags.Number; break;
                        }
                    } else if (ns == XmlReservedNs.NsExsltCommon) {
                        switch (name) {
                        case "node-set": funcFlags = XslFlags.Nodeset; break;
                        case "object-type": funcFlags = XslFlags.String; break;
                        }
                    }

                    if (funcFlags == XslFlags.None) {
                        // Unknown function. Can be script function or extension function
                        funcFlags = XslFlags.AnyType;
                        if (compiler.Settings.EnableScript && ns != null) {
                            XmlExtensionFunction scrFunc = compiler.Scripts.ResolveFunction(name, ns, args.Count, new NullErrorHelper());
                            if (scrFunc != null) {
                                XmlQueryType xt = scrFunc.XmlReturnType;
                                if (xt == TypeFactory.StringX) {
                                    funcFlags = XslFlags.String;
                                } else if (xt == TypeFactory.DoubleX) {
                                    funcFlags = XslFlags.Number;
                                } else if (xt == TypeFactory.BooleanX) {
                                    funcFlags = XslFlags.Boolean;
                                } else if (xt == TypeFactory.NodeNotRtf) {
                                    funcFlags = XslFlags.Node;
                                } else if (xt == TypeFactory.NodeSDod) {
                                    funcFlags = XslFlags.Nodeset;
                                } else if (xt == TypeFactory.ItemS) {
                                    funcFlags = XslFlags.AnyType;
                                } else if (xt == TypeFactory.Empty) {
                                    funcFlags = XslFlags.Nodeset;
                                } else {
                                    Debug.Fail("Unexpected XmlQueryType for script function: " + xt.ToString());
                                }
                            }
                        }
                        funcFlags |= XslFlags.SideEffects;
                    }
                }

                return (argsFlags & ~XslFlags.TypeFilter) | funcFlags;
            }

            #region XPath Function Flags
            private static XslFlags[] XPathFunctionFlags = {
            /*Last              */ XslFlags.Number | XslFlags.Last,
            /*Position          */ XslFlags.Number | XslFlags.Position,
            /*Count             */ XslFlags.Number,
            /*LocalName         */ XslFlags.String, // | XslFlags.Current if 0 args
            /*NamespaceUri      */ XslFlags.String, // | XslFlags.Current if 0 args
            /*Name              */ XslFlags.String, // | XslFlags.Current if 0 args
            /*String            */ XslFlags.String, // | XslFlags.Current if 0 args
            /*Number            */ XslFlags.Number, // | XslFlags.Current if 0 args
            /*Boolean           */ XslFlags.Boolean,
            /*True              */ XslFlags.Boolean,
            /*False             */ XslFlags.Boolean,
            /*Not               */ XslFlags.Boolean,
            /*Id                */ XslFlags.Nodeset | XslFlags.Current,
            /*Concat            */ XslFlags.String,
            /*StartsWith        */ XslFlags.Boolean,
            /*Contains          */ XslFlags.Boolean,
            /*SubstringBefore   */ XslFlags.String,
            /*SubstringAfter    */ XslFlags.String,
            /*Substring         */ XslFlags.String,
            /*StringLength      */ XslFlags.Number, // | XslFlags.Current if 0 args
            /*Normalize         */ XslFlags.String, // | XslFlags.Current if 0 args
            /*Translate         */ XslFlags.String,
            /*Lang              */ XslFlags.Boolean | XslFlags.Current,
            /*Sum               */ XslFlags.Number,
            /*Floor             */ XslFlags.Number,
            /*Ceiling           */ XslFlags.Number,
            /*Round             */ XslFlags.Number,
        };
            #endregion

            #region Xslt Function Flags
            private static XslFlags[] XsltFunctionFlags = {
            /*Current           */ XslFlags.Node,   // xsltCurrentNeeded = true
            /*Document          */ XslFlags.Nodeset,
            /*Key               */ XslFlags.Nodeset | XslFlags.Current,
            /*FormatNumber      */ XslFlags.String,
            /*UnparsedEntityUri */ XslFlags.String, // | XslFlags.Current if it is implemented
            /*GenerateId        */ XslFlags.String, // | XslFlags.Current if 0 args
            /*SystemProperty    */ XslFlags.String | XslFlags.Number,
            /*ElementAvailable  */ XslFlags.Boolean,
            /*FunctionAvailable */ XslFlags.Boolean,
        };
            #endregion
        }
    }

    // ------------------------------- XslAstRewriter -------------------------------

    internal sealed class XslAstRewriter {

        private static readonly QilName nullMode = AstFactory.QName(string.Empty);

        private CompilerScopeManager<VarPar> scope;
        private Stack<Template> newTemplates;
        private Compiler compiler;

        public void Rewrite(Compiler compiler) {
            this.compiler = compiler;
            this.scope = new CompilerScopeManager<VarPar>();
            this.newTemplates = new Stack<Template>();

            // Rewrite every template
            foreach (var template in compiler.AllTemplates) {
                scope.EnterScope();
                CheckNodeCost(template);
                scope.CheckEmpty();
            }

            // Add the new templates to the compiled set
            while (newTemplates.Count > 0) {
                var newtemplate = newTemplates.Pop();

                // From Stylesheet.AddTemplate(newtemplate):
                compiler.AllTemplates.Add(newtemplate);
                compiler.NamedTemplates.Add(newtemplate.Name, newtemplate);

                scope.EnterScope();
                CheckNodeCost(newtemplate);
                scope.CheckEmpty();
            }
        }

        // Returns a cost based on an estimate of the number of locals required for the given expression
        private static int NodeCostForXPath(string xpath) {
            int cost = 0;
            if (xpath != null) {
                // Every XPath expression needs at least one iterator
                cost = IteratorNodeCost;
                // Count slashes, two characters at a time, ignore leading slash
                for (int t = 2; t < xpath.Length; t += 2) {
                    if (xpath[t] == '/' || xpath[t - 1] == '/') {
                        cost += IteratorNodeCost;
                    }
                }
            }
            return cost;
        }

        // These values should be changed to achieve methods with ~2KB IL
        const int FixedNodeCost = 1;        // should probably depend on node type
        const int IteratorNodeCost = 2;     // XPath iterators are more expensive
        const int CallTemplateCost = 1;     // best kept at a minimum, 1
        const int RewriteThreshold = 100;

        // These are all the node types for which the .Select member has an XPath expression
        const int NodesWithSelect =
            (1 << (int)XslNodeType.Param) |
            (1 << (int)XslNodeType.Variable) |
            (1 << (int)XslNodeType.WithParam) |
            (1 << (int)XslNodeType.ApplyTemplates) |
            (1 << (int)XslNodeType.CopyOf) |
            (1 << (int)XslNodeType.ForEach) |
            (1 << (int)XslNodeType.If) |
            //(1 << (int)XslNodeType.Number) |          // has XPath, but not in .Select member
            (1 << (int)XslNodeType.Sort) |
            (1 << (int)XslNodeType.ValueOf) |
            (1 << (int)XslNodeType.ValueOfDoe);

        // These are all the node types which can have call-template as a child and are therefor suitable for refactoring
        const int ParentsOfCallTemplate =
            (1 << (int)XslNodeType.Attribute) |
            (1 << (int)XslNodeType.Comment) |
            (1 << (int)XslNodeType.Copy) |
            (1 << (int)XslNodeType.Element) |
            (1 << (int)XslNodeType.ForEach) |
            (1 << (int)XslNodeType.If) |                // also used for xsl:when
            (1 << (int)XslNodeType.Message) |
            (1 << (int)XslNodeType.Otherwise) |
            (1 << (int)XslNodeType.Param) |
            (1 << (int)XslNodeType.PI) |
            (1 << (int)XslNodeType.Template) |
            (1 << (int)XslNodeType.Variable) |
            (1 << (int)XslNodeType.WithParam) |
            (1 << (int)XslNodeType.LiteralAttribute) |
            (1 << (int)XslNodeType.LiteralElement);

        // Tests whether the specified XslNodeType bit is set in the provided flags
        private static bool NodeTypeTest(XslNodeType nodetype, int flags) {
            return ((flags >> (int)nodetype) & 1) != 0;
        }

        private int CheckNodeCost(XslNode node) {
            scope.EnterScope(node.Namespaces);

            // We don't want to allow rewriting by default
            bool canRewrite = false;

            // Use a constant cost for all nodes (should probably depend on the node's type)
            int nodeCost = FixedNodeCost;

            // Detect the number of iterators used by the node's 'select' attribute
            if (NodeTypeTest(node.NodeType, NodesWithSelect)) {
                nodeCost += NodeCostForXPath(node.Select);
            }

            // Iterate through all the child nodes
            var content = node.Content;
            int last = content.Count - 1;
            for (int t = 0; t <= last; ++t) {
                var child = content[t];

                var costForChild = CheckNodeCost(child);        // recurse

                nodeCost += costForChild;
                if (canRewrite && nodeCost > RewriteThreshold) {
                    // This child would overflow the limit for this scope; create a new scope

                    // Don't refactor the code if this is the last child and its cost is trivial
                    if (t < last || costForChild > CallTemplateCost) {

                        //Debug.WriteLine("Node {0} (within {5}) on {1}:{2} has cost {3}; {4} total",
                        //    child.NodeType, child.SourceLine.Start.Line, child.SourceLine.Start.Pos, costForChild, nodeCost, node.NodeType);

                        // Refactor this node, moving the current child and all after into a new template
                        Refactor(node, t);

                        // The new template (containing the remainder of the current node) will be processed later
                        nodeCost -= costForChild;
                        nodeCost += CallTemplateCost;
                    }
                    break;
                }

                // Local variables and parameters must be added to the outer scope
                if (child.NodeType == XslNodeType.Variable || child.NodeType == XslNodeType.Param) {
                    scope.AddVariable(child.Name, (VarPar)child);
                    // Parameters will cause code generation at the call-site, not in the callee
                    if (child.NodeType == XslNodeType.Param) {
                        nodeCost -= costForChild;
                    }
                }
                else if (!canRewrite) {
                    // We're passed the parameters and our first real node; start checking the cost
                    // Note: some nodes like xsl:choose cannot contain xsl:call-template
                    canRewrite = NodeTypeTest(node.NodeType, ParentsOfCallTemplate);
                }
            }

            scope.ExitScope();
            return nodeCost;
        }

        // Splits the children into two pieces: prefix and suffix
        // The prefix calls a new template T, which contains all of the suffix:
        // F=PREFIX~SUFFIX => F=PREFIX~C(T) and T=PARAMS~SUFFIX
        private void Refactor(XslNode parent, int split) {
            Debug.Assert(split > 0);
            var content = (List<XslNode>)parent.Content;

            var node = content[split];

            // Generate unique name for the new template
            QilName templatename = AstFactory.QName("generated", compiler.CreatePhantomNamespace(), "compiler");

            // Create fake ContextInfo for the new nodes, based on the context for the old node
            var fakeCtxInfo = new XsltInput.ContextInfo(node.SourceLine);

            // Create the new call-template node
            var calltemplate = AstFactory.CallTemplate(templatename, fakeCtxInfo);
            XsltLoader.SetInfo(calltemplate, null, fakeCtxInfo);

            // Create a new template node
            Template newtemplate = AstFactory.Template(templatename, null, XsltLoader.nullMode, double.NaN, node.XslVersion);
            XsltLoader.SetInfo(newtemplate, null, fakeCtxInfo);
            newTemplates.Push(newtemplate);

            // Pre-allocate the new content list to minimize the number of resizes (adding some space for any params)
            newtemplate.SetContent(new List<XslNode>(content.Count - split + 8));

            // Pass parameters from the current scope into the called template
            foreach (var scoperecord in scope.GetActiveRecords()) {

                if (!scoperecord.IsVariable) {
                    // The scope record is either a namespace declaration or an exclusion namespace
                    Debug.Assert(scoperecord.IsNamespace || scoperecord.ncName == null);
                    Debug.Assert(!compiler.IsPhantomNamespace(scoperecord.nsUri));
                    newtemplate.Namespaces = new NsDecl(newtemplate.Namespaces, scoperecord.ncName, scoperecord.nsUri);
                }
                else {
                    // The scope contains a variable that we must pass into the new template
                    var variable = scoperecord.value;

                    // Skip variables generated during errors
                    if (compiler.IsPhantomNamespace(variable.Name.NamespaceUri)) {
                        continue;
                    }

                    // Need to create a new QilName (can't reuse the one from the variable, eventhough it's exactly the same)
                    var paramname = AstFactory.QName(variable.Name.LocalName, variable.Name.NamespaceUri, variable.Name.Prefix);

                    // For each variable in scope, add xsl:with-param to the xsl:call-template
                    var withparam = AstFactory.VarPar(XslNodeType.WithParam, paramname, '$' + paramname.QualifiedName, XslVersion.Current);
                    XsltLoader.SetInfo(withparam, null, fakeCtxInfo);
                    withparam.Namespaces = variable.Namespaces;
                    calltemplate.AddContent(withparam);

                    // For each variable in scope, add xsl:param to the xsl:template
                    var param = AstFactory.VarPar(XslNodeType.Param, paramname, null, XslVersion.Current);
                    XsltLoader.SetInfo(param, null, fakeCtxInfo);
                    param.Namespaces = variable.Namespaces;
                    newtemplate.AddContent(param);
                }
            }

            // Move all the other children to the new template as well (AddRange)
            for (int t = split; t < content.Count; ++t) {
                newtemplate.AddContent(content[t]);
            }

            // Replace the child with the rewritten child; remove the rest
            content[split] = calltemplate;
            content.RemoveRange(split + 1, content.Count - split - 1);

            Debug.Assert(parent.Content.Count == split + 1);
        }
    }
}