~bigbes/sr-ht-spec

ref: 4ad8525764dbfb0f7f03eae106b4436cc44040cc sr-ht-spec/prosediff/segment.go -rw-r--r-- 11.2 KiB
4ad85257 — bigbes feat(cmd): reindex a space when a push lands 27 days ago
                                                                                
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
package prosediff

import (
	"fmt"
	"hash/fnv"
	"sort"
	"strings"

	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/ast"
	"github.com/yuin/goldmark/extension"
	extast "github.com/yuin/goldmark/extension/ast"
	"github.com/yuin/goldmark/text"
)

// BlockKind is the structural role of a block. It is part of a block's
// identity: a paragraph that becomes a list item is not a modified paragraph.
type BlockKind string

const (
	KindFrontmatter   BlockKind = "frontmatter"
	KindHeading       BlockKind = "heading"
	KindParagraph     BlockKind = "paragraph"
	KindListItem      BlockKind = "list_item"
	KindCode          BlockKind = "code"
	KindTableHeader   BlockKind = "table_header"
	KindTableRow      BlockKind = "table_row"
	KindThematicBreak BlockKind = "rule"
	KindHTML          BlockKind = "html"
)

// Prose reports whether this kind diffs word-by-word. Everything else diffs
// line-by-line, which is the code-fence distinction the design calls for.
func (k BlockKind) Prose() bool {
	switch k {
	case KindCode, KindFrontmatter, KindHTML:
		return false
	}
	return true
}

// Block is one addressable unit of a document: a paragraph, a heading, a
// single list item, a whole code fence, one table row.
//
// The tuple (HeadingPath, Kind, Ordinal, Hash) is deliberately the anchor
// tuple the design names for inline comments; nothing here is diff-only.
type Block struct {
	Kind        BlockKind
	Ordinal     int      // 0-based position in the document
	Level       int      // heading level, or list nesting depth for list items
	QuoteDepth  int      // blockquote nesting, 0 outside any quote
	HeadingPath []string // enclosing headings, outermost first
	Text        string   // source text of the block, as written
	Lines       []string // source lines; the diff unit for non-prose kinds
	Info        string   // code fence language, list marker, table column count
	StartLine   int      // 1-based, inclusive
	EndLine     int      // 1-based, inclusive
	Hash        string   // structure + normalized content
}

// Empty reports whether the block carries no content at all.
func (b Block) Empty() bool { return strings.TrimSpace(b.Text) == "" }

// Label is a short human description, used by the text renderer and usable
// as-is by a future web layer.
func (b Block) Label() string {
	s := string(b.Kind)
	switch b.Kind {
	case KindHeading:
		s = fmt.Sprintf("h%d", b.Level)
	case KindListItem:
		if b.Level > 1 {
			s = fmt.Sprintf("list item (depth %d)", b.Level)
		} else {
			s = "list item"
		}
	case KindCode:
		if b.Info != "" {
			s = "code:" + b.Info
		}
	}
	if b.QuoteDepth > 0 {
		s = strings.Repeat("quoted ", b.QuoteDepth) + s
	}
	return s
}

// Segment splits a markdown document into blocks in document order.
func Segment(src []byte) []Block {
	body, fm, lineOffset := splitFrontmatter(src)

	s := &segmenter{src: body, lineStarts: lineStarts(body), lineOffset: lineOffset}
	if fm != nil {
		s.blocks = append(s.blocks, finishBlock(Block{
			Kind:      KindFrontmatter,
			Lines:     fm,
			Text:      strings.Join(fm, "\n"),
			StartLine: 1,
			EndLine:   len(fm),
		}))
	}

	md := goldmark.New(goldmark.WithExtensions(extension.Table))
	doc := md.Parser().Parse(text.NewReader(body))
	s.walk(doc, ctx{})

	for i := range s.blocks {
		s.blocks[i].Ordinal = i
	}
	return s.blocks
}

// splitFrontmatter peels a leading YAML frontmatter fence off the document.
// goldmark would otherwise parse "---" as a thematic break and the keys as a
// paragraph, which diffs badly and is not what the block is.
func splitFrontmatter(src []byte) (body []byte, fm []string, lineOffset int) {
	s := string(src)
	if !strings.HasPrefix(s, "---\n") && s != "---" {
		return src, nil, 0
	}
	rest := s[4:]
	end := strings.Index(rest, "\n---")
	if end < 0 {
		return src, nil, 0
	}
	tail := rest[end+4:]
	if tail != "" && !strings.HasPrefix(tail, "\n") {
		return src, nil, 0
	}
	fm = strings.Split(s[:end+8], "\n")
	if tail != "" {
		tail = tail[1:]
	}
	return []byte(tail), fm, len(fm)
}

