-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile.go
More file actions
1799 lines (1636 loc) · 47.5 KB
/
compile.go
File metadata and controls
1799 lines (1636 loc) · 47.5 KB
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
package goxslt
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/speedata/goxml"
)
const xslNS = "http://www.w3.org/1999/XSL/Transform"
// compileContext holds state during stylesheet compilation, including
// import precedence tracking, cycle detection, and base path for href resolution.
type compileContext struct {
ss *Stylesheet
seq int
precedence int // current import precedence level
visited map[string]bool // absolute paths → cycle detection
basePath string // directory for resolving relative hrefs
}
// Compile parses an XSLT stylesheet (already parsed as a goxml document) and
// returns a Stylesheet ready for transformation.
// Import/include directives cannot be resolved without a file path; use
// CompileFile for stylesheets that use xsl:import or xsl:include.
func Compile(xsltDoc *goxml.XMLDocument) (*Stylesheet, error) {
ss := &Stylesheet{
DefaultMode: NewMode("", &TextOnlyCopyRuleSet{}),
Modes: make(map[string]*Mode),
Output: OutputProperties{Method: "xml"},
NamedTemplates: make(map[string]*TemplateBody),
Functions: make(map[string]*FunctionDef),
Namespaces: make(map[string]string),
}
ss.Modes[""] = ss.DefaultMode
cc := &compileContext{
ss: ss,
precedence: 1,
visited: make(map[string]bool),
}
if err := cc.compileStylesheet(xsltDoc); err != nil {
return nil, err
}
ss.DefaultMode.ComputeRankings()
for _, m := range ss.Modes {
m.ComputeRankings()
}
return ss, nil
}
// CompileFile compiles an XSLT stylesheet from a file path, enabling
// xsl:import and xsl:include resolution via relative href attributes.
func CompileFile(xsltPath string) (*Stylesheet, error) {
absPath, err := filepath.Abs(xsltPath)
if err != nil {
return nil, fmt.Errorf("XSLT: cannot resolve path %q: %w", xsltPath, err)
}
xsltDoc, err := parseXMLFile(absPath)
if err != nil {
return nil, err
}
ss := &Stylesheet{
DefaultMode: NewMode("", &TextOnlyCopyRuleSet{}),
Modes: make(map[string]*Mode),
Output: OutputProperties{Method: "xml"},
NamedTemplates: make(map[string]*TemplateBody),
Functions: make(map[string]*FunctionDef),
Namespaces: make(map[string]string),
}
ss.Modes[""] = ss.DefaultMode
cc := &compileContext{
ss: ss,
precedence: 1,
visited: map[string]bool{absPath: true},
basePath: filepath.Dir(absPath),
}
if err := cc.compileStylesheet(xsltDoc); err != nil {
return nil, err
}
ss.DefaultMode.ComputeRankings()
for _, m := range ss.Modes {
m.ComputeRankings()
}
ss.BasePath = filepath.Dir(absPath)
ss.StylesheetDoc = xsltDoc
return ss, nil
}
// parseXMLFile opens and parses an XML file.
func parseXMLFile(path string) (*goxml.XMLDocument, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("XSLT: %w", err)
}
defer f.Close()
doc, err := goxml.Parse(f)
if err != nil {
return nil, fmt.Errorf("XSLT: error parsing %s: %w", path, err)
}
return doc, nil
}
// resolveHref resolves a relative href against the compile context's base path.
func (cc *compileContext) resolveHref(href string) (string, error) {
if cc.basePath == "" {
return "", fmt.Errorf("XSLT: xsl:import/include href=%q: no base path (use CompileFile instead of Compile)", href)
}
return filepath.Join(cc.basePath, href), nil
}
// compileStylesheet compiles a single stylesheet document into cc.ss.
func (cc *compileContext) compileStylesheet(xsltDoc *goxml.XMLDocument) error {
root, err := xsltDoc.Root()
if err != nil {
return fmt.Errorf("XSLT: %w", err)
}
// Verify root is xsl:stylesheet or xsl:transform
rootNS := root.Namespaces[root.Prefix]
if rootNS != xslNS {
return fmt.Errorf("XSLT: root element is not xsl:stylesheet (namespace: %s)", rootNS)
}
if root.Name != "stylesheet" && root.Name != "transform" {
return fmt.Errorf("XSLT: root element is %s, expected stylesheet or transform", root.Name)
}
// Copy namespace declarations from the root element so that
// functions and XPath expressions can resolve prefixes.
for prefix, uri := range root.Namespaces {
cc.ss.Namespaces[prefix] = uri
}
// Build result namespaces: all stylesheet namespaces except XSL namespace
// and those listed in exclude-result-prefixes.
excluded := make(map[string]bool)
if erp := attrValue(root, "exclude-result-prefixes"); erp != "" {
if erp == "#all" {
for prefix := range root.Namespaces {
excluded[prefix] = true
}
} else {
for _, p := range strings.Fields(erp) {
if p == "#default" {
excluded[""] = true
} else {
excluded[p] = true
}
}
}
}
cc.ss.ResultNamespaces = make(map[string]string)
for prefix, uri := range root.Namespaces {
if uri == xslNS {
continue
}
if excluded[prefix] {
continue
}
cc.ss.ResultNamespaces[prefix] = uri
}
children := root.Children()
// Phase 1: process xsl:import elements (must come before all other top-level elements).
for _, child := range children {
elt, ok := child.(*goxml.Element)
if !ok {
continue
}
eltNS := elt.Namespaces[elt.Prefix]
if eltNS != xslNS {
break // non-XSL element → imports section is over
}
if elt.Name != "import" {
break // first non-import XSL element → imports section is over
}
if err := cc.processImport(elt); err != nil {
return err
}
}
// Phase 2: process all other top-level elements.
for _, child := range children {
elt, ok := child.(*goxml.Element)
if !ok {
continue
}
eltNS := elt.Namespaces[elt.Prefix]
if eltNS != xslNS {
continue
}
switch elt.Name {
case "import":
// Already processed in phase 1.
continue
case "include":
if err := cc.processInclude(elt); err != nil {
return err
}
case "template":
if err := cc.compileTemplate(elt); err != nil {
return err
}
case "output":
if v := attrValue(elt, "method"); v != "" {
cc.ss.Output.Method = v
}
if v := attrValue(elt, "indent"); v == "yes" {
cc.ss.Output.Indent = true
}
if v := attrValue(elt, "version"); v != "" {
cc.ss.Output.Version = v
}
if v := attrValue(elt, "omit-xml-declaration"); v != "" {
cc.ss.Output.OmitXMLDeclaration = (v == "yes")
}
case "function":
if err := cc.compileFunction(elt); err != nil {
return err
}
case "param":
name := attrValue(elt, "name")
if name == "" {
return fmt.Errorf("XSLT: xsl:param missing name attribute (line %d)", elt.Line)
}
sel := attrValue(elt, "select")
var children []Instruction
if sel == "" {
var err error
children, err = compileChildren(elt, cc.ss.Namespaces)
if err != nil {
return err
}
}
var asType *SequenceType
if asStr := attrValue(elt, "as"); asStr != "" {
var err error
asType, err = parseSequenceType(asStr)
if err != nil {
return fmt.Errorf("XSLT: xsl:param name='%s' as='%s': %w", name, asStr, err)
}
}
p := TemplateParam{Name: name, Select: sel, Children: children, As: asType}
cc.ss.GlobalParams = append(cc.ss.GlobalParams, p)
cc.ss.GlobalDecls = append(cc.ss.GlobalDecls, GlobalDecl{IsParam: true, Param: &cc.ss.GlobalParams[len(cc.ss.GlobalParams)-1]})
case "variable":
v, err := compileVariable(elt)
if err != nil {
return err
}
cc.ss.GlobalVars = append(cc.ss.GlobalVars, *v)
cc.ss.GlobalDecls = append(cc.ss.GlobalDecls, GlobalDecl{IsParam: false, Var: &cc.ss.GlobalVars[len(cc.ss.GlobalVars)-1]})
case "key":
name := attrValue(elt, "name")
if name == "" {
return fmt.Errorf("XSLT: xsl:key missing name attribute (line %d)", elt.Line)
}
matchStr := attrValue(elt, "match")
if matchStr == "" {
return fmt.Errorf("XSLT: xsl:key missing match attribute (line %d)", elt.Line)
}
use := attrValue(elt, "use")
if use == "" {
return fmt.Errorf("XSLT: xsl:key missing use attribute (line %d)", elt.Line)
}
// XTSE0010: xsl:key must not contain child elements when use is specified.
for _, child := range elt.Children() {
if _, ok := child.(*goxml.Element); ok {
return fmt.Errorf("XTSE0010: xsl:key must not contain child elements (line %d)", elt.Line)
}
}
pat, err := parseMatchPattern(matchStr, cc.ss.Namespaces)
if err != nil {
return fmt.Errorf("XSLT: xsl:key match='%s': %w", matchStr, err)
}
composite := attrValue(elt, "composite") == "yes"
expandedName := expandQName(name, elt.Namespaces)
// XTSE1222: all xsl:key declarations with the same name must have
// the same effective value for the composite attribute.
for _, existing := range cc.ss.Keys {
if existing.Name == expandedName && existing.Composite != composite {
return fmt.Errorf("XTSE1222: xsl:key declarations with name '%s' have inconsistent composite attribute (line %d)", name, elt.Line)
}
}
cc.ss.Keys = append(cc.ss.Keys, KeyDefinition{Name: expandedName, Match: pat, Use: use, Composite: composite})
}
}
return nil
}
// processImport handles an xsl:import element. The imported stylesheet gets
// a lower precedence than the importing one.
func (cc *compileContext) processImport(elt *goxml.Element) error {
href := attrValue(elt, "href")
if href == "" {
return fmt.Errorf("XSLT: xsl:import missing href attribute (line %d)", elt.Line)
}
absPath, err := cc.resolveHref(href)
if err != nil {
return err
}
if cc.visited[absPath] {
return fmt.Errorf("XSLT: circular import/include detected: %s", absPath)
}
cc.visited[absPath] = true
doc, err := parseXMLFile(absPath)
if err != nil {
return err
}
// Save current state.
savedPrecedence := cc.precedence
savedBasePath := cc.basePath
// Imported stylesheet gets the current (lower) precedence.
cc.basePath = filepath.Dir(absPath)
if err := cc.compileStylesheet(doc); err != nil {
return fmt.Errorf("XSLT: in imported %s: %w", href, err)
}
// After import: bump precedence so the importing stylesheet gets a higher one.
cc.precedence = savedPrecedence + 1
cc.basePath = savedBasePath
return nil
}
// processInclude handles an xsl:include element. The included stylesheet gets
// the same precedence as the including one.
func (cc *compileContext) processInclude(elt *goxml.Element) error {
href := attrValue(elt, "href")
if href == "" {
return fmt.Errorf("XSLT: xsl:include missing href attribute (line %d)", elt.Line)
}
absPath, err := cc.resolveHref(href)
if err != nil {
return err
}
if cc.visited[absPath] {
return fmt.Errorf("XSLT: circular import/include detected: %s", absPath)
}
cc.visited[absPath] = true
doc, err := parseXMLFile(absPath)
if err != nil {
return err
}
// Save and restore basePath; precedence stays the same.
savedBasePath := cc.basePath
cc.basePath = filepath.Dir(absPath)
if err := cc.compileStylesheet(doc); err != nil {
return fmt.Errorf("XSLT: in included %s: %w", href, err)
}
cc.basePath = savedBasePath
return nil
}
// OutputProperties holds xsl:output settings.
type OutputProperties struct {
Method string // "xml", "html", "text"
Indent bool
Version string
OmitXMLDeclaration bool // omit-xml-declaration="yes" → true
}
// FunctionDef holds a compiled xsl:function definition.
type FunctionDef struct {
Namespace string // resolved namespace URI
LocalName string // function name without prefix
Params []TemplateParam // positional parameters
Body *TemplateBody // compiled body
As *SequenceType // optional return type declaration
}
// Stylesheet holds the compiled XSLT stylesheet.
type Stylesheet struct {
DefaultMode *Mode
Modes map[string]*Mode
Output OutputProperties
NamedTemplates map[string]*TemplateBody
Functions map[string]*FunctionDef // key = "namespace localname"
Keys []KeyDefinition // xsl:key declarations
Namespaces map[string]string // prefix → URI from root element
ResultNamespaces map[string]string // prefix → URI to propagate to output elements
GlobalParams []TemplateParam // top-level xsl:param declarations
GlobalVars []XSLVariable // top-level xsl:variable declarations
GlobalDecls []GlobalDecl // params and variables in declaration order
BasePath string // directory for resolving document() URIs
StylesheetDoc *goxml.XMLDocument // parsed stylesheet document (for document(''))
}
// GlobalDecl represents a top-level parameter or variable in declaration order.
type GlobalDecl struct {
IsParam bool
Param *TemplateParam
Var *XSLVariable
}
func (cc *compileContext) compileTemplate(elt *goxml.Element) error {
matchAttr := attrValue(elt, "match")
nameAttr := attrValue(elt, "name")
modeAttr := attrValue(elt, "mode")
if matchAttr == "" && nameAttr == "" {
return fmt.Errorf("XSLT: xsl:template has neither match nor name attribute (line %d)", elt.Line)
}
body, err := compileTemplateBody(elt, cc.ss.Namespaces)
if err != nil {
return err
}
body.Name = nameAttr
// Register named template (higher precedence wins).
if nameAttr != "" {
cc.ss.NamedTemplates[nameAttr] = body
}
if matchAttr != "" {
pattern, err := parseMatchPattern(matchAttr, cc.ss.Namespaces)
if err != nil {
return fmt.Errorf("XSLT: error parsing match='%s': %w", matchAttr, err)
}
priority := pattern.DefaultPriority()
if p := attrValue(elt, "priority"); p != "" {
if _, err := fmt.Sscanf(p, "%f", &priority); err != nil {
return fmt.Errorf("XSLT: invalid priority '%s'", p)
}
}
mode := cc.ss.DefaultMode
if modeAttr != "" {
var ok bool
mode, ok = cc.ss.Modes[modeAttr]
if !ok {
mode = NewMode(modeAttr, &TextOnlyCopyRuleSet{})
cc.ss.Modes[modeAttr] = mode
}
}
// Handle union patterns: split "a | b" into separate rules.
if up, ok := pattern.(*UnionPattern); ok {
for i, sub := range up.Patterns {
mode.AddRule(sub, body, cc.precedence, sub.DefaultPriority(), cc.seq, i)
}
} else {
mode.AddRule(pattern, body, cc.precedence, priority, cc.seq, 0)
}
cc.seq++
}
return nil
}
// compileChildren compiles the children of an XSLT element into instructions.
func compileChildren(parent *goxml.Element, namespaces ...map[string]string) ([]Instruction, error) {
var ns map[string]string
if len(namespaces) > 0 {
ns = namespaces[0]
}
var instructions []Instruction
for _, child := range parent.Children() {
switch n := child.(type) {
case goxml.CharData:
text := n.Contents
// Skip whitespace-only text nodes between XSLT instructions.
if strings.TrimSpace(text) == "" {
continue
}
instructions = append(instructions, &LiteralText{Text: text})
case *goxml.Element:
childNS := n.Namespaces[n.Prefix]
if childNS == xslNS {
instr, err := compileXSLInstruction(n, ns)
if err != nil {
return nil, err
}
if instr != nil {
instructions = append(instructions, instr)
}
} else {
// Literal result element.
instr, err := compileLiteralElement(n, ns)
if err != nil {
return nil, err
}
instructions = append(instructions, instr)
}
}
}
return instructions, nil
}
func compileXSLInstruction(elt *goxml.Element, namespaces map[string]string) (Instruction, error) {
switch elt.Name {
case "apply-templates":
sel := attrValue(elt, "select")
mode := attrValue(elt, "mode")
sorts, err := extractSorts(elt)
if err != nil {
return nil, err
}
var withParams []XSLWithParam
for _, child := range elt.Children() {
childElt, ok := child.(*goxml.Element)
if !ok {
continue
}
childNS := childElt.Namespaces[childElt.Prefix]
if childNS != xslNS || childElt.Name != "with-param" {
continue
}
pname := attrValue(childElt, "name")
if pname == "" {
return nil, fmt.Errorf("XSLT: xsl:with-param missing name attribute (line %d)", childElt.Line)
}
wpsel := attrValue(childElt, "select")
var children []Instruction
if wpsel == "" {
var err error
children, err = compileChildren(childElt, namespaces)
if err != nil {
return nil, err
}
}
withParams = append(withParams, XSLWithParam{Name: pname, Select: wpsel, Children: children})
}
return &XSLApplyTemplates{Select: sel, Mode: mode, Sorts: sorts, WithParams: withParams}, nil
case "value-of":
sel := attrValue(elt, "select")
if sel == "" {
return nil, fmt.Errorf("XSLT: xsl:value-of missing select attribute (line %d)", elt.Line)
}
sep := " " // XSLT 2.0+ default separator
for _, attr := range elt.Attributes() {
if attr.Name == "separator" {
sep = attr.Value
break
}
}
return &XSLValueOf{Select: sel, Separator: sep}, nil
case "for-each":
sel := attrValue(elt, "select")
if sel == "" {
return nil, fmt.Errorf("XSLT: xsl:for-each missing select attribute (line %d)", elt.Line)
}
sorts, err := extractSorts(elt)
if err != nil {
return nil, err
}
children, err := compileChildren(elt, namespaces)
if err != nil {
return nil, err
}
return &XSLForEach{Select: sel, Sorts: sorts, Children: children}, nil
case "if":
test := attrValue(elt, "test")
if test == "" {
return nil, fmt.Errorf("XSLT: xsl:if missing test attribute (line %d)", elt.Line)
}
children, err := compileChildren(elt, namespaces)
if err != nil {
return nil, err
}
return &XSLIf{Test: test, Children: children}, nil
case "text":
var sb strings.Builder
for _, child := range elt.Children() {
if cd, ok := child.(goxml.CharData); ok {
sb.WriteString(cd.Contents)
}
}
return &XSLText{Text: sb.String()}, nil
case "copy-of":
sel := attrValue(elt, "select")
if sel == "" {
return nil, fmt.Errorf("XSLT: xsl:copy-of missing select attribute (line %d)", elt.Line)
}
return &XSLCopyOf{Select: sel}, nil
case "choose":
return compileChoose(elt, namespaces)
case "variable", "param":
return compileVariable(elt)
case "copy":
children, err := compileChildren(elt, namespaces)
if err != nil {
return nil, err
}
return &XSLCopy{Children: children}, nil
case "attribute":
return compileAttribute(elt, namespaces)
case "call-template":
return compileCallTemplate(elt, namespaces)
case "sequence":
sel := attrValue(elt, "select")
if sel == "" {
return nil, fmt.Errorf("XSLT: xsl:sequence missing select attribute (line %d)", elt.Line)
}
return &XSLSequence{Select: sel}, nil
case "element":
return compileElement(elt, namespaces)
case "comment":
return compileComment(elt, namespaces)
case "processing-instruction":
return compileProcessingInstruction(elt, namespaces)
case "message":
return compileMessage(elt, namespaces)
case "number":
return compileNumber(elt, namespaces)
case "map":
children, err := compileChildren(elt, namespaces)
if err != nil {
return nil, err
}
return &XSLMap{Children: children}, nil
case "map-entry":
key := attrValue(elt, "key")
if key == "" {
return nil, fmt.Errorf("XSLT: xsl:map-entry missing key attribute (line %d)", elt.Line)
}
sel := attrValue(elt, "select")
var children []Instruction
if sel == "" {
var err error
children, err = compileChildren(elt, namespaces)
if err != nil {
return nil, err
}
}
return &XSLMapEntry{Key: key, Select: sel, Children: children}, nil
case "for-each-group":
sel := attrValue(elt, "select")
if sel == "" {
return nil, fmt.Errorf("XSLT: xsl:for-each-group missing select attribute (line %d)", elt.Line)
}
groupBy := attrValue(elt, "group-by")
groupStartingWith := attrValue(elt, "group-starting-with")
if groupBy == "" && groupStartingWith == "" {
return nil, fmt.Errorf("XSLT: xsl:for-each-group missing group-by or group-starting-with attribute (line %d)", elt.Line)
}
var groupStartingPat Pattern
if groupStartingWith != "" {
var patErr error
groupStartingPat, patErr = parseMatchPattern(groupStartingWith, namespaces)
if patErr != nil {
return nil, fmt.Errorf("XSLT: xsl:for-each-group group-starting-with (line %d): %w", elt.Line, patErr)
}
}
sorts, err := extractSorts(elt)
if err != nil {
return nil, err
}
children, err := compileChildren(elt, namespaces)
if err != nil {
return nil, err
}
return &XSLForEachGroup{Select: sel, GroupBy: groupBy, GroupStartingPat: groupStartingPat, Sorts: sorts, Children: children}, nil
case "result-document":
return compileResultDocument(elt, namespaces)
case "analyze-string":
return compileAnalyzeString(elt, namespaces)
case "matching-substring", "non-matching-substring":
// Handled by the parent (analyze-string).
return nil, nil
case "sort":
// xsl:sort is handled by the parent (for-each / apply-templates).
return nil, nil
case "with-param":
// xsl:with-param is handled by the parent (call-template).
return nil, nil
default:
return nil, fmt.Errorf("XSLT: unsupported instruction xsl:%s (line %d)", elt.Name, elt.Line)
}
}
func compileChoose(elt *goxml.Element, namespaces map[string]string) (*XSLChoose, error) {
choose := &XSLChoose{}
for _, child := range elt.Children() {
childElt, ok := child.(*goxml.Element)
if !ok {
continue
}
childNS := childElt.Namespaces[childElt.Prefix]
if childNS != xslNS {
continue
}
switch childElt.Name {
case "when":
test := attrValue(childElt, "test")
if test == "" {
return nil, fmt.Errorf("XSLT: xsl:when missing test attribute (line %d)", childElt.Line)
}
children, err := compileChildren(childElt, namespaces)
if err != nil {
return nil, err
}
choose.When = append(choose.When, XSLWhen{Test: test, Children: children})
case "otherwise":
children, err := compileChildren(childElt, namespaces)
if err != nil {
return nil, err
}
choose.Otherwise = children
}
}
if len(choose.When) == 0 {
return nil, fmt.Errorf("XSLT: xsl:choose must have at least one xsl:when (line %d)", elt.Line)
}
return choose, nil
}
func compileVariable(elt *goxml.Element) (*XSLVariable, error) {
name := attrValue(elt, "name")
if name == "" {
return nil, fmt.Errorf("XSLT: xsl:variable missing name attribute (line %d)", elt.Line)
}
sel := attrValue(elt, "select")
var children []Instruction
if sel == "" {
var err error
children, err = compileChildren(elt)
if err != nil {
return nil, err
}
}
var asType *SequenceType
if asStr := attrValue(elt, "as"); asStr != "" {
var err error
asType, err = parseSequenceType(asStr)
if err != nil {
return nil, fmt.Errorf("XSLT: xsl:variable name='%s' as='%s': %w", name, asStr, err)
}
}
return &XSLVariable{Name: name, Select: sel, Children: children, As: asType}, nil
}
func compileLiteralElement(elt *goxml.Element, namespaces ...map[string]string) (*LiteralElement, error) {
var ns map[string]string
if len(namespaces) > 0 {
ns = namespaces[0]
}
var attrs []LiteralAttribute
for _, attr := range elt.Attributes() {
// Skip xmlns declarations.
if attr.Name == "xmlns" || strings.HasPrefix(attr.Name, "xmlns:") {
continue
}
avt, err := parseAVT(attr.Value)
if err != nil {
return nil, fmt.Errorf("XSLT: error parsing AVT in attribute %s: %w", attr.Name, err)
}
attrName := attr.Name
if attr.Prefix != "" {
attrName = attr.Prefix + ":" + attr.Name
}
attrs = append(attrs, LiteralAttribute{Name: attrName, Namespace: attr.Namespace, Value: avt})
}
children, err := compileChildren(elt, ns)
if err != nil {
return nil, err
}
return &LiteralElement{
Name: elt.Name,
Namespace: elt.Namespaces[elt.Prefix],
Prefix: elt.Prefix,
Attributes: attrs,
Children: children,
}, nil
}
// compileTemplateBody separates leading xsl:param elements from
// instructions and returns a TemplateBody.
func compileTemplateBody(elt *goxml.Element, namespaces ...map[string]string) (*TemplateBody, error) {
var ns map[string]string
if len(namespaces) > 0 {
ns = namespaces[0]
}
var params []TemplateParam
var instructions []Instruction
pastParams := false
for _, child := range elt.Children() {
switch n := child.(type) {
case goxml.CharData:
text := n.Contents
if strings.TrimSpace(text) == "" {
continue
}
pastParams = true
instructions = append(instructions, &LiteralText{Text: text})
case *goxml.Element:
childNS := n.Namespaces[n.Prefix]
if childNS == xslNS && n.Name == "param" && !pastParams {
name := attrValue(n, "name")
if name == "" {
return nil, fmt.Errorf("XSLT: xsl:param missing name attribute (line %d)", n.Line)
}
sel := attrValue(n, "select")
var children []Instruction
if sel == "" {
var err error
children, err = compileChildren(n, ns)
if err != nil {
return nil, err
}
}
var asType *SequenceType
if asStr := attrValue(n, "as"); asStr != "" {
var asErr error
asType, asErr = parseSequenceType(asStr)
if asErr != nil {
return nil, fmt.Errorf("XSLT: xsl:param name='%s' as='%s': %w", name, asStr, asErr)
}
}
params = append(params, TemplateParam{Name: name, Select: sel, Children: children, As: asType})
} else {
pastParams = true
if childNS == xslNS {
instr, err := compileXSLInstruction(n, ns)
if err != nil {
return nil, err
}
if instr != nil {
instructions = append(instructions, instr)
}
} else {
instr, err := compileLiteralElement(n, ns)
if err != nil {
return nil, err
}
instructions = append(instructions, instr)
}
}
}
}
return &TemplateBody{
Params: params,
Instructions: instructions,
}, nil
}
// compileAttribute compiles an xsl:attribute element.
func compileAttribute(elt *goxml.Element, namespaces map[string]string) (*XSLAttribute, error) {
nameStr := attrValue(elt, "name")
if nameStr == "" {
return nil, fmt.Errorf("XSLT: xsl:attribute missing name attribute (line %d)", elt.Line)
}
nameAVT, err := parseAVT(nameStr)
if err != nil {
return nil, fmt.Errorf("XSLT: error parsing name AVT in xsl:attribute: %w", err)
}
var nsAVT AVT
if nsStr := attrValue(elt, "namespace"); nsStr != "" {
nsAVT, err = parseAVT(nsStr)
if err != nil {
return nil, fmt.Errorf("XSLT: error parsing namespace AVT in xsl:attribute: %w", err)
}
}
sel := attrValue(elt, "select")
var children []Instruction
if sel == "" {
children, err = compileChildren(elt, namespaces)
if err != nil {
return nil, err
}
}
return &XSLAttribute{Name: nameAVT, Namespace: nsAVT, Select: sel, Children: children}, nil
}
// compileCallTemplate compiles an xsl:call-template element.
func compileCallTemplate(elt *goxml.Element, namespaces map[string]string) (*XSLCallTemplate, error) {
name := attrValue(elt, "name")
if name == "" {
return nil, fmt.Errorf("XSLT: xsl:call-template missing name attribute (line %d)", elt.Line)
}
var withParams []XSLWithParam
for _, child := range elt.Children() {
childElt, ok := child.(*goxml.Element)
if !ok {
continue
}
childNS := childElt.Namespaces[childElt.Prefix]
if childNS != xslNS || childElt.Name != "with-param" {
continue
}
pname := attrValue(childElt, "name")
if pname == "" {
return nil, fmt.Errorf("XSLT: xsl:with-param missing name attribute (line %d)", childElt.Line)
}
sel := attrValue(childElt, "select")
var children []Instruction
if sel == "" {
var err error
children, err = compileChildren(childElt, namespaces)
if err != nil {
return nil, err
}
}
withParams = append(withParams, XSLWithParam{Name: pname, Select: sel, Children: children})
}
return &XSLCallTemplate{Name: name, WithParams: withParams}, nil
}
func (cc *compileContext) compileFunction(elt *goxml.Element) error {
name := attrValue(elt, "name")
if name == "" {
return fmt.Errorf("XSLT: xsl:function missing name attribute (line %d)", elt.Line)
}
// Split prefix:localname
var prefix, localName string
if idx := strings.IndexByte(name, ':'); idx >= 0 {
prefix = name[:idx]
localName = name[idx+1:]
} else {
return fmt.Errorf("XSLT: xsl:function name '%s' must be in a namespace (line %d)", name, elt.Line)
}
// Resolve prefix to namespace URI (check element namespaces first, then stylesheet)
ns, ok := elt.Namespaces[prefix]
if !ok {
ns, ok = cc.ss.Namespaces[prefix]
}
if !ok {
return fmt.Errorf("XSLT: xsl:function name '%s': cannot resolve prefix '%s' (line %d)", name, prefix, elt.Line)
}
var asType *SequenceType
if asStr := attrValue(elt, "as"); asStr != "" {
var parseErr error
asType, parseErr = parseSequenceType(asStr)
if parseErr != nil {
return fmt.Errorf("XSLT: xsl:function name='%s' as='%s': %w", name, asStr, parseErr)
}
}
body, err := compileTemplateBody(elt, cc.ss.Namespaces)
if err != nil {
return err
}
cc.ss.Functions[ns+" "+localName] = &FunctionDef{
Namespace: ns,
LocalName: localName,