-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilder_inline.go
More file actions
870 lines (808 loc) · 31.3 KB
/
Copy pathbuilder_inline.go
File metadata and controls
870 lines (808 loc) · 31.3 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
package marksplice
import (
"fmt"
"strings"
"unicode/utf8"
"github.com/zoster81/marksplice/internal/source"
"github.com/zoster81/marksplice/internal/splice"
)
type inlineConstructionKind uint8
const (
inlineConstructionText inlineConstructionKind = iota + 1
inlineConstructionCode
inlineConstructionEmphasis
inlineConstructionStrong
inlineConstructionStrikethrough
inlineConstructionLink
inlineConstructionImage
inlineConstructionAutoLink
inlineConstructionBareAutoLink
inlineConstructionReferenceLink
inlineConstructionReferenceImage
inlineConstructionFootnoteReference
inlineConstructionMathDollar
inlineConstructionMathBacktick
)
// Inline is a construction-only typed inline value.
//
// Its zero value is invalid. Use the exported Inline construction functions
// rather than depending on its private representation.
type Inline struct {
kind inlineConstructionKind
text string
destination string
reference string
title string
hasTitle bool
referenceForm typedInlineReferenceForm
referenceScope typedInlineReferenceScope
children []Inline
}
// TextInline returns semantic plain text for typed inline construction.
//
// ASCII punctuation is encoded with canonical GFM backslash escapes so caller text
// cannot become Markdown syntax implicitly. Validation occurs when the
// value is appended to a DocumentBuilder.
func TextInline(text string) Inline {
return Inline{kind: inlineConstructionText, text: text}
}
// CodeInline returns one conservative single-line code span construction value.
//
// The writer selects an adaptive backtick delimiter longer than every internal run.
// Leading/trailing horizontal space and leading/trailing backticks are rejected
// because supporting those shapes would require semantic whitespace or delimiter
// normalization beyond the existing source-proven parsed CodeSpan capability.
func CodeInline(code string) Inline {
return Inline{kind: inlineConstructionCode, text: code}
}
// EmphasisInline returns one conservative emphasis construction value.
// It permits bounded nesting of code, emphasis, strong, and strikethrough children
// while keeping links/images/autolinks outside this wrapper slice.
func EmphasisInline(content ...Inline) Inline {
return Inline{kind: inlineConstructionEmphasis, children: cloneTypedInlineConstruction(content)}
}
// StrongInline returns one conservative strong-emphasis construction value.
// It applies the same bounded structured-child policy as EmphasisInline.
func StrongInline(content ...Inline) Inline {
return Inline{kind: inlineConstructionStrong, children: cloneTypedInlineConstruction(content)}
}
// StrikethroughInline returns one conservative GFM strikethrough construction value.
// It permits bounded code/emphasis/strong children but rejects direct
// strikethrough-in-strikethrough nesting because adjacent tilde runs are ambiguous.
func StrikethroughInline(content ...Inline) Inline {
return Inline{kind: inlineConstructionStrikethrough, children: cloneTypedInlineConstruction(content)}
}
// LinkInline returns one conservative inline-link construction value.
//
// The destination is written in angle brackets and labels may contain the reviewed
// bounded structured-inline children; use LinkInlineWithTitle for a title.
func LinkInline(destination string, label ...Inline) Inline {
return newTypedLinkOrImage(inlineConstructionLink, destination, "", false, label)
}
// LinkInlineWithTitle returns one conservative inline-link construction value
// with a canonical double-quoted title. The title must be non-empty and require no
// GFM escape or entity interpretation.
func LinkInlineWithTitle(destination, title string, label ...Inline) Inline {
return newTypedLinkOrImage(inlineConstructionLink, destination, title, true, label)
}
// ImageInline returns one conservative inline-image construction value.
//
// The destination is written in angle brackets and alt content may contain the reviewed
// bounded structured-inline children; use ImageInlineWithTitle for a title.
func ImageInline(destination string, alt ...Inline) Inline {
return newTypedLinkOrImage(inlineConstructionImage, destination, "", false, alt)
}
// ImageInlineWithTitle returns one conservative inline-image construction value
// with a canonical double-quoted title. It applies the same conservative title policy
// as LinkInlineWithTitle.
func ImageInlineWithTitle(destination, title string, alt ...Inline) Inline {
return newTypedLinkOrImage(inlineConstructionImage, destination, title, true, alt)
}
func newTypedLinkOrImage(kind inlineConstructionKind, destination, title string, hasTitle bool, content []Inline) Inline {
return Inline{
kind: kind,
destination: destination,
title: title,
hasTitle: hasTitle,
children: cloneTypedInlineConstruction(content),
}
}
// AutoLinkInline returns one canonical angle-autolink construction value.
// Validation succeeds only when reparsing produces the existing source-proven AutoLink capability.
func AutoLinkInline(value string) Inline {
return Inline{kind: inlineConstructionAutoLink, text: value}
}
// BareAutoLinkInline returns one parser-proven GFM extended autolink token
// without adding angle brackets. The complete requested token must be owned by
// one AutoLink observation after reparsing or construction fails closed.
func BareAutoLinkInline(value string) Inline {
return Inline{kind: inlineConstructionBareAutoLink, text: value}
}
// AppendHeadingContent appends one top-level ATX heading from typed inline content.
func (b *DocumentBuilder) AppendHeadingContent(level int, content ...Inline) error {
if b == nil {
return fmt.Errorf("%w: nil document builder", ErrInvalidConstruction)
}
inlineGFM, err := b.renderTypedInlineConstruction(content)
if err != nil {
return err
}
return b.AppendHeading(level, inlineGFM)
}
// AppendParagraphContent appends one top-level single-line paragraph from typed inline content.
func (b *DocumentBuilder) AppendParagraphContent(content ...Inline) error {
if b == nil {
return fmt.Errorf("%w: nil document builder", ErrInvalidConstruction)
}
inlineGFM, err := b.renderTypedInlineConstruction(content)
if err != nil {
return err
}
return b.AppendParagraph(inlineGFM)
}
// AppendBlockquoteContent appends one simple top-level blockquote from typed inline content.
func (b *DocumentBuilder) AppendBlockquoteContent(content ...Inline) error {
if b == nil {
return fmt.Errorf("%w: nil document builder", ErrInvalidConstruction)
}
inlineGFM, err := b.renderTypedInlineConstruction(content)
if err != nil {
return err
}
return b.AppendBlockquote(inlineGFM)
}
// AppendNestedBlockquoteContent appends one explicitly nested blockquote from typed inline content.
func (b *DocumentBuilder) AppendNestedBlockquoteContent(depth int, content ...Inline) error {
if b == nil {
return fmt.Errorf("%w: nil document builder", ErrInvalidConstruction)
}
if depth < 2 || depth > maxConstructionBlockquoteDepth {
return fmt.Errorf("%w: nested blockquote depth must be between 2 and %d", ErrInvalidConstruction, maxConstructionBlockquoteDepth)
}
inlineGFM, err := b.renderTypedInlineConstruction(content)
if err != nil {
return err
}
return b.AppendNestedBlockquote(depth, inlineGFM)
}
type typedInlineExpectation struct {
kind Kind
contentRange Range
labelRange Range
titleRange Range
destination string
title string
mathStyle MathExpressionStyle
angleDestination bool
hasTitle bool
}
const maxTypedInlineNestingDepth = 64
type typedInlineWritePolicy uint8
const (
typedInlineTopLevel typedInlineWritePolicy = iota
typedInlineStructuredNested
)
type typedInlineWriteContext struct {
expected *[]typedInlineExpectation
hierarchy *[]splice.ConstructionInlineExpectation
linkImageExpected *[]splice.ConstructionLinkImageExpectation
referenceExpected *[]splice.ConstructionReferenceInlineExpectation
footnoteExpected *[]typedFootnoteReferenceExpectation
referenceDefinitions []typedInlineReferenceDefinition
deferredReferenceDefinitions []typedInlineReferenceDefinition
footnoteDefinitions []string
deferredFootnoteDefinitions []string
policy typedInlineWritePolicy
parent int
depth int
emphasisMarker byte
parentKind inlineConstructionKind
}
func (b *DocumentBuilder) renderTypedInlineConstruction(content []Inline) (string, error) {
if len(content) == 0 {
return "", fmt.Errorf("%w: typed inline content is empty", ErrInvalidConstruction)
}
var output strings.Builder
expected := make([]typedInlineExpectation, 0, len(content))
hierarchy := make([]splice.ConstructionInlineExpectation, 0, len(content))
linkImageExpected := make([]splice.ConstructionLinkImageExpectation, 0, len(content))
referenceExpected := make([]splice.ConstructionReferenceInlineExpectation, 0, len(content))
footnoteExpected := make([]typedFootnoteReferenceExpectation, 0, len(content))
context := typedInlineWriteContext{
expected: &expected,
hierarchy: &hierarchy,
linkImageExpected: &linkImageExpected,
referenceExpected: &referenceExpected,
footnoteExpected: &footnoteExpected,
referenceDefinitions: typedInlineReferenceDefinitions(b.blocks),
deferredReferenceDefinitions: typedInlineReferenceDefinitions(b.deferredReferences),
footnoteDefinitions: constructionFootnoteLabels(b.blocks),
deferredFootnoteDefinitions: constructionFootnoteLabels(b.deferredFootnotes),
policy: typedInlineTopLevel,
parent: -1,
}
for index, inline := range content {
if err := writeTypedInlineConstruction(&output, inline, context); err != nil {
return "", fmt.Errorf("%w: typed inline at index %d: %v", ErrInvalidConstruction, index, err)
}
}
if output.Len() == 0 {
return "", fmt.Errorf("%w: typed inline content is empty", ErrInvalidConstruction)
}
source := output.String()
if err := validateTypedInlineConstruction(source, expected, hierarchy, linkImageExpected, referenceExpected, footnoteExpected); err != nil {
return "", err
}
return source, nil
}
func writeTypedInlineConstruction(output *strings.Builder, inline Inline, context typedInlineWriteContext) error {
inline = normalizeTypedInlineCommonMarkInput(inline)
if !typedInlineKindAllowed(context.policy, inline.kind) {
return fmt.Errorf("nested typed inline kind is not supported")
}
switch inline.kind {
case inlineConstructionText:
return writeTypedInlineText(output, inline.text)
case inlineConstructionCode:
return writeTypedInlineCode(output, inline.text, context)
case inlineConstructionEmphasis, inlineConstructionStrong, inlineConstructionStrikethrough:
return writeTypedInlineDelimited(output, inline, context)
case inlineConstructionLink, inlineConstructionImage:
return writeTypedInlineLinkOrImage(output, inline, context)
case inlineConstructionReferenceLink, inlineConstructionReferenceImage:
return writeTypedInlineReferenceLinkOrImage(output, inline, context)
case inlineConstructionFootnoteReference:
return writeTypedInlineFootnoteReference(output, inline, context)
case inlineConstructionMathDollar, inlineConstructionMathBacktick:
return writeTypedInlineMath(output, inline, context.expected)
case inlineConstructionAutoLink:
return writeTypedInlineAutoLink(output, inline.text, true, context.expected)
case inlineConstructionBareAutoLink:
return writeTypedInlineAutoLink(output, inline.text, false, context.expected)
default:
return fmt.Errorf("unsupported typed inline kind")
}
}
func typedInlineKindAllowed(policy typedInlineWritePolicy, kind inlineConstructionKind) bool {
switch policy {
case typedInlineTopLevel:
return true
case typedInlineStructuredNested:
switch kind {
case inlineConstructionText, inlineConstructionCode, inlineConstructionEmphasis, inlineConstructionStrong, inlineConstructionStrikethrough:
return true
default:
return false
}
default:
return false
}
}
func normalizeTypedInlineCommonMarkInput(inline Inline) Inline {
inline.text = source.NormalizeCommonMarkString(inline.text)
inline.destination = source.NormalizeCommonMarkString(inline.destination)
inline.reference = source.NormalizeCommonMarkString(inline.reference)
inline.title = source.NormalizeCommonMarkString(inline.title)
return inline
}
func writeTypedInlineText(output *strings.Builder, text string) error {
if err := validateTypedInlineText(text); err != nil {
return err
}
writeEscapedInlineText(output, text)
return nil
}
func writeTypedInlineCode(output *strings.Builder, code string, context typedInlineWriteContext) error {
if err := validateTypedInlineCode(code); err != nil {
return err
}
fenceLength := typedInlineCodeFenceLength(code)
fence := strings.Repeat("`", fenceLength)
syntaxStart := output.Len()
output.WriteString(fence)
contentStart := output.Len()
output.WriteString(code)
contentEnd := output.Len()
output.WriteString(fence)
*context.expected = append(*context.expected, typedInlineExpectation{
kind: KindCodeSpan,
contentRange: Range{Start: contentStart, End: contentEnd},
})
*context.hierarchy = append(*context.hierarchy, splice.ConstructionInlineExpectation{
Kind: splice.KindCodeSpan,
SyntaxRange: splice.Range{Start: syntaxStart, End: output.Len()},
ContentRange: splice.Range{Start: contentStart, End: contentEnd},
Marker: '`',
DelimiterLength: fenceLength,
Parent: context.parent,
})
return nil
}
func writeTypedInlineDelimited(output *strings.Builder, inline Inline, context typedInlineWriteContext) error {
if len(inline.children) == 0 {
return fmt.Errorf("delimited inline content is empty")
}
if context.depth >= maxTypedInlineNestingDepth {
return fmt.Errorf("typed inline nesting exceeds %d", maxTypedInlineNestingDepth)
}
if inline.kind == inlineConstructionStrikethrough && context.parentKind == inlineConstructionStrikethrough {
return fmt.Errorf("direct nested strikethrough is not supported")
}
marker, delimiterLength, publicKind, proofKind := typedInlineDelimitedSyntax(inline.kind, context.emphasisMarker)
markerText := strings.Repeat(string(marker), delimiterLength)
syntaxStart := output.Len()
proofIndex := len(*context.hierarchy)
*context.hierarchy = append(*context.hierarchy, splice.ConstructionInlineExpectation{
Kind: proofKind,
Marker: marker,
DelimiterLength: delimiterLength,
Parent: context.parent,
})
output.WriteString(markerText)
contentStart := output.Len()
childContext := context
childContext.policy = typedInlineStructuredNested
childContext.parent = proofIndex
childContext.depth++
childContext.parentKind = inline.kind
if inline.kind == inlineConstructionEmphasis || inline.kind == inlineConstructionStrong {
childContext.emphasisMarker = marker
}
for _, child := range inline.children {
if err := writeTypedInlineConstruction(output, child, childContext); err != nil {
return err
}
}
contentEnd := output.Len()
output.WriteString(markerText)
(*context.hierarchy)[proofIndex].SyntaxRange = splice.Range{Start: syntaxStart, End: output.Len()}
(*context.hierarchy)[proofIndex].ContentRange = splice.Range{Start: contentStart, End: contentEnd}
if typedInlineChildrenAreText(inline.children) {
*context.expected = append(*context.expected, typedInlineExpectation{
kind: publicKind,
contentRange: Range{Start: contentStart, End: contentEnd},
})
}
return nil
}
func typedInlineDelimitedSyntax(kind inlineConstructionKind, parentMarker byte) (byte, int, Kind, splice.Kind) {
if kind == inlineConstructionStrikethrough {
return '~', 2, KindStrikethrough, splice.KindStrikethrough
}
marker := byte('*')
if parentMarker == '*' {
marker = '_'
}
if kind == inlineConstructionStrong {
return marker, 2, KindStrong, splice.KindStrong
}
return marker, 1, KindEmphasis, splice.KindEmphasis
}
func typedInlineChildrenAreText(children []Inline) bool {
for _, child := range children {
if child.kind != inlineConstructionText {
return false
}
}
return true
}
func writeTypedInlineLinkOrImage(output *strings.Builder, inline Inline, context typedInlineWriteContext) error {
if len(inline.children) == 0 {
return fmt.Errorf("link or image label is empty")
}
if err := validateTypedInlineDestination(inline.destination); err != nil {
return err
}
if inline.hasTitle {
if err := validateTypedInlineTitle(inline.title); err != nil {
return err
}
}
kind := KindInlineLink
proofKind := splice.KindInlineLink
syntaxStart := output.Len()
if inline.kind == inlineConstructionImage {
kind = KindImage
proofKind = splice.KindImage
output.WriteByte('!')
}
structured := !typedInlineChildrenAreText(inline.children)
proofIndex := -1
if structured {
proofIndex = len(*context.hierarchy)
*context.hierarchy = append(*context.hierarchy, splice.ConstructionInlineExpectation{
Kind: proofKind,
Parent: context.parent,
})
}
output.WriteByte('[')
labelStart := output.Len()
childContext := context
childContext.policy = typedInlineStructuredNested
childContext.parent = proofIndex
for _, child := range inline.children {
if err := writeTypedInlineConstruction(output, child, childContext); err != nil {
return err
}
}
labelEnd := output.Len()
output.WriteString("](<")
destinationStart := output.Len()
output.WriteString(inline.destination)
destinationEnd := output.Len()
output.WriteByte('>')
titleRange := Range{}
if inline.hasTitle {
output.WriteString(" \"")
titleStart := output.Len()
output.WriteString(inline.title)
titleRange = Range{Start: titleStart, End: output.Len()}
output.WriteByte('"')
}
output.WriteByte(')')
if structured {
(*context.hierarchy)[proofIndex].SyntaxRange = splice.Range{Start: syntaxStart, End: output.Len()}
(*context.hierarchy)[proofIndex].ContentRange = splice.Range{Start: labelStart, End: labelEnd}
*context.linkImageExpected = append(*context.linkImageExpected, splice.ConstructionLinkImageExpectation{
Kind: proofKind,
SyntaxRange: splice.Range{Start: syntaxStart, End: output.Len()},
LabelRange: splice.Range{Start: labelStart, End: labelEnd},
Destination: inline.destination,
Title: inline.title,
HasTitle: inline.hasTitle,
})
return nil
}
*context.expected = append(*context.expected, typedInlineExpectation{
kind: kind,
contentRange: Range{Start: destinationStart, End: destinationEnd},
labelRange: Range{Start: labelStart, End: labelEnd},
titleRange: titleRange,
destination: inline.destination,
title: inline.title,
angleDestination: true,
hasTitle: inline.hasTitle,
})
return nil
}
func writeTypedInlineAutoLink(output *strings.Builder, value string, angle bool, expected *[]typedInlineExpectation) error {
if err := validateTypedInlineAutoLinkValue(value); err != nil {
return err
}
if angle {
output.WriteByte('<')
}
contentStart := output.Len()
output.WriteString(value)
contentEnd := output.Len()
if angle {
output.WriteByte('>')
}
*expected = append(*expected, typedInlineExpectation{
kind: KindAutoLink,
contentRange: Range{Start: contentStart, End: contentEnd},
destination: value,
angleDestination: angle,
})
return nil
}
func validateTypedInlineConstruction(source string, expected []typedInlineExpectation, hierarchy []splice.ConstructionInlineExpectation, linkImages []splice.ConstructionLinkImageExpectation, references []splice.ConstructionReferenceInlineExpectation, footnotes []typedFootnoteReferenceExpectation) error {
if err := splice.ValidateConstructionLinkImages([]byte(source), linkImages); err != nil {
return fmt.Errorf("%w: typed link/image semantic proof: %v", ErrInvalidConstruction, err)
}
if err := splice.ValidateConstructionReferenceInlines([]byte(source), references); err != nil {
return fmt.Errorf("%w: typed reference inline proof: %v", ErrInvalidConstruction, err)
}
if err := splice.ValidateConstructionInlineHierarchy([]byte(source), hierarchy, references); err != nil {
return fmt.Errorf("%w: typed inline hierarchy proof: %v", ErrInvalidConstruction, err)
}
if err := validateTypedFootnoteReferences(source, footnotes); err != nil {
return err
}
document, err := Parse([]byte(source + "\n"))
if err != nil {
return fmt.Errorf("%w: typed inline candidate parse: %v", ErrInvalidConstruction, err)
}
actual, err := collectTypedInlineCandidate(document, len(source), len(expected))
if err != nil {
return err
}
if !sameTypedInlineExpectations(actual, expected) {
return fmt.Errorf("%w: typed inline semantic proof changed", ErrInvalidConstruction)
}
return nil
}
func collectTypedInlineCandidate(document *Document, sourceLength, expectedCount int) ([]typedInlineExpectation, error) {
actual := make([]typedInlineExpectation, 0, expectedCount)
paragraphs := 0
for _, node := range document.Nodes() {
if node.Kind() == KindParagraph {
paragraph, ok := document.Paragraph(node.ID())
if !ok || paragraph.Range() != (Range{Start: 0, End: sourceLength}) {
return nil, fmt.Errorf("%w: typed inline candidate paragraph changed", ErrInvalidConstruction)
}
paragraphs++
continue
}
if constructionOnlyTypedInlineNode(document, node) {
continue
}
expectation, ok, err := typedInlineExpectationFromNode(document, node)
if err != nil {
return nil, err
}
if !ok {
return nil, fmt.Errorf("%w: typed inline candidate introduced public kind %d", ErrInvalidConstruction, node.Kind())
}
actual = append(actual, expectation)
}
if paragraphs != 1 || len(actual) != expectedCount {
return nil, fmt.Errorf("%w: typed inline candidate structure changed", ErrInvalidConstruction)
}
return actual, nil
}
func constructionOnlyTypedInlineNode(document *Document, node Node) bool {
switch node.Kind() {
case KindEmphasis, KindStrong, KindStrikethrough:
internal, ok := document.internalNode(node.ID())
return ok && !internal.Editable
default:
return false
}
}
func typedInlineExpectationFromNode(document *Document, node Node) (typedInlineExpectation, bool, error) {
switch node.Kind() {
case KindStrikethrough:
detail, ok := document.Strikethrough(node.ID())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline strikethrough is not source-proven", ErrInvalidConstruction)
}
return typedInlineExpectation{kind: KindStrikethrough, contentRange: detail.Range()}, true, nil
case KindCodeSpan:
detail, ok := document.CodeSpan(node.ID())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline code span is not source-proven", ErrInvalidConstruction)
}
return typedInlineExpectation{kind: KindCodeSpan, contentRange: detail.Range()}, true, nil
case KindEmphasis:
detail, ok := document.Emphasis(node.ID())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline emphasis is not source-proven", ErrInvalidConstruction)
}
return typedInlineExpectation{kind: KindEmphasis, contentRange: detail.Range()}, true, nil
case KindStrong:
detail, ok := document.Strong(node.ID())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline strong emphasis is not source-proven", ErrInvalidConstruction)
}
return typedInlineExpectation{kind: KindStrong, contentRange: detail.Range()}, true, nil
default:
return typedInlineRelationshipExpectation(document, node)
}
}
func typedInlineRelationshipExpectation(document *Document, node Node) (typedInlineExpectation, bool, error) {
switch node.Kind() {
case KindInlineLink:
return typedInlineLinkExpectation(document, node)
case KindImage:
return typedInlineImageExpectation(document, node)
case KindAutoLink:
return typedInlineAutoLinkExpectation(document, node)
case KindMathExpression:
return typedInlineMathExpectation(document, node)
default:
return typedInlineExpectation{}, false, nil
}
}
func typedInlineMathExpectation(document *Document, node Node) (typedInlineExpectation, bool, error) {
detail, ok := document.MathExpression(node.ID())
if !ok || detail.Style() == MathExpressionFencedBlock {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline math is not source-proven", ErrInvalidConstruction)
}
payload, ok := detail.PayloadRange()
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline math payload is not contiguous", ErrInvalidConstruction)
}
return typedInlineExpectation{kind: KindMathExpression, contentRange: payload, mathStyle: detail.Style()}, true, nil
}
func typedInlineLinkExpectation(document *Document, node Node) (typedInlineExpectation, bool, error) {
detail, ok := document.InlineLink(node.ID())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline link is not source-proven", ErrInvalidConstruction)
}
internal, ok := document.internalNode(node.ID())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline link mapping is incomplete", ErrInvalidConstruction)
}
mapping, ok := document.document.InlineLinkSource(internal.ID)
if !ok || mapping.LabelRange.Start == mapping.LabelRange.End {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline link mapping is incomplete", ErrInvalidConstruction)
}
return typedInlineExpectation{
kind: KindInlineLink,
contentRange: detail.Range(),
labelRange: publicRange(mapping.LabelRange),
titleRange: publicRange(mapping.TitleRange),
destination: internal.Destination,
title: internal.Title,
angleDestination: mapping.AngleDestination,
hasTitle: mapping.HasTitle,
}, true, nil
}
func typedInlineImageExpectation(document *Document, node Node) (typedInlineExpectation, bool, error) {
detail, ok := document.Image(node.ID())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline image is not source-proven", ErrInvalidConstruction)
}
internal, ok := document.internalNode(node.ID())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline image mapping is incomplete", ErrInvalidConstruction)
}
mapping, ok := document.document.ImageSource(internal.ID)
if !ok || mapping.AltRange.Start == mapping.AltRange.End {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline image mapping is incomplete", ErrInvalidConstruction)
}
destination, ok := document.SourceRange(detail.Range())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline image destination is not readable", ErrInvalidConstruction)
}
titleRange := publicRange(mapping.TitleRange)
title := ""
if mapping.HasTitle {
titleSource, ok := document.SourceRange(titleRange)
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed inline image title is not readable", ErrInvalidConstruction)
}
title = string(titleSource)
}
return typedInlineExpectation{
kind: KindImage,
contentRange: detail.Range(),
labelRange: publicRange(mapping.AltRange),
titleRange: titleRange,
destination: string(destination),
title: title,
angleDestination: mapping.AngleDestination,
hasTitle: mapping.HasTitle,
}, true, nil
}
func typedInlineAutoLinkExpectation(document *Document, node Node) (typedInlineExpectation, bool, error) {
detail, ok := document.AutoLink(node.ID())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed autolink is not source-proven", ErrInvalidConstruction)
}
internal, ok := document.internalNode(node.ID())
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed autolink mapping is incomplete", ErrInvalidConstruction)
}
mapping, ok := document.document.AutoLinkSource(internal.ID)
if !ok {
return typedInlineExpectation{}, false, fmt.Errorf("%w: typed autolink mapping is incomplete", ErrInvalidConstruction)
}
return typedInlineExpectation{
kind: KindAutoLink,
contentRange: detail.Range(),
destination: internal.Value,
angleDestination: mapping.Angle,
}, true, nil
}
func sameTypedInlineExpectations(actual, expected []typedInlineExpectation) bool {
if len(actual) != len(expected) {
return false
}
matched := make([]bool, len(actual))
for _, want := range expected {
found := false
for index, got := range actual {
if matched[index] || got != want {
continue
}
matched[index] = true
found = true
break
}
if !found {
return false
}
}
return true
}
func cloneTypedInlineConstruction(content []Inline) []Inline {
return append([]Inline(nil), content...)
}
func validateTypedInlineText(text string) error {
switch {
case text == "":
return fmt.Errorf("typed inline text is empty")
case !utf8.ValidString(text):
return fmt.Errorf("typed inline text is not valid UTF-8")
case strings.ContainsAny(text, "\r\n"):
return fmt.Errorf("typed inline text must stay on one physical line")
case strings.IndexByte(text, 0) >= 0:
return fmt.Errorf("typed inline text contains NUL")
default:
return nil
}
}
func validateTypedInlineCode(code string) error {
if err := validateTypedInlineText(code); err != nil {
return fmt.Errorf("code span %v", err)
}
if isHorizontalInlineSpace(code[0]) || isHorizontalInlineSpace(code[len(code)-1]) {
return fmt.Errorf("code span leading or trailing horizontal space requires normalization")
}
if code[0] == '`' || code[len(code)-1] == '`' {
return fmt.Errorf("code span leading or trailing backtick is not source-proven")
}
return nil
}
func validateTypedInlineDestination(destination string) error {
switch {
case destination == "":
return fmt.Errorf("link destination is empty")
case !utf8.ValidString(destination):
return fmt.Errorf("link destination is not valid UTF-8")
case strings.ContainsAny(destination, "\r\n"):
return fmt.Errorf("link destination must stay on one physical line")
case strings.IndexByte(destination, 0) >= 0:
return fmt.Errorf("link destination contains NUL")
case strings.ContainsAny(destination, "<>\\&"):
return fmt.Errorf("link destination requires GFM escaping or entity interpretation")
default:
return nil
}
}
func validateTypedInlineTitle(title string) error {
if err := validateTypedInlineText(title); err != nil {
return fmt.Errorf("link title %v", err)
}
if strings.ContainsAny(title, "\"\\&") {
return fmt.Errorf("link title requires GFM escaping or entity interpretation")
}
return nil
}
func validateTypedInlineAutoLinkValue(value string) error {
if err := validateTypedInlineText(value); err != nil {
return fmt.Errorf("autolink %v", err)
}
if strings.ContainsAny(value, "<>") {
return fmt.Errorf("autolink value contains an angle bracket")
}
return nil
}
func typedInlineCodeFenceLength(code string) int {
maxRun := 0
for index := 0; index < len(code); {
if code[index] != '`' {
index++
continue
}
end := index + 1
for end < len(code) && code[end] == '`' {
end++
}
if run := end - index; run > maxRun {
maxRun = run
}
index = end
}
return maxRun + 1
}
func writeEscapedInlineText(output *strings.Builder, text string) {
for index := 0; index < len(text); index++ {
value := text[index]
if isASCIIPunctuation(value) {
output.WriteByte('\\')
}
output.WriteByte(value)
}
}
func isASCIIPunctuation(value byte) bool {
return value >= '!' && value <= '/' ||
value >= ':' && value <= '@' ||
value >= '[' && value <= '`' ||
value >= '{' && value <= '~'
}
func isHorizontalInlineSpace(value byte) bool {
return value == ' ' || value == '\t'
}