type ctx struct {
	headings   []string
	quoteDepth int
	listDepth  int
	marker     string
}

type segmenter struct {
	src        []byte
	lineStarts []int
	lineOffset int
	blocks     []Block
	// headingStack holds (level, text) of the currently open headings.
	headingStack []headingEntry
}

type headingEntry struct {
	level int
	text  string
}

func (s *segmenter) walk(n ast.Node, c ctx) {
	for child := n.FirstChild(); child != nil; child = child.NextSibling() {
		s.node(child, c)
	}
}

func (s *segmenter) node(n ast.Node, c ctx) {
	switch v := n.(type) {
	case *ast.Heading:
		txt := s.linesText(v.Lines())
		start, end := s.segLines(v.Lines())
		s.emit(Block{
			Kind:        KindHeading,
			Level:       v.Level,
			QuoteDepth:  c.quoteDepth,
			HeadingPath: s.currentPath(),
			Text:        txt,
			Lines:       splitLines(txt),
			StartLine:   start,
			EndLine:     end,
		})
		s.pushHeading(v.Level, txt)

	case *ast.Paragraph, *ast.TextBlock:
		lines := n.Lines()
		txt := s.linesText(lines)
		if strings.TrimSpace(txt) == "" {
			return
		}
		start, end := s.segLines(lines)
		kind := KindParagraph
		level := 0
		if c.listDepth > 0 {
			kind = KindListItem
			level = c.listDepth
		}
		s.emit(Block{
			Kind:        kind,
			Level:       level,
			QuoteDepth:  c.quoteDepth,
			HeadingPath: s.currentPath(),
			Text:        txt,
			Lines:       splitLines(txt),
			Info:        c.marker,
			StartLine:   start,
			EndLine:     end,
		})

	case *ast.FencedCodeBlock:
		txt := s.linesText(v.Lines())
		start, end := s.segLines(v.Lines())
		info := ""
		if v.Info != nil {
			seg := v.Info.Segment
			info = string(seg.Value(s.src))
		}
		s.emit(Block{
			Kind:        KindCode,
			QuoteDepth:  c.quoteDepth,
			Level:       c.listDepth,
			HeadingPath: s.currentPath(),
			Text:        txt,
			Lines:       splitLines(txt),
			Info:        info,
			StartLine:   start,
			EndLine:     end,
		})

	case *ast.CodeBlock:
		txt := s.linesText(v.Lines())
		start, end := s.segLines(v.Lines())
		s.emit(Block{
			Kind:        KindCode,
			QuoteDepth:  c.quoteDepth,
			Level:       c.listDepth,
			HeadingPath: s.currentPath(),
			Text:        txt,
			Lines:       splitLines(txt),
			Info:        "indented",
			StartLine:   start,
			EndLine:     end,
		})

	case *ast.HTMLBlock:
		txt := s.linesText(v.Lines())
		start, end := s.segLines(v.Lines())
		s.emit(Block{
			Kind:        KindHTML,
			QuoteDepth:  c.quoteDepth,
			HeadingPath: s.currentPath(),
			Text:        txt,
			Lines:       splitLines(txt),
			StartLine:   start,
			EndLine:     end,
		})

	case *ast.ThematicBreak:
		line := s.lineOf(nodeStart(n))
		s.emit(Block{
			Kind:        KindThematicBreak,
			QuoteDepth:  c.quoteDepth,
			HeadingPath: s.currentPath(),
			Text:        "---",
			Lines:       []string{"---"},
			StartLine:   line,
			EndLine:     line,
		})

	case *ast.List:
		inner := c
		inner.listDepth = c.listDepth + 1
		inner.marker = string(rune(v.Marker))
		if v.IsOrdered() {
			inner.marker = "ordered"
		}
		s.walk(v, inner)

	case *ast.ListItem:
		s.walk(v, c)

	case *ast.Blockquote:
		inner := c
		inner.quoteDepth = c.quoteDepth + 1
		s.walk(v, inner)

	case *extast.Table:
		s.table(v, c)

	default:
		// Containers we do not model explicitly still get descended into,
		// so no content is silently dropped.
		if n.Type() == ast.TypeBlock && n.HasChildren() {
			s.walk(n, c)
		}
	}
}

func (s *segmenter) table(t *extast.Table, c ctx) {
	cols := len(t.Alignments)
	for row := t.FirstChild(); row != nil; row = row.NextSibling() {
		kind := KindTableRow
		if row.Kind() == extast.KindTableHeader {
			kind = KindTableHeader
		}
		start, stop := nodeSpan(row)
		if start < 0 {
			continue
		}
		txt := strings.TrimRight(s.sourceLineRange(start, stop), "\n")
		line := s.lineOf(start)
		s.emit(Block{
			Kind:        kind,
			QuoteDepth:  c.quoteDepth,
			HeadingPath: s.currentPath(),
			Text:        txt,
			Lines:       splitLines(txt),
			Info:        fmt.Sprintf("%d cols", cols),
			StartLine:   line,
			EndLine:     s.lineOf(stop),
		})
	}
}

func (s *segmenter) emit(b Block) {
	s.blocks = append(s.blocks, finishBlock(b))
}

// finishBlock computes the identity hash: structure plus normalized content.
// Prose normalizes through the tokenizer (so wrapping does not count); code
// and frontmatter keep their lines verbatim (so whitespace does count).
func finishBlock(b Block) Block {
	h := fnv.New64a()
	fmt.Fprintf(h, "%s\x00%d\x00%d\x00", b.Kind, b.Level, b.QuoteDepth)
	if b.Kind.Prose() {
		h.Write([]byte(Normalize(b.Text)))
	} else {
		h.Write([]byte(b.Info))
		h.Write([]byte{0})
		h.Write([]byte(strings.Join(b.Lines, "\n")))
	}
	b.Hash = fmt.Sprintf("%016x", h.Sum64())
	return b
}

func (s *segmenter) pushHeading(level int, txt string) {
	for len(s.headingStack) > 0 && s.headingStack[len(s.headingStack)-1].level >= level {
		s.headingStack = s.headingStack[:len(s.headingStack)-1]
	}
	s.headingStack = append(s.headingStack, headingEntry{level: level, text: strings.TrimSpace(txt)})
}

func (s *segmenter) currentPath() []string {
	if len(s.headingStack) == 0 {
		return nil
	}
	out := make([]string, len(s.headingStack))
	for i, e := range s.headingStack {
		out[i] = e.text
	}
	return out
}

func (s *segmenter) linesText(segs *text.Segments) string {
	if segs == nil || segs.Len() == 0 {
		return ""
	}
	var sb strings.Builder
	for i := 0; i < segs.Len(); i++ {
		seg := segs.At(i)
		sb.Write(seg.Value(s.src))
	}
	return strings.TrimRight(sb.String(), "\n")
}

func (s *segmenter) segLines(segs *text.Segments) (int, int) {
	if segs == nil || segs.Len() == 0 {
		return 0, 0
	}
	return s.lineOf(segs.At(0).Start), s.lineOf(segs.At(segs.Len()-1).Stop - 1)
}

// sourceLineRange expands a byte span to whole source lines, which is how a
// table row (whose AST node carries only inline segments) recovers the pipe
// syntax the reviewer actually wrote.
func (s *segmenter) sourceLineRange(start, stop int) string {
	if start < 0 || stop > len(s.src) || start > stop {
		return ""
	}
	for start > 0 && s.src[start-1] != '\n' {
		start--
	}
	for stop < len(s.src) && s.src[stop] != '\n' {
		stop++
	}
	return string(s.src[start:stop])
}

func (s *segmenter) lineOf(off int) int {
	i := sort.SearchInts(s.lineStarts, off+1) - 1
	if i < 0 {
		i = 0
	}
	return i + 1 + s.lineOffset
}

func lineStarts(src []byte) []int {
	out := []int{0}
	for i, c := range src {
		if c == '\n' {
			out = append(out, i+1)
		}
	}
	return out
}

func splitLines(s string) []string {
	if s == "" {
		return nil
	}
	return strings.Split(s, "\n")
}

// nodeSpan returns the byte range covered by a node's descendant text
// segments, or (-1, -1) when the node carries none.
func nodeSpan(n ast.Node) (int, int) {
	start, stop := -1, -1
	consider := func(a, b int) {
		if start < 0 || a < start {
			start = a
		}
		if b > stop {
			stop = b
		}
	}
	var visit func(ast.Node)
	visit = func(n ast.Node) {
		if t, ok := n.(*ast.Text); ok {
			consider(t.Segment.Start, t.Segment.Stop)
		}
		// Lines() panics on inline nodes, so it is only asked of blocks.
		if n.Type() == ast.TypeBlock {
			if lines := n.Lines(); lines != nil && lines.Len() > 0 {
				consider(lines.At(0).Start, lines.At(lines.Len()-1).Stop)
			}
		}
		for c := n.FirstChild(); c != nil; c = c.NextSibling() {
			visit(c)
		}
	}
	visit(n)
	return start, stop
}

func nodeStart(n ast.Node) int {
	start, _ := nodeSpan(n)
	if start < 0 {
		return 0
	}
	return start
}