feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
package parser
import (
"strings"
"testing"
)
// The cases are GitHub's, as its Markdown API rendered them.
func TestAlerts(t *testing.T) {
alert := func(kind, title, body string) string {
return `<div class="markdown-alert markdown-alert-` + kind + `">` + "\n" +
`<p class="markdown-alert-title">` + title + "</p>\n" + body + "</div>\n"
}
quote := func(body string) string { return "<blockquote>\n" + body + "</blockquote>\n" }
for _, c := range []struct{ name, src, want string }{
{"note", "> [!NOTE]\n> Body.", alert("note", "Note", "<p>Body.</p>\n")},
{"every kind", "> [!TIP]\n> a\n\n> [!IMPORTANT]\n> a\n\n> [!WARNING]\n> a\n\n> [!CAUTION]\n> a",
alert("tip", "Tip", "<p>a</p>\n") + alert("important", "Important", "<p>a</p>\n") +
alert("warning", "Warning", "<p>a</p>\n") + alert("caution", "Caution", "<p>a</p>\n")},
{"any case", "> [!note]\n> Body.", alert("note", "Note", "<p>Body.</p>\n")},
{"spaces around the marker", "> [!WARNING] \n> Body.", alert("warning", "Warning", "<p>Body.</p>\n")},
{"a blank line first", ">\n> [!NOTE]\n> Body.", alert("note", "Note", "<p>Body.</p>\n")},
{"a lazy line", "> [!NOTE]\nlazy line", alert("note", "Note", "<p>lazy line</p>\n")},
{"a blank line after", "> [!NOTE]\n>\n> Body.", alert("note", "Note", "<p>Body.</p>\n")},
{"a list after", "> [!NOTE]\n> - one", alert("note", "Note", "<ul>\n<li>one</li>\n</ul>\n")},
{"a heading after", "> [!CAUTION]\n> # Head", alert("caution", "Caution", "<h1>Head</h1>\n")},
{"a second marker is text", "> [!NOTE]\n> [!TIP]\n> Body.", alert("note", "Note", "<p>[!TIP]\nBody.</p>\n")},
{"text after the marker", "> [!NOTE] Body.", quote("<p>[!NOTE] Body.</p>\n")},
{"the marker alone", "> [!TIP]", quote("<p>[!TIP]</p>\n")},
{"an unknown kind", "> [!FOO]\n> Body.", quote("<p>[!FOO]\nBody.</p>\n")},
{"nested in a quote", "> > [!NOTE]\n> > Body.", quote(quote("<p>[!NOTE]\nBody.</p>\n"))},
{"in a list", "- item\n\n > [!NOTE]\n > Body.", "<ul>\n<li>\n<p>item</p>\n" + quote("<p>[!NOTE]\nBody.</p>\n") + "</li>\n</ul>\n"},
{"after a paragraph", "> a\n> [!NOTE]\n> Body.", quote("<p>a\n[!NOTE]\nBody.</p>\n")},
{"a marker after the marker", "> [!NOTE]\n>\n> [!TIP]\n> x", alert("note", "Note", "<p>[!TIP]\nx</p>\n")},
{"a definition after the marker", "> [!NOTE]\n>\n> [a]: /u", quote("<p>[!NOTE]</p>\n")},
{"a footnote after the marker", "> [!NOTE]\n> [^1]: x\n\ny[^1]", quote("<p>[!NOTE]</p>\n") + "<p>y<sup class=\"footnote-ref\"><a href=\"#fn-1\" id=\"fnref-1\" data-footnote-ref>1</a></sup></p>\n" +
"<section class=\"footnotes\" data-footnotes>\n<ol>\n<li id=\"fn-1\">\n<p>x</p>\n<a href=\"#fnref-1\" class=\"footnote-backref\">↩</a>\n</li>\n</ol>\n</section>\n"},
} {
d := New(Default)
d.Set(c.src)
if got := d.HTML(); got != c.want {
t.Errorf("%s: %q gives\n%s\nwant\n%s", c.name, c.src, got, c.want)
}
off := New(Default &^ ExtAlerts)
off.Set(c.src)
for i := range off.Len() {
if off.Block(i).Alert != NoAlert {
t.Errorf("%s: an alert without ExtAlerts", c.name)
}
}
}
}
// An alert written a byte at a time, as a reply streams in, ends as it
// parses at once, and is one as soon as its text starts.
func TestAlertStreaming(t *testing.T) {
src := "Intro.\n\n> [!WARNING]\n>\n> Mind the **gap**.\n> - and this\n\nAfter."
want := New(Default)
want.Set(src)
d := New(Default)
d.SetStreaming(true)
for k := range len(src) {
d.Append(src[k : k+1])
if got := d.Source(); len(got) == len("Intro.\n\n> [!WARNING]\n>\n> M") {
if q := d.Block(2); q.Kind != Quote || q.Alert != AlertWarning {
t.Errorf("at %q: block 2 is %v, alert %v", got, q.Kind, q.Alert)
}
}
}
d.SetStreaming(false)
if got, w := d.HTML(), want.HTML(); got != w {
t.Errorf("streamed\n%s\nwant\n%s", got, w)
}
}
// While streaming, a marker alone shows as the alert its quote will
// most likely become; once the text is complete, it is text as GitHub
// has it.
func TestAlertMarkerStreaming(t *testing.T) {
d := New(Default)
d.SetStreaming(true)
d.Set("> [!WARNING]")
if q := d.Block(1); q.Kind != Quote || q.Alert != AlertWarning {
t.Errorf("streaming: %v, alert %v", q.Kind, q.Alert)
}
if got := d.HTML(); strings.Contains(got, "[!WARNING]") {
t.Errorf("the marker shows while streaming: %s", got)
}
d.SetStreaming(false)
if q := d.Block(1); q.Alert != NoAlert {
t.Errorf("complete: alert %v in %s", q.Alert, d.HTML())
}
}
// Editing the marker away, or back, changes the quote.
func TestAlertEdit(t *testing.T) {
d := New(Default)
d.Set("a\n\n> [!NOTE]\n> Body.\n\nb")
if d.Block(2).Alert != AlertNote {
t.Fatalf("no alert in %s", d.HTML())
}
d.Set("a\n\n> [NOTE]\n> Body.\n\nb")
if d.Block(2).Alert != NoAlert {
t.Errorf("an alert without its marker: %s", d.HTML())
}
d.Set("a\n\n> [!TIP]\n> Body.\n\nb")
if d.Block(2).Alert != AlertTip {
t.Errorf("no tip once edited back: %s", d.HTML())
}
}
+352
View File
@@ -0,0 +1,352 @@
package parser
import (
"strings"
"unicode"
"unicode/utf8"
)
// GitHub's extended autolinks, as cmark-gfm finds them (autolink.c):
// www. and http(s):// links as the inline parser comes to their w and :,
// email addresses in the text once parsed.
func isHostChar(s string) bool {
r, n := utf8.DecodeRuneInString(s)
if n == 0 || r == utf8.RuneError && n == 1 {
return false
}
if unicode.IsSpace(r) {
return false
}
if r < utf8.RuneSelf {
return !isEscapable(byte(r))
}
return !unicode.IsPunct(r)
}
// autolinkDelim returns where a link ends once trailing punctuation, an
// entity-like ending and unbalanced parentheses are left out.
func autolinkDelim(data string, end int) int {
open, closing := 0, 0
for i := 0; i < end; i++ {
switch data[i] {
case '<':
end = i
case '(':
open++
case ')':
closing++
}
}
for end > 0 {
switch data[end-1] {
case ')':
if closing <= open {
return end
}
closing--
end--
case '?', '!', '.', ',', ':', '*', '_', '~', '\'', '"':
end--
case ';':
k := end - 2
for k > 0 && isASCIILetter(data[k]) {
k--
}
if k < end-2 && data[k] == '&' {
end = k
} else {
end--
}
default:
return end
}
}
return end
}
// checkDomain returns the length of the domain at the start of data, 0
// if it has an underscore in its last two segments, or, unless short,
// no dot.
func checkDomain(data string, short bool) int {
np, us1, us2 := 0, 0, 0
i := 1
for ; i < len(data)-1; i++ {
if data[i] == '\\' && i < len(data)-2 {
i++
}
switch {
case data[i] == '_':
us2++
case data[i] == '.':
us1, us2 = us2, 0
np++
case !isHostChar(data[i:]) && data[i] != '-':
goto done
}
}
done:
if (us1 > 0 || us2 > 0) && np <= 10 {
return 0
}
if short || np > 0 {
return i
}
return 0
}
// inBracket reports whether a link's or an image's text is open.
func (ip *inlineParser) inBracket() bool { return ip.lastB >= 0 }
// wwwLink reads a link starting with www. at pos.
func (ip *inlineParser) wwwLink() bool {
s := ip.s
pos := ip.pos
if ip.inBracket() || !strings.HasPrefix(s[pos:], "www.") {
return false
}
if pos > 0 && strings.IndexByte("*_~(", s[pos-1]) < 0 && !isUnicodeSpaceByte(s[pos-1]) {
// Beyond ASCII, after a space or punctuation such as “ or (.
if r, _ := utf8.DecodeLastRuneInString(s[:pos]); r < utf8.RuneSelf || !isUnicodeSpace(r) && !endsAutolink(r) {
return false
}
}
data := s[pos:]
end := checkDomain(data, false)
if end == 0 {
return false
}
end = autolinkEnd(data, end)
ip.d.steps += end
end = autolinkDelim(data, end)
if end == 0 {
return false
}
ip.addAutolink(pos, pos+end, "http://"+data[:end])
ip.pos = pos + end
return true
}
// autolinkEnd returns where a link's text starting at data[:end] runs
// out: at a space, a <, or punctuation beyond ASCII, such as the CJK ,
// and 。 or curly quotes, which text written without spaces puts right
// after a link. Letters beyond ASCII, as in IDN hosts and paths, go on.
func autolinkEnd(data string, end int) int {
for end < len(data) && !isUnicodeSpaceByte(data[end]) && data[end] != '<' {
if data[end] < utf8.RuneSelf {
end++
continue
}
r, n := utf8.DecodeRuneInString(data[end:])
if isUnicodeSpace(r) || endsAutolink(r) {
break
}
end += n
}
return end
}
// endsAutolink reports whether r, beyond ASCII, ends an extended
// autolink: any space, line and paragraph separators included, and
// punctuation but dashes and connectors, which paths such as Wikipedia's
// use.
func endsAutolink(r rune) bool {
return unicode.IsSpace(r) || unicode.IsPunct(r) && !unicode.In(r, unicode.Pd, unicode.Pc)
}
func isUnicodeSpaceByte(c byte) bool {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'
}
// urlLink reads a link of http, https or ftp at the colon at pos, taking
// back the scheme from the text before it.
func (ip *inlineParser) urlLink() bool {
s := ip.s
pos := ip.pos
if ip.inBracket() || !strings.HasPrefix(s[pos:], "://") {
return false
}
// The scheme, from the text just added.
last := ip.nodes[0].last
if last < 0 {
return false
}
ln := &ip.nodes[last]
if ln.kind != Text || !ln.plain || ln.end != pos {
return false
}
rewind := 0
for rewind < len(ln.text) && isASCIILetter(ln.text[len(ln.text)-1-rewind]) {
rewind++
}
ip.d.steps += rewind
start := pos - rewind
scheme := strings.ToLower(s[start:pos])
if scheme != "http" && scheme != "https" && scheme != "ftp" {
return false
}
if len(s) <= pos+3 || !isHostChar(s[pos+3:]) {
return false
}
data := s[pos:]
n := checkDomain(data[3:], true)
if n == 0 {
return false
}
end := 3 + n
end = autolinkEnd(data, end)
ip.d.steps += end
end = autolinkDelim(data, end)
if end == 0 {
return false
}
// Take the scheme off the text.
ln.end = start
ln.text = s[ln.start:start]
ip.addAutolink(start, pos+end, s[start:pos+end])
ip.pos = pos + end
return true
}
func (ip *inlineParser) addAutolink(a, b int, dest string) {
l := ip.newNode(Link, "", a, b)
ip.nodes[l].dest = dest
ip.nodes[l].auto = true
ip.appendChild(0, l)
t := ip.newNode(Text, ip.s[a:b], a, b)
ip.appendChild(l, t)
}
// emailLinks finds email addresses in the text below node n, outside
// links, after joining text that follows text.
func (ip *inlineParser) emailLinks(n int32, inLink bool) {
for c := ip.nodes[n].first; c >= 0; c = ip.nodes[c].next {
nd := &ip.nodes[c]
switch nd.kind {
case Link, Image:
continue
case Text:
if strings.IndexByte(ip.nodes[c].text, '@') >= 0 {
ip.splitEmails(c)
}
default:
ip.emailLinks(c, inLink)
}
}
}
// splitEmails turns the email addresses in text node c into links.
func (ip *inlineParser) splitEmails(c int32) {
for {
nd := &ip.nodes[c]
data := nd.text
a, b, mailto, ok := findEmail(data)
if !ok {
ip.d.steps += len(data)
return
}
ip.d.steps += b
source := ip.s[nd.start:min(nd.end, len(ip.s))]
off := func(i int) int { return nd.start + literalToSource(source, data, i) }
start, end := nd.start, nd.end
la, lb := off(a), off(b)
dest := data[a:b]
if mailto {
dest = "mailto:" + dest
}
l := ip.newNode(Link, "", la, lb)
ip.nodes[l].dest = dest
ip.nodes[l].auto = true
t := ip.newNode(Text, data[a:b], la, lb)
ip.appendChild(l, t)
post := ip.newNode(Text, data[b:], lb, end)
nd = &ip.nodes[c]
nd.text, nd.start, nd.end = data[:a], start, la
ip.insertAfter(c, l)
ip.insertAfter(l, post)
c = post
}
}
// findEmail finds the first email address in data, as cmark-gfm does:
// its bytes, and whether its link needs mailto: (not when written with
// mailto: or xmpp:).
func findEmail(data string) (a, b int, mailto, ok bool) {
offset := 0
for offset < len(data) {
at := strings.IndexByte(data[offset:], '@')
if at < 0 {
return
}
maxRewind := at
auto, xmpp := true, false
foundAt:
base := offset + maxRewind // the @
rewind := 0
for ; rewind < maxRewind; rewind++ {
ch := data[base-rewind-1]
if isASCIILetter(ch) || isASCIIDigit(ch) || strings.IndexByte(".+-_", ch) >= 0 {
continue
}
if ch == ':' {
if validProtocol("mailto:", data, base, rewind) {
auto = false
continue
}
if validProtocol("xmpp:", data, base, rewind) {
auto, xmpp = false, true
continue
}
}
break
}
if rewind == 0 {
offset += maxRewind + 1
continue
}
np := 0
linkEnd := 1
for ; linkEnd < len(data)-base; linkEnd++ {
ch := data[base+linkEnd]
switch {
case isASCIILetter(ch) || isASCIIDigit(ch):
case ch == '@':
offset += maxRewind + 1
maxRewind = linkEnd - 1
goto foundAt
case ch == '.' && linkEnd < len(data)-base-1 && (isASCIILetter(data[base+linkEnd+1]) || isASCIIDigit(data[base+linkEnd+1])):
np++
case ch == '/' && xmpp:
case ch != '-' && ch != '_':
goto ended
}
}
ended:
if last := data[base+linkEnd-1]; linkEnd < 2 || np == 0 || !isASCIILetter(last) && last != '.' {
offset += maxRewind + linkEnd
continue
}
linkEnd = autolinkDelim(data[base:], linkEnd)
if linkEnd == 0 {
offset += maxRewind + 1
continue
}
return base - rewind, base + linkEnd, auto, true
}
return
}
// validProtocol reports whether protocol ends rewind bytes before the @
// at base, after something other than a letter or a digit.
func validProtocol(protocol, data string, base, rewind int) bool {
end := base - rewind
start := end - len(protocol)
if start < 0 || data[start:end] != protocol {
return false
}
if start == 0 {
return true
}
c := data[start-1]
return !isASCIILetter(c) && !isASCIIDigit(c)
}
+89
View File
@@ -0,0 +1,89 @@
package parser
import (
"os"
"testing"
)
func llm(b *testing.B) string {
data, err := os.ReadFile("testdata/llm.md")
if err != nil {
b.Fatal(err)
}
return string(data)
}
// inlinesAll parses the inlines of every block, as showing them does.
func inlinesAll(d *Document) {
for i := range d.Len() {
d.Inlines(i)
}
}
// BenchmarkParse parses the 50 KB answer whole, inlines included.
func BenchmarkParse(b *testing.B) {
src := llm(b)
b.SetBytes(int64(len(src)))
b.ReportAllocs()
for b.Loop() {
inlinesAll(Parse(src))
}
}
// BenchmarkPathological parses the inputs of TestLinearTime, which
// counts the parser's steps; this times them.
func BenchmarkPathological(b *testing.B) {
srcs := make([]string, len(pathological))
for i, c := range pathological {
srcs[i] = c.src(5000)
}
b.ReportAllocs()
for b.Loop() {
for i, c := range pathological {
d := New(c.ext)
d.Set(srcs[i])
inlinesAll(d)
}
}
}
// benchStream streams the answer in chunks of n bytes, with healing, the
// inlines of the tail parsed after each, as a frame shows them; it
// reports the time per chunk.
func benchStream(b *testing.B, n int) {
src := llm(b)
b.ReportAllocs()
chunks := 0
for b.Loop() {
d := New(Default)
d.SetStreaming(true)
for i := 0; i < len(src); i += n {
d.Append(src[i:min(i+n, len(src))])
inlinesAll(d)
chunks++
}
}
b.ReportMetric(float64(b.Elapsed().Nanoseconds())/float64(chunks), "ns/chunk")
}
func BenchmarkStream4(b *testing.B) { benchStream(b, 4) }
func BenchmarkStream64(b *testing.B) { benchStream(b, 64) }
// BenchmarkEdit types a character in the middle of the answer and takes
// it back, as an editor's preview.
func BenchmarkEdit(b *testing.B) {
src := llm(b)
d := Parse(src)
inlinesAll(d)
mid := len(src) / 2
for mid < len(src) && src[mid] != ' ' {
mid++
}
b.ReportAllocs()
for b.Loop() {
d.Edit(mid, mid, "x")
inlinesAll(d)
d.Edit(mid, mid+1, "")
inlinesAll(d)
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,26 @@
package parser
import "testing"
// Emphasis closed by CJK punctuation and followed by CJK text, as
// Chinese writes it without spaces.
func TestCJKEmphasis(t *testing.T) {
for src, want := range map[string]string{
"**五种方式都能承载。**下面是判断": "<p><strong>五种方式都能承载。</strong>下面是判断</p>\n",
"**已有可靠内网:直接 HTTP。**接入成本最低。": "<p><strong>已有可靠内网:直接 HTTP。</strong>接入成本最低。</p>\n",
"针对你强调的**“简单”**,我会这样选": "<p>针对你强调的<strong>“简单”</strong>,我会这样选</p>\n",
"~~删除。~~保留": "<p><del>删除。</del>保留</p>\n",
"snake_case_name": "<p>snake_case_name</p>\n",
"a **b** c": "<p>a <strong>b</strong> c</p>\n",
// _ and a single ~ keep CommonMark's rule next to CJK text.
"中文__粗体。__后文": "<p>中文__粗体。__后文</p>\n",
"第1章~“附录”和“序”~第3章": "<p>第1章~“附录”和“序”~第3章</p>\n",
// Latin text with curly quotes reads as before.
"He said “*hello*” to me.": "<p>He said “<em>hello</em>” to me.</p>\n",
"**Alice**’s and **Bob**’s toys": "<p><strong>Alice</strong>’s and <strong>Bob</strong>’s toys</p>\n",
} {
if got := render(src, Default); got != want {
t.Errorf("%q: got %q, want %q", src, got, want)
}
}
}
+494
View File
@@ -0,0 +1,494 @@
package parser
import (
"iter"
"slices"
"strings"
"unsafe"
)
// Extensions are the syntax a Document reads beyond CommonMark.
type Extensions uint32
const (
// ExtTables are GitHub's tables, of cells between pipes.
ExtTables Extensions = 1 << iota
// ExtTaskLists are list items starting with [ ] or [x].
ExtTaskLists
// ExtStrikethrough is text between one or two tildes.
ExtStrikethrough
// ExtAutolinks are links without angle brackets: www.example.com,
// https://example.com and someone@example.com.
ExtAutolinks
// ExtFootnotes are references as [^1], defined by [^1]: lines.
ExtFootnotes
// ExtMath is TeX between $$ and $$, \[ and \], or \( and \), in blocks
// of their own or within text.
ExtMath
// ExtDollarMath is TeX between single dollar signs, as $x^2$, except
// where the dollars read as amounts of money: not after an opening
// dollar followed by a space or a digit, nor before a closing one
// following a space or followed by a digit. It needs ExtMath.
ExtDollarMath
// ExtAlerts are GitHub's alerts: a block quote at the top level whose
// first line is [!NOTE], [!TIP], [!IMPORTANT], [!WARNING] or
// [!CAUTION] alone, followed by its text (Block.Alert).
ExtAlerts
// ExtMentions are GitHub's mentions of people and teams, as @octocat
// and @github/docs, in text outside code and links (Mention).
ExtMentions
// ExtReferences are GitHub's references to issues and pull requests,
// as #123, GH-123 and octocat/hello#123, in text outside code and
// links (Reference).
ExtReferences
// GFM is GitHub Flavored Markdown, as its spec has it.
GFM = ExtTables | ExtTaskLists | ExtStrikethrough | ExtAutolinks
// Default is GitHub Flavored Markdown with footnotes and math, as
// language models write it, and the alerts, mentions and references
// of GitHub's comments. Mentions and references are text until a
// view resolves them.
Default = GFM | ExtFootnotes | ExtMath | ExtAlerts | ExtMentions | ExtReferences
)
// Kind is what a block is.
type Kind uint8
// Kinds of blocks.
const (
// Root holds the top-level blocks: block 0 of a document.
Root Kind = iota
Paragraph
// Heading has a Level from 1 to 6.
Heading
ThematicBreak
// CodeBlock is fenced or indented code, whose Info string names the
// language of a fence.
CodeBlock
// HTMLBlock is raw HTML, whose lines are its content.
HTMLBlock
// Quote is a block quote, holding blocks.
Quote
// List holds items, Ordered or not, Tight or not.
List
// Item is an item of a list, holding blocks, with a Task state.
Item
// Table holds rows, the first its Header, whose cells align as Align
// says.
Table
TableRow
// TableCell holds inline content.
TableCell
// FootnoteDefinition holds the blocks of a footnote, its Label the
// footnote's.
FootnoteDefinition
// MathBlock is display math, whose lines are its TeX.
MathBlock
)
var kindNames = [...]string{"root", "paragraph", "heading", "thematic break", "code block", "HTML block", "quote", "list", "item", "table", "table row", "table cell", "footnote definition", "math block"}
func (k Kind) String() string {
if int(k) < len(kindNames) {
return kindNames[k]
}
return "unknown"
}
// Task is the check box of a task list item.
type Task uint8
const (
NoTask Task = iota
Unchecked
Checked
)
// Align is how a table's column aligns its cells.
type Align uint8
const (
AlignNone Align = iota
AlignLeft
AlignCenter
AlignRight
)
// Alert is the kind of a GitHub alert.
type Alert uint8
const (
NoAlert Alert = iota
AlertNote
AlertTip
AlertImportant
AlertWarning
AlertCaution
)
var alertNames = [...]string{"", "Note", "Tip", "Important", "Warning", "Caution"}
// String returns the alert's title, as GitHub shows it: Note, Tip,
// Important, Warning or Caution.
func (a Alert) String() string {
if int(a) < len(alertNames) {
return alertNames[a]
}
return ""
}
// alertOf returns the alert a line marks, as [!NOTE], in any case and
// with spaces or tabs around it, or NoAlert.
func alertOf(line string) Alert {
line = strings.Trim(line, " \t")
if len(line) < 6 || line[0] != '[' || line[1] != '!' || line[len(line)-1] != ']' {
return NoAlert
}
name := line[2 : len(line)-1]
for a := AlertNote; a <= AlertCaution; a++ {
if strings.EqualFold(name, alertNames[a]) {
return a
}
}
return NoAlert
}
// Block is a block of a document: blocks are in document order, a block's
// children right after it, up to its Next.
type Block struct {
Kind Kind
// Parent is the index of the block holding it, -1 for the root.
Parent int
// Next is the index after the block and its descendants.
Next int
// Start and End are the offsets of the block's bytes in the source,
// from its first character to the end of its last line.
Start, End int
// Open reports that the block is still open at the end of the
// source, so that more text can continue it: a fence without its
// closing fence, or the paragraph being written.
Open bool
// Level is a heading's, from 1 to 6.
Level int
// Ordered, Number (an ordered list's first), Marker (*, - or + for
// a bullet list, . or ) after an ordered list's numbers) and Tight
// (no blank lines between its items and their blocks) describe a
// list.
Ordered bool
Number int
Marker byte
Tight bool
// Task is an item's check box.
Task Task
// Fenced tells a fenced code block from an indented one.
Fenced bool
// Header tells a table's header row.
Header bool
// Alert is the kind of a block quote that is a GitHub alert, its
// [!NOTE] line not in its text (ExtAlerts): a marker alone in its
// paragraph leaves a paragraph without lines (LineCount 0), which
// shows nothing.
Alert Alert
// Align is the alignment of a table's columns.
Align []Align
// info is a fenced code block's info string or a footnote's label.
info string
// What the parser and the inline parser keep.
parse blockState
// segA and segB are the block's content lines in the document's
// segs, and segMark how many lines it held as the block began.
segA, segB, segMark int32
text string
textS int32 // the source offset of text[0] when text is a slice of the source, else -1
inl []Inline
inlOK bool
// labels are those its inlines looked up as references, to parse
// them anew when a definition of one comes or goes.
labels []string
rev uint32
// healed tells inlines parsed completed, as the end of a streaming
// document's.
healed bool
}
// seg is a line of a leaf block's content: pad spaces (from a tab partly
// consumed by indentation), the source's bytes [start, end), and a
// newline unless cell.
type seg struct {
start, end int32
pad int8
cell bool // a table cell: no newline, and \| is |
}
// Info returns a fenced code block's info string, unescaped, its
// language first (see Language).
func (b *Block) Info() string {
if b.Kind != CodeBlock {
return ""
}
return b.info
}
// Label returns a footnote definition's label.
func (b *Block) Label() string {
if b.Kind != FootnoteDefinition {
return ""
}
return b.info
}
// Language returns the language of a fenced code block, the first word
// of its info string.
func (b *Block) Language() string {
s := b.Info()
if i := strings.IndexAny(s, " \t"); i >= 0 {
s = s[:i]
}
return s
}
// Revision changes when the block's inlines are parsed anew, as when a
// link reference defined later in the document resolves its links: views
// keep what they made of a block while it stays the same.
func (b *Block) Revision() uint32 { return b.rev }
// Healed reports whether the block's inlines were completed as the tail
// of a streaming document: their closers are not in the source, and
// change as it grows.
func (b *Block) Healed() bool { return b.healed }
// Document is Markdown parsed, which takes text appended to it, or edits,
// and parses only what they change.
type Document struct {
src string
// buf holds the source as text is appended: its bytes before the
// source's length never change, so that the source is a string over
// them, and appending copies only the text appended.
buf []byte
ext Extensions
blocks []Block
segs []seg
refs map[string]linkRef
// defs are the link reference definitions in order, duplicates
// included, which take over as edits remove those before them.
defs []definition
notes map[string]int // footnote label → definition block
// restart is the offset of the line where parsing restarts as text
// is appended: the start of the outermost block open after the last
// complete line, or that line's end; restartAt is the index of the
// first block parsed from there.
restart int
restartAt int
// streaming completes unclosed syntax at the end of the source (see
// SetStreaming), and tail is the block holding the end.
streaming bool
tail int
// cut is where the source parsed for display ends: text held back
// while streaming lies past it.
cut int
// oldInl keeps the inlines of blocks parsed again as text is
// appended, to reuse.
oldInl []oldInline
// healedAt is the block whose inlines were parsed healed, or -1.
healedAt int
// revs counts the inlines parsed, to give each a Revision of its own.
revs uint32
inp inlineParser
// steps counts the work parsing does beyond reading the source once:
// the bytes scanned ahead or back, and the delimiters, brackets, nodes
// and lines walked, as the loops that could take quadratic time do it.
// Tests check that it grows linearly with the source.
steps int
// marks is the buffer of the last sourceMap.
marks []int
}
type oldInline struct {
at int // the offset of the block's content
rev uint32
text string
segs []seg // its lines, as offsets move with them
inl []Inline
labels []string
healed bool
}
// definition is a link reference definition of a label.
type definition struct {
key string
linkRef
}
// define adds a definition, which defines its label unless one before
// it did.
func (d *Document) define(df definition) {
d.defs = append(d.defs, df)
if _, ok := d.refs[df.key]; !ok {
d.refs[df.key] = df.linkRef
}
}
// linkRef is a link reference definition.
type linkRef struct {
dest, title string
at int // the offset of the definition
}
// Parse parses src with the Default extensions.
func Parse(src string) *Document {
d := New(Default)
d.Set(src)
return d
}
// New returns an empty document reading ext.
func New(ext Extensions) *Document {
d := &Document{ext: ext, healedAt: -1}
d.inp.d = d
d.reset()
return d
}
func (d *Document) reset() {
d.blocks = append(d.blocks[:0], Block{Kind: Root, Parent: -1, Next: 1, textS: -1})
d.segs = d.segs[:0]
d.blocks[0].parse.open = true
d.blocks[0].parse.lastChild = -1
d.refs = map[string]linkRef{}
d.defs = d.defs[:0]
d.notes = map[string]int{}
d.restart, d.restartAt = 0, 1
}
// Source returns the text of the document.
func (d *Document) Source() string { return d.src }
// Footnote returns the FootnoteDefinition block of a label, as a
// FootnoteRef's Text holds it.
func (d *Document) Footnote(label string) (int, bool) {
i, ok := d.notes[normalizeLabel(label)]
return i, ok
}
// Extensions returns what the document reads beyond CommonMark.
func (d *Document) Extensions() Extensions { return d.ext }
// Len returns the number of blocks, the root's included.
func (d *Document) Len() int { return len(d.blocks) }
// Block returns block i, 0 being the root. The block stays valid until
// the document changes.
func (d *Document) Block(i int) *Block { return &d.blocks[i] }
// Children returns the indices of the children of block i.
func (d *Document) Children(i int) iter.Seq[int] {
return func(yield func(int) bool) {
end := d.blocks[i].Next
for j := i + 1; j < end; j = d.blocks[j].Next {
if !yield(j) {
return
}
}
}
}
// Streaming reports whether the document completes unclosed syntax at
// its end (see SetStreaming).
func (d *Document) Streaming() bool { return d.streaming }
// SetStreaming sets whether the document is text still being written, as
// a language model's reply: its end then shows what it will most likely
// become rather than the half-written syntax it is. The last paragraph
// closes its emphasis, code spans, strikethrough and math (a single $'s
// too, with ExtDollarMath), within which _ and * open no emphasis; a
// link whose destination is being written is a link (Inline.Pending), a
// tag being written is left out, and lines that could still turn into
// something else are held back: a line of only a few markers, as - or
// ==, which would make the paragraph above a heading, and a table's
// header until its delimiter row comes. Finished blocks are never
// changed. Turn it off once the text is complete, to parse its end
// exactly as CommonMark does.
func (d *Document) SetStreaming(on bool) {
if d.streaming == on {
return
}
d.streaming = on
d.parseTail()
}
// Set makes src the text of the document, parsing only what changed
// since the last: text appended to it, or else the blocks around the
// change (see Edit).
func (d *Document) Set(src string) {
old := d.src
switch {
case src == old:
return
case len(src) > len(old) && src[:len(old)] == old:
// The new source is the string given, copied nowhere.
d.reserve(src[len(old):])
d.src = src
d.parseTail()
return
}
// The common prefix and suffix bound the change.
p := 0
for p < len(old) && p < len(src) && old[p] == src[p] {
p++
}
s := 0
for s < len(old)-p && s < len(src)-p && old[len(old)-1-s] == src[len(src)-1-s] {
s++
}
d.Edit(p, len(old)-s, src[p:len(src)-s])
}
// Append adds text to the end of the document, parsing again only the
// outermost block still open before it, or nothing but the new lines
// when no block is.
func (d *Document) Append(text string) {
if text == "" {
return
}
d.reserve(text)
if len(d.buf) != len(d.src) || len(d.src) > 0 && unsafe.StringData(d.src) != unsafe.SliceData(d.buf) {
d.buf = append(make([]byte, 0, max(2*len(d.src)+len(text), 512)), d.src...)
}
if cap(d.buf)-len(d.buf) < len(text) {
d.buf = append(make([]byte, 0, 2*cap(d.buf)+len(text)), d.buf...)
}
d.buf = append(d.buf, text...)
d.src = unsafe.String(unsafe.SliceData(d.buf), len(d.buf))
d.parseTail()
}
// reserve makes room for the blocks of text, a large part of a document
// parsed at once.
func (d *Document) reserve(text string) {
if len(text) < 4096 {
return
}
n := strings.Count(text, "\n")
d.blocks = slices.Grow(d.blocks, n+n/4+8)
}
// Edit replaces the source's bytes [from, to) with text. Parsing restarts
// at the top-level block before the change and goes on until a top-level
// block starts where one started before it, from which the blocks parsed
// before are kept.
func (d *Document) Edit(from, to int, text string) {
if from == to && text == "" {
return
}
if from == len(d.src) && to == from {
d.Append(text)
return
}
d.edit(from, to, text)
}
// String returns the source of the document.
func (d *Document) String() string { return d.src }
+127
View File
@@ -0,0 +1,127 @@
package parser
import (
"fmt"
"runtime"
"strings"
"testing"
)
// TestEditKeepsTailInlines checks that incremental edits that resync a
// later block keep the inlines and offsets a parse of the whole source
// gives, including when a reference definition comes or goes.
func TestEditKeepsTailInlines(t *testing.T) {
src := "first [docs] **bold**\n\n" +
"[docs]: /one\n\n" +
"# middle\n\n" +
"tail [docs] *emphasis*\n\n" +
"last line\n"
const tail = "tail [docs] *emphasis*"
for _, c := range []struct {
name, from, text string
length int
preserve bool
}{
{"insert", "middle", "X", 0, true},
{"replace", "middle", "middles", len("middle"), true},
{"delete", "m", "", 1, true},
{"same length", "middle", "Middle", len("middle"), true},
{"add definition", "last line", "[docs]: /two\n\nlast line", len("last line"), false},
{"change definition", "/one", "/changed", len("/one"), false},
} {
t.Run(c.name, func(t *testing.T) {
from := strings.Index(src, c.from)
if from < 0 {
t.Fatalf("%q is not in the source", c.from)
}
to := from + c.length
next := src[:from] + c.text + src[to:]
d := New(Default)
d.Set(src)
inlinesAll(d)
rev := uint32(0)
if c.preserve {
rev = d.Block(blockWithText(d, tail)).Revision()
}
d.Edit(from, to, c.text)
if d.Source() != next {
t.Fatalf("source = %q, want %q", d.Source(), next)
}
fresh := Parse(next)
if c.preserve {
if got := d.Block(blockWithText(d, tail)).Revision(); got != rev {
t.Errorf("resynced tail was parsed again: revision %d, want %d", got, rev)
}
}
got, want := dumpEditedDocument(d), dumpEditedDocument(fresh)
if got != want {
t.Errorf("edited document:\n%s\nwhole parse:\n%s", got, want)
}
})
}
}
func blockWithText(d *Document, text string) int {
for i := range d.Children(0) {
if d.LineCount(i) > 0 {
line, _ := d.Line(i, 0)
if line == text {
return i
}
}
}
return -1
}
// TestEditWorkScalesWithTail checks that editing near the end does not
// copy all the segments and inlines of the document before the edit.
func TestEditWorkScalesWithTail(t *testing.T) {
editBytes := func(src string) uint64 {
var before, after runtime.MemStats
d := New(Default)
d.Set(src)
inlinesAll(d)
at := strings.Index(src, "two")
runtime.ReadMemStats(&before)
d.Edit(at, at, "x")
inlinesAll(d)
runtime.ReadMemStats(&after)
return after.TotalAlloc - before.TotalAlloc
}
many, few := editSources(2000)
if len(many) != len(few) {
t.Fatalf("sources differ in length: %d and %d", len(many), len(few))
}
withManySegs, withFewSegs := editBytes(many), editBytes(few)
if withManySegs > withFewSegs*2 {
t.Errorf("prefix of many segments: %d B, of few segments: %d B", withManySegs, withFewSegs)
}
}
// editSources gives two sources of the same length: the first has many
// segments before the edit, the second has one long line instead.
func editSources(n int) (string, string) {
tail := "one\n\ntwo\n\ntail [docs]\n\n[docs]: /u\n"
return strings.Repeat("a\n", n) + "\n" + tail,
strings.Repeat("a", 2*n-1) + "\n\n" + tail
}
func dumpEditedDocument(d *Document) string {
var out strings.Builder
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
fmt.Fprintf(&out, "%d %v [%d,%d) parent %d next %d\n", i, b.Kind, b.Start, b.End, b.Parent, b.Next)
for k := 0; k < d.LineCount(i); k++ {
line, at := d.Line(i, k)
if got := d.Source()[at : at+len(line)]; got != line {
fmt.Fprintf(&out, " line %d %q at %d is %q\n", k, line, at, got)
} else {
fmt.Fprintf(&out, " line %d %q at %d\n", k, line, at)
}
}
for _, in := range d.Inlines(i) {
fmt.Fprintf(&out, " %v %q %q [%d,%d) next %d\n", in.Kind, in.Text, in.Dest, in.Start, in.End, in.Next)
}
}
return out.String()
}
+207
View File
@@ -0,0 +1,207 @@
package parser
import (
"slices"
"strings"
)
// Healing completes what the end of a streaming document leaves open in
// the inline content of its last block, as Vercel's remend does to the
// text, but from the parser's own delimiters, and only for that block:
// the source never changes. It returns the text to parse and the length
// of what came from the source, past which the text was added.
// heal returns s completed, and whether the tree the parser holds is
// already that of the text returned.
func (ip *inlineParser) heal(s string) (string, int, bool) {
s = trimTrailingMarkers(s)
from := len(s)
// A link whose destination is being written: [text](http…
s += pendingLink(s)
// A code span not closed.
if ticks := openCodeSpan(s); ticks > 0 {
run := 0
for run < len(s) && s[len(s)-1-run] == '`' {
run++
}
if run >= ticks || run == 0 {
run = 0
}
s += strings.Repeat("`", ticks-run)
}
// The closing tildes of strikethrough half written: ~~struck~.
if strings.HasSuffix(s, "~") && !strings.HasSuffix(s, "~~") && strings.Contains(s, "~~") {
s += "~"
}
// Emphasis, strikethrough and math not closed: the openers the parser
// leaves, innermost first; and the text of a link being written shows
// without its bracket.
ip.run(s)
type opener struct {
at int
closer string
}
var open []opener
// Math not closed, by $$ or a single $ (ExtDollarMath), runs to the
// end: what follows is TeX, whose _ and * open no emphasis.
math, closer := len(s), ""
if ip.ext&ExtMath != 0 && ip.openMath >= 0 {
math, closer = ip.openMath, "$$"
}
if ip.ext&ExtDollarMath != 0 && ip.openDollar >= 0 && ip.openDollar < math {
math, closer = ip.openDollar, "$"
}
if closer != "" {
open = append(open, opener{math, closer})
}
for _, d := range ip.leftover {
if d.c == '*' && wordInside(s, d.at, d.orig) || d.c == '~' && d.orig == 1 || d.at > math {
continue // 2*3, a tilde for "about", as ~200, or TeX
}
open = append(open, opener{d.at, strings.Repeat(string(d.c), d.n)})
}
if ip.lastB >= 0 && ip.nodes[ip.br[ip.lastB].node].start < math {
ip.hide = ip.nodes[ip.br[ip.lastB].node].start
}
if len(open) == 0 && ip.hide < 0 {
return s, from, true
}
slices.SortStableFunc(open, func(a, b opener) int { return b.at - a.at })
var b strings.Builder
b.WriteString(s)
for _, o := range open {
b.WriteString(o.closer)
}
return b.String(), from, false
}
// wordInside reports whether a run of n delimiters at i has letters or
// digits of ASCII on both sides, as 2*3, which is not emphasis being
// written.
func wordInside(s string, i, n int) bool {
if i == 0 || i+n >= len(s) {
return false
}
isWord := func(c byte) bool { return isASCIILetter(c) || isASCIIDigit(c) }
return isWord(s[i-1]) && isWord(s[i+n])
}
// trimTrailingMarkers drops what the end of s may be starting, with
// nothing after it yet: a run of delimiters opening emphasis, a code span
// or math, a bracket, or a backslash.
func trimTrailingMarkers(s string) string {
for {
t := strings.TrimRight(s, " \t")
if t == "" {
return t
}
c := t[len(t)-1]
k := len(t)
for k > 0 && t[k-1] == c {
k--
}
run := len(t) - k
opening := k == 0 || t[k-1] == ' ' || t[k-1] == '\t' || t[k-1] == '\n'
switch {
case strings.HasSuffix(t, "!["):
t = t[:len(t)-2]
case c == '[':
t = t[:k]
case (c == '*' || c == '_' || c == '~' || c == '$') && opening:
t = t[:k]
case c == '`' && !closesSpan(t[:k], run):
t = t[:k]
case c == '\\' && run%2 == 1:
t = t[:len(t)-1]
default:
return t
}
s = t
}
}
// closesSpan reports whether a run of n backticks after s closes a code
// span s opens.
func closesSpan(s string, n int) bool { return openCodeSpan(s) == n }
// pendingLink returns what closes the destination of a link being
// written at the end of s, after ](, or nothing: the parentheses it
// opened, and the link's, or > and ) for one in angle brackets.
func pendingLink(s string) string {
k := strings.LastIndex(s, "](")
if k < 0 || !strings.Contains(s[:k], "[") {
return ""
}
// Not inside a code span.
if strings.Count(s[:k], "`")%2 == 1 {
return ""
}
rest := s[k+2:]
if strings.HasPrefix(rest, "<") {
if strings.ContainsAny(rest, ">\n") {
return ""
}
return ">)"
}
depth := 0
for i := 0; i < len(rest); i++ {
switch rest[i] {
case '\\':
i++
case '(':
depth++
case ')':
if depth == 0 {
return "" // the link is closed
}
depth--
case ' ', '\t', '\n':
return ""
}
}
return strings.Repeat(")", depth+1)
}
// openCodeSpan returns the length of the run of backticks opening a code
// span that s leaves open, or 0.
func openCodeSpan(s string) int {
for i := 0; i < len(s); i++ {
switch s[i] {
case '\\':
i++
case '`':
j := i
for j < len(s) && s[j] == '`' {
j++
}
n := j - i
// Its closer: the next run of as many.
k := j
found := false
for k < len(s) {
m := strings.IndexByte(s[k:], '`')
if m < 0 {
break
}
k += m
e := k
for e < len(s) && s[e] == '`' {
e++
}
if e-k == n {
found = true
i = e - 1
break
}
k = e
}
if !found {
if j == len(s) {
return 0 // a run at the very end opens nothing yet
}
return n
}
}
}
return 0
}
+117
View File
@@ -0,0 +1,117 @@
package parser
import "testing"
func streamed(src string) string {
d := New(Default)
d.SetStreaming(true)
d.Set(src)
return d.HTML()
}
func TestHealing(t *testing.T) {
for _, c := range []struct{ src, want string }{
{"Some **bol", "<p>Some <strong>bol</strong></p>\n"},
{"Some **bold** and *ita", "<p>Some <strong>bold</strong> and <em>ita</em></p>\n"},
{"**a *b", "<p><strong>a <em>b</em></strong></p>\n"},
{"a ~~gone", "<p>a <del>gone</del></p>\n"},
{"run `go te", "<p>run <code>go te</code></p>\n"},
{"run ``a`", "<p>run <code>a</code></p>\n"},
{"hello **", "<p>hello</p>\n"},
{"hello *", "<p>hello</p>\n"},
{"hello `", "<p>hello</p>\n"},
{"2*3 is", "<p>2*3 is</p>\n"},
{"snake_case_name", "<p>snake_case_name</p>\n"},
{"see [the docs](https://exa", `<p>see <a href="https://exa">the docs</a></p>` + "\n"},
{"see [the docs](", `<p>see <a href="">the docs</a></p>` + "\n"},
{"math $$x^2", `<p>math <span class="math display">x^2</span></p>` + "\n"},
{"A paragraph\n-", "<p>A paragraph</p>\n"},
{"A paragraph\n==", "<p>A paragraph</p>\n"},
{"A paragraph\n---\n", "<h2>A paragraph</h2>\n"},
{"Intro\n\n| a | b |\n", "<p>Intro</p>\n"},
{"Intro\n\n| a | b |\n|--", "<p>Intro</p>\n"},
{"| a | b |\n|---|---|\n| 1 | 2", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>2</td>\n</tr>\n</tbody>\n</table>\n"},
{"| a | b |\n|---|---|\n| 1 | **2", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td><strong>2</strong></td>\n</tr>\n</tbody>\n</table>\n"},
{"```go\nfunc main() {", "<pre><code class=\"language-go\">func main() {\n</code></pre>\n"},
{"caf\xc3", "<p>caf</p>\n"},
{"Done **bold**\n\nnext", "<p>Done <strong>bold</strong></p>\n<p>next</p>\n"},
} {
if got := streamed(c.src); got != c.want {
t.Errorf("%q:\ngot %q\nwant %q", c.src, got, c.want)
}
}
}
// TestHealingOnlyTail checks that blocks already finished show as
// written.
func TestHealingOnlyTail(t *testing.T) {
got := streamed("a **b\n\nc **d")
want := "<p>a **b</p>\n<p>c <strong>d</strong></p>\n"
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestPendingLink(t *testing.T) {
d := New(Default)
d.SetStreaming(true)
d.Set("see [docs](https://exa")
in := d.Inlines(1)
if len(in) < 2 || in[1].Kind != Link || !in[1].Pending {
t.Fatalf("inlines %+v", in)
}
d.Append("mple.com) now")
in = d.Inlines(1)
if in[1].Kind != Link || in[1].Pending || in[1].Dest != "https://example.com" {
t.Fatalf("inlines %+v", in)
}
}
// TestHealingDollarMath heals math a single dollar opens (ExtDollarMath)
// as it streams, whose _ and * are TeX rather than emphasis, while money,
// escaped dollars and finished text read as before.
func TestHealingDollarMath(t *testing.T) {
for _, c := range []struct{ src, want string }{
{"where $x_i", `<p>where <span class="math inline">x_i</span></p>` + "\n"},
{"where $a*b", `<p>where <span class="math inline">a*b</span></p>` + "\n"},
{"where $x_i^2 + y_", `<p>where <span class="math inline">x_i^2 + y_</span></p>` + "\n"},
{"where $\\frac{a}{b", `<p>where <span class="math inline">\frac{a}{b</span></p>` + "\n"},
{"where $x \\", `<p>where <span class="math inline">x</span></p>` + "\n"},
{"where $x $", `<p>where <span class="math inline">x</span></p>` + "\n"},
{"*see $x_i", `<p><em>see <span class="math inline">x_i</span></em></p>` + "\n"},
{"**see $a_b", `<p><strong>see <span class="math inline">a_b</span></strong></p>` + "\n"},
{"$a$ and $b_", `<p><span class="math inline">a</span> and <span class="math inline">b_</span></p>` + "\n"},
{"see [link $x", `<p>see link <span class="math inline">x</span></p>` + "\n"},
{"math $$x^2", `<p>math <span class="math display">x^2</span></p>` + "\n"},
{"math $$x_i *y", `<p>math <span class="math display">x_i *y</span></p>` + "\n"},
// Money and escapes open no math.
{"costs $5 and *more", "<p>costs $5 and <em>more</em></p>\n"},
{"costs $ 5 and _more", "<p>costs $ 5 and <em>more</em></p>\n"},
{"costs \\$x and *more", "<p>costs $x and <em>more</em></p>\n"},
{"costs $", "<p>costs</p>\n"},
{"costs 5$", "<p>costs 5$</p>\n"},
} {
d := New(Default | ExtDollarMath)
d.SetStreaming(true)
d.Set(c.src)
if got := d.HTML(); got != c.want {
t.Errorf("%q:\ngot %q\nwant %q", c.src, got, c.want)
}
}
// Without ExtDollarMath, a dollar is text.
if got := streamed("where $x_i *y"); got != "<p>where $x_i <em>y</em></p>\n" {
t.Errorf("without ExtDollarMath: %q", got)
}
// Finished, unclosed math is text, as before.
for _, c := range []struct{ src, want string }{
{"where $x_i", "<p>where $x_i</p>\n"},
{"where $a *b*", "<p>where $a <em>b</em></p>\n"},
{"costs $5 and $x$", `<p>costs $5 and <span class="math inline">x</span></p>` + "\n"},
} {
d := New(Default | ExtDollarMath)
d.Set(c.src)
if got := d.HTML(); got != c.want {
t.Errorf("finished %q:\ngot %q\nwant %q", c.src, got, c.want)
}
}
}
+404
View File
@@ -0,0 +1,404 @@
package parser
import (
"strconv"
"strings"
)
// HTML returns the document as HTML, as cmark-gfm renders it, raw HTML
// included as written.
func (d *Document) HTML() string {
var w htmlWriter
w.d = d
w.blocks(0)
w.footnotes()
return w.b.String()
}
type htmlWriter struct {
d *Document
b strings.Builder
notes []string // footnote labels in the order of their first reference
}
func (w *htmlWriter) cr() {
if s := w.b.Len(); s > 0 {
str := w.b.String()
if str[s-1] != '\n' {
w.b.WriteByte('\n')
}
}
}
func (w *htmlWriter) blocks(parent int) {
for i := range w.d.Children(parent) {
if b := w.d.Block(i); b.Kind == Paragraph && b.segB == b.segA {
continue // an alert's marker
}
w.block(i)
}
}
func (w *htmlWriter) tight(i int) bool {
b := w.d.Block(i)
if b.Parent <= 0 {
return false
}
p := w.d.Block(b.Parent)
if p.Kind != Item || p.Parent < 0 {
return false
}
return w.d.Block(p.Parent).Tight
}
func (w *htmlWriter) block(i int) {
d := w.d
b := d.Block(i)
switch b.Kind {
case Paragraph:
if w.tight(i) {
w.inlines(i)
return
}
w.cr()
w.b.WriteString("<p>")
w.inlines(i)
w.b.WriteString("</p>\n")
case Heading:
w.cr()
tag := "h" + strconv.Itoa(b.Level)
w.b.WriteString("<" + tag + ">")
w.inlines(i)
w.b.WriteString("</" + tag + ">\n")
case ThematicBreak:
w.cr()
w.b.WriteString("<hr />\n")
case CodeBlock:
w.cr()
w.b.WriteString("<pre><code")
if lang := b.Language(); lang != "" {
w.b.WriteString(` class="language-`)
escapeHTML(&w.b, lang)
w.b.WriteString(`"`)
}
w.b.WriteString(">")
escapeHTML(&w.b, d.Lines(i))
w.b.WriteString("</code></pre>\n")
case HTMLBlock:
w.cr()
w.b.WriteString(d.Lines(i))
w.cr()
case MathBlock:
w.cr()
w.b.WriteString(`<div class="math display">`)
escapeHTML(&w.b, strings.TrimSuffix(d.Lines(i), "\n"))
w.b.WriteString("</div>\n")
case Quote:
w.cr()
if a := b.Alert; a != NoAlert {
// As GitHub writes alerts, without its icons.
name := strings.ToLower(a.String())
w.b.WriteString(`<div class="markdown-alert markdown-alert-` + name + `">` + "\n")
w.b.WriteString(`<p class="markdown-alert-title">` + a.String() + "</p>\n")
w.blocks(i)
w.cr()
w.b.WriteString("</div>\n")
break
}
w.b.WriteString("<blockquote>\n")
w.blocks(i)
w.cr()
w.b.WriteString("</blockquote>\n")
case List:
w.cr()
if b.Ordered {
if b.Number != 1 {
w.b.WriteString(`<ol start="` + strconv.Itoa(b.Number) + `">` + "\n")
} else {
w.b.WriteString("<ol>\n")
}
} else {
w.b.WriteString("<ul>\n")
}
w.blocks(i)
if b.Ordered {
w.b.WriteString("</ol>\n")
} else {
w.b.WriteString("</ul>\n")
}
case Item:
w.cr()
w.b.WriteString("<li>")
switch b.Task {
case Unchecked:
w.b.WriteString(`<input type="checkbox" disabled="" /> `)
case Checked:
w.b.WriteString(`<input type="checkbox" checked="" disabled="" /> `)
}
w.blocks(i)
w.b.WriteString("</li>\n")
case Table:
w.cr()
w.b.WriteString("<table>\n")
body := false
for r := range d.Children(i) {
row := d.Block(r)
if row.Header {
w.b.WriteString("<thead>\n")
} else if !body {
w.b.WriteString("<tbody>\n")
body = true
}
w.b.WriteString("<tr>\n")
k := 0
for c := range d.Children(r) {
tag := "td"
if row.Header {
tag = "th"
}
w.b.WriteString("<" + tag)
if k < len(b.Align) {
switch b.Align[k] {
case AlignLeft:
w.b.WriteString(` align="left"`)
case AlignCenter:
w.b.WriteString(` align="center"`)
case AlignRight:
w.b.WriteString(` align="right"`)
}
}
w.b.WriteString(">")
w.inlines(c)
w.b.WriteString("</" + tag + ">\n")
k++
}
w.b.WriteString("</tr>\n")
if row.Header {
w.b.WriteString("</thead>\n")
}
}
if body {
w.b.WriteString("</tbody>\n")
}
w.b.WriteString("</table>\n")
case FootnoteDefinition:
// Listed at the end, in the order of their references.
}
}
// Lines returns the content of a code, HTML or math block, each line
// ending with a newline.
func (d *Document) Lines(i int) string {
segs := d.segsOf(&d.blocks[i])
n := 0
for _, s := range segs {
n += int(s.pad) + int(s.end-s.start) + 1
}
var sb strings.Builder
sb.Grow(n)
for _, s := range segs {
for range s.pad {
sb.WriteByte(' ')
}
sb.WriteString(d.src[s.start:s.end])
sb.WriteByte('\n')
}
return sb.String()
}
// LineCount returns the number of lines of a code, HTML or math block.
func (d *Document) LineCount(i int) int { b := &d.blocks[i]; return int(b.segB - b.segA) }
// Line returns line k of a code, HTML or math block, without its newline,
// and the offset in the source of its first byte.
func (d *Document) Line(i, k int) (string, int) {
s := d.segs[int(d.blocks[i].segA)+k]
line := d.src[s.start:s.end]
if s.pad > 0 {
line = strings.Repeat(" ", int(s.pad)) + line
}
return line, int(s.start)
}
func (w *htmlWriter) inlines(i int) {
in := w.d.Inlines(i)
w.inline(in, 0, len(in))
}
func (w *htmlWriter) inline(in []Inline, from, to int) {
for k := from; k < to; k = in[k].Next {
n := &in[k]
switch n.Kind {
case Text, Mention, Reference:
// Mentions and references are links only where a host
// resolves them.
escapeHTML(&w.b, n.Text)
case SoftBreak:
w.b.WriteString("\n")
case LineBreak:
w.b.WriteString("<br />\n")
case Code:
w.b.WriteString("<code>")
escapeHTML(&w.b, n.Text)
w.b.WriteString("</code>")
case Emphasis:
w.b.WriteString("<em>")
w.inline(in, k+1, n.Next)
w.b.WriteString("</em>")
case Strong:
w.b.WriteString("<strong>")
w.inline(in, k+1, n.Next)
w.b.WriteString("</strong>")
case Strikethrough:
w.b.WriteString("<del>")
w.inline(in, k+1, n.Next)
w.b.WriteString("</del>")
case Link:
w.b.WriteString(`<a href="`)
escapeHref(&w.b, n.Dest)
w.b.WriteString(`"`)
if n.Title != "" {
w.b.WriteString(` title="`)
escapeHTML(&w.b, n.Title)
w.b.WriteString(`"`)
}
w.b.WriteString(">")
w.inline(in, k+1, n.Next)
w.b.WriteString("</a>")
case Image:
w.b.WriteString(`<img src="`)
escapeHref(&w.b, n.Dest)
w.b.WriteString(`" alt="`)
escapeHTML(&w.b, PlainText(in[k+1:n.Next]))
w.b.WriteString(`"`)
if n.Title != "" {
w.b.WriteString(` title="`)
escapeHTML(&w.b, n.Title)
w.b.WriteString(`"`)
}
w.b.WriteString(" />")
case HTML:
w.b.WriteString(n.Text)
case Math:
if n.Display {
w.b.WriteString(`<span class="math display">`)
} else {
w.b.WriteString(`<span class="math inline">`)
}
escapeHTML(&w.b, n.Text)
w.b.WriteString("</span>")
case FootnoteRef:
num := w.note(n.Text)
id := strconv.Itoa(num)
w.b.WriteString(`<sup class="footnote-ref"><a href="#fn-` + id + `" id="fnref-` + id + `" data-footnote-ref>` + id + `</a></sup>`)
}
}
}
// note returns the number of footnote label, numbering it at its first
// reference.
func (w *htmlWriter) note(label string) int {
key := normalizeLabel(label)
for i, l := range w.notes {
if l == key {
return i + 1
}
}
w.notes = append(w.notes, key)
return len(w.notes)
}
func (w *htmlWriter) footnotes() {
if len(w.notes) == 0 {
return
}
w.cr()
w.b.WriteString("<section class=\"footnotes\" data-footnotes>\n<ol>\n")
for k := 0; k < len(w.notes); k++ {
i := w.d.notes[w.notes[k]]
id := strconv.Itoa(k + 1)
w.b.WriteString(`<li id="fn-` + id + `">` + "\n")
w.blocks(i)
w.cr()
w.b.WriteString(`<a href="#fnref-` + id + `" class="footnote-backref">↩</a>` + "\n</li>\n")
}
w.b.WriteString("</ol>\n</section>\n")
}
// PlainText returns the text of inlines without their markup: the text
// of links and emphasis, code as its text, line breaks as spaces.
func PlainText(in []Inline) string {
var b strings.Builder
for k := range in {
switch n := &in[k]; n.Kind {
case Text, Code, HTML, Math, Mention, Reference:
b.WriteString(n.Text)
case SoftBreak, LineBreak:
b.WriteByte(' ')
case FootnoteRef:
b.WriteString("[^" + n.Text + "]")
}
}
return b.String()
}
func escapeHTML(b *strings.Builder, s string) {
last := 0
for i := 0; i < len(s); i++ {
var r string
switch s[i] {
case '&':
r = "&amp;"
case '<':
r = "&lt;"
case '>':
r = "&gt;"
case '"':
r = "&quot;"
case 0:
r = "�"
default:
continue
}
b.WriteString(s[last:i])
b.WriteString(r)
last = i + 1
}
b.WriteString(s[last:])
}
// hrefSafe are the bytes a URL keeps as they are, as cmark's houdini.
var hrefSafe = func() (t [256]bool) {
for c := 'a'; c <= 'z'; c++ {
t[c] = true
}
for c := 'A'; c <= 'Z'; c++ {
t[c] = true
}
for c := '0'; c <= '9'; c++ {
t[c] = true
}
for _, c := range "-_.+!*(),%#@?=;:/,+$~" {
t[c] = true
}
return
}()
func escapeHref(b *strings.Builder, s string) {
const hex = "0123456789ABCDEF"
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case hrefSafe[c]:
b.WriteByte(c)
case c == '&':
b.WriteString("&amp;")
case c == '\'':
b.WriteString("&#x27;")
default:
b.WriteByte('%')
b.WriteByte(hex[c>>4])
b.WriteByte(hex[c&15])
}
}
}
File diff suppressed because it is too large. Load diff
+116
View File
@@ -0,0 +1,116 @@
package parser
import (
"runtime"
"strings"
"testing"
)
// pathological are inputs that take quadratic time in parsers without
// cmark's guards, or took it in this one, made of n repeats.
var pathological = []struct {
name string
ext Extensions
src func(n int) string
}{
{"mismatched openers", Default, repeat("*a_ ")},
{"emphasis openers", Default, repeat("*a ")},
{"many emphasis", Default, repeat("**a** ")},
{"underscores", Default, func(n int) string { return strings.Repeat("_a ", n) + strings.Repeat("a_ ", n) }},
{"strikethrough openers", Default, repeat("~~a ")},
{"unclosed links", Default, repeat("[a](<b")},
{"unclosed titles", Default, repeat(`[a](b "`)},
{"brackets", Default, repeat("[")},
{"unclosed brackets", Default, func(n int) string { return strings.Repeat("[", n) + "a" + strings.Repeat("]", n) }},
{"image brackets", Default, func(n int) string { return strings.Repeat("![", n) + strings.Repeat("]", n) }},
{"backticks", Default, repeat("`a``")},
{"backtick runs", Default, backtickRuns},
{"escapes", Default, repeat(`\*`)},
{"unclosed comments", Default, func(n int) string { return "a " + strings.Repeat("<!--", n) }},
{"math spans", Default, func(n int) string { return "a " + strings.Repeat("$$a ", n) }},
{"emails", Default, repeat("a@b.")},
{"urls", Default, repeat("x://")},
{"nested quotes", Default, func(n int) string { return strings.Repeat(">", n) + " a" }},
{"nested lists", Default, func(n int) string { return strings.Repeat("* ", n) + "a" }},
{"link definitions", Default, repeat("[a]: u\n")},
{"tables", Default, func(n int) string { return "| a |\n|---|\n" + strings.Repeat("|\n", n) }},
{"pipes", Default, func(n int) string { return strings.Repeat("| ", n) + "\n|" + strings.Repeat("-|", n) }},
{"lines ending in CR", Default, repeat("a\r")},
{"indented lines", Default, repeat("a\n ")},
{"quoted lines", Default, repeat("> a\n")},
{"openers then links", Default, func(n int) string { return strings.Repeat("[", n) + strings.Repeat("[a](b)", n) }},
{"escaped pipes", Default, func(n int) string { return "| a |\n|---|\n| " + strings.Repeat(`\| *a* `, n) + "|" }},
{"mentions", Default, repeat("@a ")},
{"repository references", Default, repeat("aaaaaaaa/bbbbbbbb#")},
{"words before references", Default, repeat("a#")},
{"alerts", Default, repeat("> [!NOTE]\n")},
}
func repeat(unit string) func(int) string {
return func(n int) string { return strings.Repeat(unit, n) }
}
// backtickRuns returns runs of backticks of every length up to n/40,
// none closed, as cmark's pathological tests.
func backtickRuns(n int) string {
var b strings.Builder
for k := 1; k <= n/40; k++ {
b.WriteString("e")
b.WriteString(strings.Repeat("`", k))
}
return b.String()
}
// work parses src, and the inlines of every block with inlines, and
// returns the steps it took (Document.steps) and the bytes it allocated,
// which grow quadratically where text is copied over and over, as steps
// do not show.
func work(src string, ext Extensions, inlines bool) (steps, bytes int) {
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
d := New(ext)
d.Set(src)
if inlines {
inlinesAll(d)
}
runtime.ReadMemStats(&after)
return d.steps, int(after.TotalAlloc - before.TotalAlloc)
}
// checkLinear checks that parsing src(n), inlines included, takes work
// that grows linearly with the input: about the same a byte for src(4n)
// as for src(n), where a quadratic parser takes four times as much, and
// a few steps a byte. It counts what the parser does rather than timing
// it, so that a quadratic regression fails on every machine and a busy
// machine never fails.
func checkLinear(t *testing.T, name string, ext Extensions, src func(n int) string) {
t.Helper()
checkLinearWork(t, name, ext, true, src)
}
// checkLinearWork is checkLinear, the inlines parsed with inlines.
func checkLinearWork(t *testing.T, name string, ext Extensions, inlines bool, src func(n int) string) {
t.Helper()
// The steps of linear inputs are an affine function of the input's
// length, under 5 a byte; allocations grow less evenly, as slices
// double.
const n, stepsPerByte = 5000, 8
small, large := src(n), src(4*n)
sa, ba := work(small, ext, inlines)
sb, bb := work(large, ext, inlines)
perByte := func(w int, src string) float64 { return float64(w) / float64(len(src)) }
if perByte(sb, large) > 1.25*perByte(sa, small) || sb > stepsPerByte*len(large) {
t.Errorf("%s: %d steps for %d bytes, %d for %d", name, sa, len(small), sb, len(large))
}
if perByte(bb, large) > 1.5*perByte(ba, small)+16 {
t.Errorf("%s: %d bytes allocated for %d bytes, %d for %d", name, ba, len(small), bb, len(large))
}
}
// TestLinearTime checks that inputs quadratic in parsers without cmark's
// guards take linear work.
func TestLinearTime(t *testing.T) {
for _, c := range pathological {
checkLinear(t, c.name, c.ext, c.src)
}
}
+344
View File
@@ -0,0 +1,344 @@
package parser
import (
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
// GitHub's mentions (@octocat, @github/docs) and references to issues
// and pull requests (#123, GH-123, octocat/hello#123), found in the text
// once parsed, as email addresses are: never in code or links. Whether
// the person, team or issue exists is for a view to resolve.
const (
maxLogin = 39 // the longest GitHub login
maxRepo = 100 // the longest repository name
maxDigit = 10 // the most digits of an issue number
)
// Login returns whom a Mention mentions: a login, as octocat, or a team,
// as github/docs.
func (in Inline) Login() string {
if in.Kind != Mention || in.Text == "" {
return ""
}
return in.Text[1:]
}
// Ref returns the repository a Reference is in, as owner/name, or "" for
// the document's own, and the number of the issue or pull request.
func (in Inline) Ref() (repo string, number int) {
if in.Kind != Reference {
return "", 0
}
i := strings.LastIndexAny(in.Text, "#-")
if i < 0 {
return "", 0
}
if in.Text[i] == '#' {
repo = in.Text[:i]
}
number, _ = strconv.Atoi(in.Text[i+1:])
return repo, number
}
// references turns the mentions and references in the text of node n's
// descendants into nodes of their own, but in links and images, and in
// raw HTML's a, code, pre, style and script elements, as GitHub does.
// open counts those elements open before n's first child; it returns
// how many are open after its last.
func (ip *inlineParser) references(n int32, open int) int {
for c := ip.nodes[n].first; c >= 0; c = ip.nodes[c].next {
nd := &ip.nodes[c]
switch nd.kind {
case Link, Image:
case HTML:
open = max(open+skipElement(nd.text), 0)
case Text:
if open == 0 {
// A text's start is a word's start unless text before it
// ends in a word, as formatting ends none (_a_#1).
prev := nd.prev >= 0 && ip.nodes[nd.prev].kind == Text && endsInWord(ip.nodes[nd.prev].text)
c = ip.splitReferences(c, prev)
}
default:
open = ip.references(c, open)
}
}
return open
}
// skipElement returns 1 for raw HTML opening an element whose text has
// no mentions or references, -1 for HTML closing one, else 0.
func skipElement(tag string) int {
closing := strings.HasPrefix(tag, "</")
name := strings.TrimPrefix(strings.TrimPrefix(tag, "<"), "/")
end := 0
for end < len(name) && isASCIIAlnum(name[end]) {
end++
}
switch strings.ToLower(name[:end]) {
case "a", "code", "pre", "style", "script":
default:
return 0
}
switch {
case closing:
return -1
case strings.HasSuffix(tag, "/>"):
return 0
}
return 1
}
// splitReferences splits text node c at its mentions and references,
// which a word precedes when prevWord, and returns the last node of the
// text.
func (ip *inlineParser) splitReferences(c int32, prevWord bool) int32 {
// The text's @, # and - are found once each, as offsets in the text
// whose rest each split leaves: origin is where node c's text starts.
sc := refScan{next: [3]int{-1, -1, -1}, has: ip.refBytes}
origin := 0
for {
nd := &ip.nodes[c]
data := nd.text
a, b, kind, steps := findReference(data, origin, &sc, prevWord, ip.ext)
ip.d.steps += steps
if kind == Text {
return c
}
source := ip.s[nd.start:min(nd.end, len(ip.s))]
start, end := nd.start, nd.end
la := start + literalToSource(source, data, a)
lb := start + literalToSource(source, data, b)
r := ip.newNode(kind, data[a:b], la, lb)
post := ip.newNode(Text, data[b:], lb, end)
nd = &ip.nodes[c]
nd.text, nd.start, nd.end = data[:a], start, la
ip.insertAfter(c, r)
ip.insertAfter(r, post)
c, prevWord = post, endsInWord(data[:b])
origin += b
}
}
// refScan is where the next @, # and - of a text are, as offsets in it,
// -1 before they are looked for, and the text's length when there is none
// or the paragraph has none (has, as referenceBytes returns).
type refScan struct {
next [3]int
has uint8
}
// findReference finds the first mention or reference in data, the text
// from origin on, which a word character precedes when prevWord: its
// bytes and kind, or Text when there is none, and the bytes it scanned.
func findReference(data string, origin int, sc *refScan, prevWord bool, ext Extensions) (a, b int, kind InlineKind, steps int) {
mentions, refs := ext&ExtMentions != 0, ext&ExtReferences != 0
wordBefore := func(i int) bool {
if i == 0 {
return prevWord
}
return endsInWord(data[:i])
}
// The next @, # and - at or after i, each found with the vectorized
// IndexByte, which IndexAny is not, and kept across the text's splits.
find := func(k int, c byte, i int) int {
if sc.next[k] < origin+i {
if j := strings.IndexByte(data[i:], c); j < 0 {
sc.next[k] = origin + len(data)
} else {
sc.next[k] = origin + i + j
}
steps += sc.next[k] - origin - i
}
return sc.next[k] - origin
}
for i := 0; i < len(data); i++ {
j := len(data)
if sc.has&hasAt != 0 {
j = find(0, '@', i)
}
if sc.has&hasHash != 0 {
j = min(j, find(1, '#', i))
}
if sc.has&hasGH != 0 {
j = min(j, find(2, '-', i))
}
if j == len(data) {
return 0, 0, Text, steps
}
i = j
switch data[i] {
case '@':
if mentions && !wordBefore(i) {
if e := scanMention(data, i+1); e > 0 {
return i, e, Mention, steps + e - i
}
}
case '#':
if !refs {
continue
}
from := i
if wordBefore(i) {
var n int
from, n = repoBefore(data, i, prevWord)
steps += n
if from < 0 {
continue
}
}
if e := scanNumber(data, i+1); e > 0 {
return from, e, Reference, steps + e - i
}
default: // GH-123, found at its hyphen, as letters are many
if refs && isGH(data, i) && !wordBefore(i-2) {
if e := scanNumber(data, i+1); e > 0 {
return i - 2, e, Reference, steps + e - i
}
}
}
}
return 0, 0, Text, steps
}
// scanMention returns the end of the login, or team, at data[i:], after
// an @, or 0: a login is letters, digits and hyphens, from a letter or a
// digit, and a team a login, a slash and its name. No word follows it,
// nor a dot and a word, as in @example.com.
func scanMention(data string, i int) int {
j := i
if j >= len(data) || !isASCIIAlnum(data[j]) {
return 0
}
for j < len(data) && (isASCIIAlnum(data[j]) || data[j] == '-') {
j++
}
if j-i > maxLogin {
return 0
}
if j+1 < len(data) && data[j] == '/' && isASCIIAlnum(data[j+1]) {
j += 2
for j < len(data) && (isASCIIAlnum(data[j]) || data[j] == '-' || data[j] == '_') {
j++
}
}
if startsWithWord(data[j:]) || j+1 < len(data) && data[j] == '.' && isASCIIAlnum(data[j+1]) {
return 0
}
return j
}
// scanNumber returns the end of the issue number at data[i:], or 0: no
// more than maxDigit digits, from 1 to 9, which no word follows.
func scanNumber(data string, i int) int {
j := i
if j >= len(data) || data[j] < '1' || data[j] > '9' {
return 0
}
for j < len(data) && isASCIIDigit(data[j]) {
j++
}
if j-i > maxDigit || startsWithWord(data[j:]) {
return 0
}
return j
}
// repoBefore returns where owner/name ends at data[h], a #, begins, or
// -1, and the bytes it scanned: no word, slash or dot precedes it.
func repoBefore(data string, h int, prevWord bool) (int, int) {
j := h
for j > 0 && h-j < maxRepo && isRepoChar(data[j-1]) {
j--
}
if j == h || j == 0 || data[j-1] != '/' {
return -1, h - j
}
o := j - 1
k := o
for k > 0 && o-k < maxLogin && (isASCIIAlnum(data[k-1]) || data[k-1] == '-') {
k--
}
steps := h - k
if k == o || !isASCIIAlnum(data[k]) {
return -1, steps
}
if k == 0 {
if prevWord {
return -1, steps
}
return 0, steps
}
if c := data[k-1]; c == '/' || c == '.' || endsInWord(data[:k]) {
return -1, steps
}
return k, steps
}
func isRepoChar(c byte) bool { return isASCIIAlnum(c) || c == '-' || c == '_' || c == '.' }
// isWordRune reports whether r is of a word: a letter, a digit or _.
func isWordRune(r rune) bool {
if r < utf8.RuneSelf {
return isASCIIAlnum(byte(r)) || r == '_'
}
return unicode.IsLetter(r) || unicode.IsDigit(r)
}
func endsInWord(s string) bool {
r, _ := utf8.DecodeLastRuneInString(s)
return s != "" && isWordRune(r)
}
func startsWithWord(s string) bool {
r, _ := utf8.DecodeRuneInString(s)
return s != "" && isWordRune(r)
}
// isGH reports whether data[i], a hyphen, follows GH, in any case.
func isGH(data string, i int) bool {
return i >= 2 && data[i-2]|0x20 == 'g' && data[i-1]|0x20 == 'h'
}
// Which of a text's bytes may start a mention or a reference, as
// referenceBytes finds them.
const (
hasAt = 1 << iota // @, of a mention
hasHash // #, of a reference
hasGH // the - of GH-
)
// referenceBytes returns which bytes that may start a mention or a
// reference s holds, of those ext reads, so that text without them is not
// scanned again, nor scanned for those it lacks.
func referenceBytes(s string, ext Extensions) uint8 {
var has uint8
// IndexByte is vectorized, which ContainsAny is not.
if ext&ExtMentions != 0 && strings.IndexByte(s, '@') >= 0 {
has |= hasAt
}
if ext&ExtReferences == 0 {
return has
}
if strings.IndexByte(s, '#') >= 0 {
has |= hasHash
}
for i := strings.IndexByte(s, '-'); i >= 0; {
if isGH(s, i) {
has |= hasGH
break
}
j := strings.IndexByte(s[i+1:], '-')
if j < 0 {
break
}
i += 1 + j
}
return has
}
func isASCIIAlnum(c byte) bool { return isASCIIDigit(c) || isASCIILetter(c) }
+105
View File
@@ -0,0 +1,105 @@
package parser
import (
"fmt"
"strings"
"testing"
)
// refsOf lists the mentions and references of src's blocks, each as
// kind:text@start, checking that its offsets are its source.
func refsOf(t *testing.T, ext Extensions, src string) string {
t.Helper()
d := New(ext)
d.Set(src)
var out []string
for i := range d.Len() {
for _, in := range d.Inlines(i) {
if in.Kind != Mention && in.Kind != Reference {
continue
}
if got := src[in.Start:in.End]; got != in.Text {
t.Errorf("%q: %v %q is %q in the source", src, in.Kind, in.Text, got)
}
out = append(out, fmt.Sprintf("%v:%s@%d", in.Kind, in.Text, in.Start))
}
}
return strings.Join(out, " ")
}
// The cases are GitHub's, as its Markdown API rendered them, but for
// whether the person or the issue exists, which a view resolves.
func TestMentions(t *testing.T) {
for _, c := range []struct{ src, want string }{
{"hi @octocat and @hubot.", "mention:@octocat@3 mention:@hubot@16"},
{"foo@octocat x@y _@octocat", ""},
{"(@a) \"@b\" /@c .@d", "mention:@a@1 mention:@b@6 mention:@c@11 mention:@d@15"},
{"@a, @b! @c? @d: @e.", "mention:@a@0 mention:@b@4 mention:@c@8 mention:@d@12 mention:@e@16"},
{"@foo- @foo_bar @-foo", "mention:@foo-@0"},
{"cc @github/docs", "mention:@github/docs@3"},
{"@octocat@x @octocat.dev", "mention:@octocat@0"},
{"mail me@example.com", ""},
{"`@octocat` [@octocat](https://x.y) **@octocat** <@octocat>", "mention:@octocat@37 mention:@octocat@49"},
{"é@octocat", ""},
{"@" + strings.Repeat("a", 39) + " @" + strings.Repeat("a", 40), "mention:@" + strings.Repeat("a", 39) + "@0"},
{"# Hi @octocat", "mention:@octocat@5"},
{"| @octocat |\n|---|", "mention:@octocat@2"},
{"_a_@octocat **b**@octocat", "mention:@octocat@3 mention:@octocat@17"},
{`<a href="u">@octocat</a> <code>@octocat</code> <b>@octocat</b> <br/>@octocat`, "mention:@octocat@50 mention:@octocat@68"},
{"<pre>\n@a</pre>", ""},
} {
if got := refsOf(t, Default, c.src); got != c.want {
t.Errorf("%q gives %q, want %q", c.src, got, c.want)
}
}
if got := refsOf(t, Default&^ExtMentions, "hi @octocat #1"); got != "reference:#1@12" {
t.Errorf("without ExtMentions: %q", got)
}
}
func TestReferences(t *testing.T) {
for _, c := range []struct{ src, want string }{
{"see #874, (#871). a#874 #874abc #874. #0", "reference:#874@4 reference:#871@11 reference:#874@32"},
{"GH-874 gh-874 xGH-1", "reference:GH-874@0 reference:gh-874@7"},
{"octocat/hello-world#12 (b/c_d.e#3) (a.b/c#3)", "reference:octocat/hello-world#12@0 reference:b/c_d.e#3@24"},
{"x.org/a/b#1 /a/b#1 _#874", ""},
{"`#1` [#1](u) *#1*", "reference:#1@14"},
{"#12345678901 #1234567890", "reference:#1234567890@13"},
{"_a_#1 me@x.com#2 #3#4", "reference:#1@3 reference:#2@14 reference:#3@17"},
{"<code>#1</code> <A HREF=u>#2</a> #3", "reference:#3@33"},
} {
if got := refsOf(t, Default, c.src); got != c.want {
t.Errorf("%q gives %q, want %q", c.src, got, c.want)
}
}
if got := refsOf(t, Default&^ExtReferences, "hi @octocat #1"); got != "mention:@octocat@3" {
t.Errorf("without ExtReferences: %q", got)
}
}
func TestLoginAndRef(t *testing.T) {
d := New(Default)
d.Set("@octocat @github/docs #12 GH-7 octocat/hello#3")
type ref struct {
login, repo string
n int
}
var got []ref
for _, in := range d.Inlines(1) {
if in.Kind == Mention || in.Kind == Reference {
r, n := in.Ref()
got = append(got, ref{in.Login(), r, n})
}
}
want := []ref{{"octocat", "", 0}, {"github/docs", "", 0}, {"", "", 12}, {"", "", 7}, {"", "octocat/hello", 3}}
if fmt.Sprint(got) != fmt.Sprint(want) {
t.Errorf("got %v, want %v", got, want)
}
// Inlines made by hand do not panic.
if login := (Inline{Kind: Mention}).Login(); login != "" {
t.Errorf("an empty mention's login is %q", login)
}
if repo, n := (Inline{Kind: Reference, Text: "x"}).Ref(); repo != "" || n != 0 {
t.Errorf("a reference without a number is %q, %d", repo, n)
}
}
@@ -0,0 +1,91 @@
package parser
import (
"strings"
"testing"
)
// Bugs found reviewing the inline parser; each test fails on 088606d5.
// An email autolink in text after an entity or an escape gets the
// offsets of the decoded text, not of the source.
func TestReviewEmailOffsets(t *testing.T) {
for _, src := range []string{"a &amp; b x@y.com", `a \* b x@y.com`} {
d := Parse(src)
for _, in := range d.Inlines(1) {
if in.Kind == Link {
if got := d.Source()[in.Start:in.End]; got != "x@y.com" {
t.Errorf("%q: link [%d,%d) is %q, want %q", src, in.Start, in.End, got, "x@y.com")
}
}
}
}
}
// Quadratic time: nested footnote-like brackets, $ math with
// ExtDollarMath, and \( without \).
func TestReviewQuadratic(t *testing.T) {
checkLinear(t, "footnote brackets", Default, func(n int) string { return strings.Repeat("[^a", n) + strings.Repeat("]", n) })
checkLinear(t, "dollar openers", Default|ExtDollarMath, repeat("$a "))
checkLinear(t, "\\( openers", Default, repeat(`\(`))
}
// HTML entities are only names of the table followed by ;, not a
// legacy name's prefix.
func TestReviewEntityPrefix(t *testing.T) {
if got, want := render("&copyright; &notit;", Default), "<p>&amp;copyright; &amp;notit;</p>\n"; got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestReviewHealing(t *testing.T) {
for _, c := range []struct{ src, want string }{
// A tilde for "about" strikes the rest of the paragraph through.
{"about ~200 keys. See", "<p>about ~200 keys. See</p>\n"},
// Strong next to CJK text is not healed: ** shows.
{"这是**重要", "<p>这是<strong>重要</strong></p>\n"},
// An open code span skips healing emphasis: ** shows.
{"Edit **`config.ya", "<p>Edit <strong><code>config.ya</code></strong></p>\n"},
// $$ inside a code span counts as open math: $$ shows.
{"Use `$$` for display math", "<p>Use <code>$$</code> for display math</p>\n"},
// A destination with parentheses: raw syntax, and the added ) shows.
{"See [Go](https://en.wikipedia.org/wiki/Go_(lang", `<p>See <a href="https://en.wikipedia.org/wiki/Go_(lang)">Go</a></p>` + "\n"},
// The text of a link being written shows its [.
{"See the [Go blog", "<p>See the Go blog</p>\n"},
// Strikethrough being closed shows its tildes.
{"a ~~struck~", "<p>a <del>struck</del></p>\n"},
// A < destination: the added ) shows.
{"see [a](<htt", `<p>see <a href="htt">a</a></p>` + "\n"},
} {
if got := streamed(c.src); got != c.want {
t.Errorf("%q:\ngot %q\nwant %q", c.src, got, c.want)
}
}
}
// Extended autolinks end at punctuation beyond ASCII, such as the CJK
// comma, and at spaces beyond ASCII, but not at letters beyond ASCII.
func TestReviewAutolinkUnicodePunct(t *testing.T) {
for _, c := range []struct{ src, want string }{
{"信中附上链接:https://vishnuai.in/mediakit,并留下电话联系方式。", `<p>信中附上链接:<a href="https://vishnuai.in/mediakit">https://vishnuai.in/mediakit</a>,并留下电话联系方式。</p>` + "\n"},
{"见 https://example.com/a。", `<p>见 <a href="https://example.com/a">https://example.com/a</a>。</p>` + "\n"},
{"“www.example.com”", `<p>“<a href="http://www.example.com">www.example.com</a>”</p>` + "\n"},
{"(www.example.com/路径)", `<p>(<a href="http://www.example.com/%E8%B7%AF%E5%BE%84">www.example.com/路径</a>)</p>` + "\n"},
{"https://例子.测试/页面", `<p><a href="https://%E4%BE%8B%E5%AD%90.%E6%B5%8B%E8%AF%95/%E9%A1%B5%E9%9D%A2">https://例子.测试/页面</a></p>` + "\n"},
{"https://en.wikipedia.org/wiki/1990–91_season", `<p><a href="https://en.wikipedia.org/wiki/1990%E2%80%9391_season">https://en.wikipedia.org/wiki/1990–91_season</a></p>` + "\n"},
{"https://example.com\u3000下一句", `<p><a href="https://example.com">https://example.com</a>` + "\u3000下一句</p>\n"},
{"https://example.com\u2028下一句", `<p><a href="https://example.com">https://example.com</a>` + "\u2028下一句</p>\n"},
{"https://example.com/a\u2028下一句", `<p><a href="https://example.com/a">https://example.com/a</a>` + "\u2028下一句</p>\n"},
{"见\u2029www.example.com", "<p>见\u2029" + `<a href="http://www.example.com">www.example.com</a></p>` + "\n"},
{"邮箱:a@example.com,谢谢", `<p>邮箱:<a href="mailto:a@example.com">a@example.com</a>,谢谢</p>` + "\n"},
// Written links keep their whole destination and text.
{"[文档,下载](https://example.org/文档,下载)", `<p><a href="https://example.org/%E6%96%87%E6%A1%A3%EF%BC%8C%E4%B8%8B%E8%BD%BD">文档,下载</a></p>` + "\n"},
{"[https://example.org/文档,下载](https://example.org/文档,下载)", `<p><a href="https://example.org/%E6%96%87%E6%A1%A3%EF%BC%8C%E4%B8%8B%E8%BD%BD">https://example.org/文档,下载</a></p>` + "\n"},
{"<https://example.org/x,y>", `<p><a href="https://example.org/x%EF%BC%8Cy">https://example.org/x,y</a></p>` + "\n"},
{"[见 https://example.org/a,b](https://c.org)", `<p><a href="https://c.org">见 https://example.org/a,b</a></p>` + "\n"},
} {
if got := render(c.src, Default); got != c.want {
t.Errorf("%q:\ngot %q\nwant %q", c.src, got, c.want)
}
}
}
@@ -0,0 +1,891 @@
package parser
import (
"fmt"
"math/rand/v2"
"os"
"strconv"
"strings"
"testing"
"time"
"unicode/utf8"
)
// checkInvariants checks Next, Parent and segs ranges.
func checkInvariants(t *testing.T, d *Document, ctx string) {
t.Helper()
n := len(d.blocks)
if d.blocks[0].Next != n {
t.Fatalf("%s: root.Next %d, len %d", ctx, d.blocks[0].Next, n)
}
for i := 1; i < n; i++ {
b := &d.blocks[i]
if b.Parent < 0 || b.Parent >= i {
t.Fatalf("%s: block %d parent %d", ctx, i, b.Parent)
}
p := &d.blocks[b.Parent]
if b.Next <= i || b.Next > p.Next {
t.Fatalf("%s: block %d (%v) Next %d, parent %d Next %d", ctx, i, b.Kind, b.Next, b.Parent, p.Next)
}
if b.segA > b.segB || int(b.segB) > len(d.segs) {
t.Fatalf("%s: block %d segs [%d,%d) of %d", ctx, i, b.segA, b.segB, len(d.segs))
}
for _, s := range d.segsOf(b) {
if s.start > s.end || int(s.end) > len(d.src) {
t.Fatalf("%s: block %d seg %v src %d", ctx, i, s, len(d.src))
}
}
}
for k, i := range d.notes {
if i <= 0 || i >= n || d.blocks[i].Kind != FootnoteDefinition || normalizeLabel(d.blocks[i].info) != k {
t.Fatalf("%s: notes[%q]=%d bad", ctx, k, i)
}
}
}
var zzExt = func() Extensions {
if os.Getenv("ZZTABLES") != "" {
return Default
}
return Default &^ ExtTables
}()
func zzSeed() uint64 {
n, _ := strconv.ParseUint(os.Getenv("ZZSEED"), 10, 64)
return n
}
// zzKnown filters sources hitting a bug already reported: a label defined
// twice.
func zzKnown(src string) bool {
zzSeen = zzSeen || strings.Count(src, "[a]:") > 1 || strings.Count(src, "[b]:") > 1 || strings.Count(src, "[a]") > 1 && strings.Contains(src, "[a]:") || strings.Count(src, "[b]") > 1 && strings.Contains(src, "[b]:")
return zzSeen
}
var zzSeen bool
// zzFuzzOnly skips the random differential tests and probes unless
// ZZFUZZ is set (ZZSEED, ZZTABLES and ZZSTRUCT vary them).
func zzFuzzOnly(t *testing.T) {
if os.Getenv("ZZFUZZ") == "" {
t.Skip("set ZZFUZZ=1")
}
}
var zzStruct = os.Getenv("ZZSTRUCT") != ""
// zzDump describes blocks and their inlines with offsets.
func zzDump(d *Document) string {
var sb strings.Builder
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
fmt.Fprintf(&sb, "%d %v p%d n%d [%d,%d) open=%v L%d %v%d%c t%v task%d f%v h%v %v %q\n", i, b.Kind, b.Parent, b.Next, b.Start, b.End, b.Open, b.Level, b.Ordered, b.Number, b.Marker, b.Tight, b.Task, b.Fenced, b.Header, b.Align, b.info)
if b.Kind == CodeBlock || b.Kind == MathBlock || b.Kind == HTMLBlock {
for k := 0; k < d.LineCount(i); k++ {
l, o := d.Line(i, k)
fmt.Fprintf(&sb, " line %q @%d\n", l, o)
}
}
for _, in := range d.Inlines(i) {
fmt.Fprintf(&sb, " %v %q %q [%d,%d) n%d\n", in.Kind, in.Text, in.Dest, in.Start, in.End, in.Next)
}
}
return sb.String()
}
func zzStructFails(d *Document, ext Extensions) bool {
f := New(ext)
f.Set(d.Source())
return zzDump(d) != zzDump(f)
}
var zzPieces = []string{
"", "\n", "\n\n", "\r\n", "\r", "\t", "- ", "* ", "+ ", "> ", ">", "# ", "## ", "```", "~~~", "**", "*", "_", "[a]", "[a]: /u\n", "[b]: /v \"t\"\n",
"|", "| a | b |\n", "|---|---|\n", "a | b\n", "--- | ---\n", " ", " ", "1. ", "2) ", "---\n", "===\n", "text", "word ", "`", "<div>", "</div>\n", "<!-- ", "-->", "<pre>",
"$$", "$$\n", "\\[", "\\]", "\\[\n", "\\]\n", "[^1]", "[^1]: ", "[^x]: note\n", " more\n", "é", "日本", "\u00a0", "[ ] ", "[x] ", "<http://a.b>", "www.x.com ", "$x$", "\\(y\\)",
}
func zzRandDoc(r *rand.Rand, n int) string {
var sb strings.Builder
for range n {
sb.WriteString(zzPieces[r.IntN(len(zzPieces))])
}
return sb.String()
}
func zzCheck(t *testing.T, d *Document, ext Extensions, ctx string) {
t.Helper()
checkInvariants(t, d, ctx)
if want := render(d.Source(), ext); d.HTML() != want && !zzKnown(d.Source()) {
t.Fatalf("%s:\nsrc %q\ngot %q\nwant %q", ctx, d.Source(), d.HTML(), want)
}
}
func zzAppendFails(chunks []string, stream bool, ext Extensions) (failed bool) {
defer func() {
if recover() != nil {
failed = true
}
}()
zzSeen = false
d := New(ext)
d.SetStreaming(stream)
src := ""
for _, c := range chunks {
d.Append(c)
src += c
d.HTML()
if !stream && d.HTML() != render(src, ext) && !zzKnown(src) {
return true
}
}
d.SetStreaming(false)
return (d.HTML() != render(src, ext) || zzStruct && zzStructFails(d, ext)) && !zzKnown(src)
}
func zzMinChunks(chunks []string, stream bool, ext Extensions) []string {
for changed := true; changed; {
changed = false
for i := 0; i < len(chunks); i++ {
ns := append(append([]string(nil), chunks[:i]...), chunks[i+1:]...)
if zzAppendFails(ns, stream, ext) {
chunks, changed, i = ns, true, i-1
continue
}
if i+1 < len(chunks) {
ns = append(append(append([]string(nil), chunks[:i]...), chunks[i]+chunks[i+1]), chunks[i+2:]...)
if zzAppendFails(ns, stream, ext) {
chunks, changed, i = ns, true, i-1
continue
}
}
}
for i := range chunks {
for k := 0; k < len(chunks[i]); k++ {
ns := append([]string(nil), chunks...)
ns[i] = chunks[i][:k] + chunks[i][k+1:]
if ns[i] != "" && utf8.ValidString(ns[i]) && zzAppendFails(ns, stream, ext) {
chunks, changed, k = ns, true, k-1
}
}
}
}
return chunks
}
func zzStreamFails(chunks []string, ext Extensions) (failed bool) {
defer func() {
if recover() != nil {
failed = true
}
}()
zzSeen = false
d := New(ext)
d.SetStreaming(true)
src := ""
for _, c := range chunks {
d.Append(c)
src += c
f := New(ext)
f.SetStreaming(true)
f.Set(src)
if d.HTML() != f.HTML() && !zzKnown(src) {
return true
}
}
return false
}
func TestParserReviewStreamMatchesFreshStream(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(51+zzSeed(), 52))
for iter := range 20000 {
ext := zzExt
src := zzRandDoc(r, 1+r.IntN(14))
var chunks []string
for i := 0; i < len(src); {
k := min(1+r.IntN(6), len(src)-i)
chunks = append(chunks, src[i:i+k])
i += k
}
if zzStreamFails(chunks, ext) {
// Minimize.
for changed := true; changed; {
changed = false
for i := 0; i < len(chunks); i++ {
ns := append(append([]string(nil), chunks[:i]...), chunks[i+1:]...)
if zzStreamFails(ns, ext) {
chunks, changed, i = ns, true, i-1
}
}
for i := range chunks {
for k := 0; k < len(chunks[i]); k++ {
ns := append([]string(nil), chunks...)
ns[i] = chunks[i][:k] + chunks[i][k+1:]
if ns[i] != "" && utf8.ValidString(ns[i]) && zzStreamFails(ns, ext) {
chunks, changed, k = ns, true, k-1
}
}
}
}
t.Fatalf("iter %d: streaming %q differs from a fresh streaming parse", iter, chunks)
}
}
}
func zzTimeAppend(src string, chunk int) time.Duration {
d := New(Default)
t0 := time.Now()
for i := 0; i < len(src); i += chunk {
d.Append(src[i:min(i+chunk, len(src))])
}
return time.Since(t0)
}
func TestParserReviewLineEndings(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(61+zzSeed(), 62))
norm := func(s string) string {
return strings.ReplaceAll(strings.ReplaceAll(s, "\r\n", "\n"), "\r", "\n")
}
found := 0
for iter := 0; iter < 30000 && found < 8; iter++ {
var sb strings.Builder
for range 1 + r.IntN(10) {
p := zzPieces[r.IntN(len(zzPieces))]
if strings.Contains(p, "\r") {
continue
}
sb.WriteString(p)
}
s := sb.String()
for _, eol := range []string{"\r\n", "\r"} {
c := strings.ReplaceAll(s, "\n", eol)
if want, got := render(s, Default), norm(render(c, Default)); got != want {
// Minimize s.
f := func(s string) bool {
c := strings.ReplaceAll(s, "\n", eol)
return render(s, Default) != norm(render(c, Default))
}
for changed := true; changed; {
changed = false
for k := 0; k < len(s); k++ {
n := s[:k] + s[k+1:]
if utf8.ValidString(n) && f(n) {
s, changed, k = n, true, k-1
}
}
}
c = strings.ReplaceAll(s, "\n", eol)
t.Errorf("eol %q: %q\n lf %q\n eol %q", eol, s, render(s, Default), render(c, Default))
found++
break
}
}
}
}
func TestParserReviewRandomAppend(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(11+zzSeed(), 12))
for iter := range 30000 {
ext := zzExt
if r.IntN(3) == 0 {
ext = zzExt | ExtDollarMath
}
src := zzRandDoc(r, 1+r.IntN(14))
stream := r.IntN(2) == 0
var chunks []string
for i := 0; i < len(src); {
k := min(1+r.IntN(6), len(src)-i)
chunks = append(chunks, src[i:i+k])
i += k
}
if zzAppendFails(chunks, stream, ext) {
t.Fatalf("iter %d stream=%v ext=%b minimal chunks %q", iter, stream, ext, zzMinChunks(chunks, stream, ext))
}
}
}
// zzEditFails reports whether Set(prev) then Edit(from, to, text) differs from a whole parse.
func zzEditFails(prev string, from, to int, text string, ext Extensions) bool {
d := New(ext)
d.Set(prev)
d.HTML()
failed := false
func() {
defer func() {
if recover() != nil {
failed = true
}
}()
d.Edit(from, to, text)
failed = d.HTML() != render(d.Source(), ext)
}()
return failed
}
func zzMinEdit(prev string, from, to int, text string, ext Extensions) (string, int, int) {
for changed := true; changed; {
changed = false
for i := 0; i < len(prev); i++ {
if i >= from && i < to {
continue
}
np := prev[:i] + prev[i+1:]
nf, nt := from, to
if i < from {
nf--
nt--
}
if utf8.ValidString(np) && zzEditFails(np, nf, nt, text, ext) {
prev, from, to = np, nf, nt
changed = true
i--
}
}
for to > from {
np := prev[:from] + prev[from+1:]
if utf8.ValidString(np) && zzEditFails(np, from, to-1, text, ext) {
prev, to = np, to-1
changed = true
} else {
break
}
}
}
return prev, from, to
}
// zzReplay sets each state in turn (streaming around it when stream), and
// reports whether any step differs from a whole parse.
func zzReplay(states []string, stream bool, ext Extensions) (failed bool) {
defer func() {
if recover() != nil {
failed = true
}
}()
zzSeen = false
d := New(ext)
for _, s := range states {
if stream {
d.SetStreaming(true)
}
d.Set(s)
if stream {
d.HTML()
d.SetStreaming(false)
}
if (d.HTML() != render(s, ext) || zzStruct && zzStructFails(d, ext)) && !zzKnown(s) {
return true
}
}
return false
}
func zzMinStates(states []string, stream bool, ext Extensions) []string {
for changed := true; changed; {
changed = false
for i := 0; i < len(states); i++ {
ns := append(append([]string(nil), states[:i]...), states[i+1:]...)
if len(ns) > 0 && zzReplay(ns, stream, ext) {
states = ns
changed = true
i--
}
}
// Shrink each state by dropping bytes.
for i := range states {
for k := 0; k < len(states[i]); k++ {
ns := append([]string(nil), states...)
ns[i] = states[i][:k] + states[i][k+1:]
if utf8.ValidString(ns[i]) && zzReplay(ns, stream, ext) {
states = ns
changed = true
k--
}
}
}
}
return states
}
func zzShow(t *testing.T, states []string, stream bool, ext Extensions) {
d := New(ext)
for _, s := range states {
if stream {
d.SetStreaming(true)
}
d.Set(s)
if stream {
t.Logf("streaming: %q", d.HTML())
d.SetStreaming(false)
}
t.Logf("set %q\n got %q\n want %q", s, d.HTML(), render(s, ext))
}
}
// An edit shrinking a heading before a quiet block shifts a restart point
// that lay before the splice: restart goes negative and the next Append
// panics.
func TestParserReviewEditStaleRestartPanics(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Fatalf("panic: %v", r)
}
}()
d := New(0)
d.Set("# a\nb")
d.Set("c\n\nb") // Edit(0, 3, "c\n"): delta -1
t.Logf("restart %d restartAt %d", d.restart, d.restartAt)
d.Append("x")
if want := render("c\n\nbx", 0); d.HTML() != want {
t.Fatalf("got %q want %q", d.HTML(), want)
}
}
func TestParserReviewEditStaleRestartWrong(t *testing.T) {
d := New(0)
d.Set("# a\nb")
d.Set("# a\n\nb") // insert a blank line: delta +1, restart stays 0 -> 1
t.Logf("restart %d restartAt %d", d.restart, d.restartAt)
d.Append("x")
if want := render("# a\n\nbx", 0); d.HTML() != want {
t.Fatalf("got %q want %q", d.HTML(), want)
}
}
// A setext heading whose paragraph began with a definition moves its
// Start past the definition, so the restart point noted from it skips
// the paragraph's first lines.
func TestParserReviewSetextAfterDefinitionAppend(t *testing.T) {
d := New(0)
d.Append("[a]: /u\n b\n=\n")
d.Append("x")
if want := render("[a]: /u\n b\n=\nx", 0); d.HTML() != want {
t.Fatalf("got %q want %q", d.HTML(), want)
}
}
// A table whose header was a later line of a paragraph starts at the
// header line, where parsing restarts: alone, "2) a|b" is a list item.
func TestParserReviewTableFromParagraphRestart(t *testing.T) {
d := New(GFM)
d.Append("e\n2) a|b\n-|-\n")
d.Append("x")
if want := render(d.Source(), GFM); d.HTML() != want {
t.Errorf("append: got %q want %q", d.HTML(), want)
}
d = New(GFM)
d.Set("e\n2) a|b\n-|-\n\nz\n")
d.Edit(14, 15, "y")
if want := render(d.Source(), GFM); d.HTML() != want {
t.Errorf("edit: got %q want %q", d.HTML(), want)
}
}
// A second definition of a label, in the blocks an edit keeps, is lost
// when the edit removes the first: refs keeps only the first, so the
// splice has no record of the second.
func TestParserReviewDuplicateDefinitionLost(t *testing.T) {
d := New(0)
d.Set("[b]: /1\n\n[b]\n\n[b]: /2\n")
d.Edit(0, 1, "")
if want := render(d.Source(), 0); d.HTML() != want {
t.Fatalf("got %q want %q", d.HTML(), want)
}
}
// An edit that changes only a continuation line's indentation reuses the
// paragraph's old inlines (same first offset, same text) with the old
// offsets.
func TestParserReviewReusedInlinesStaleOffsets(t *testing.T) {
d := New(0)
d.Set("a\nb\n\nc\n")
d.HTML()
d.Edit(2, 2, " ")
f := New(0)
f.Set(d.Source())
if got, want := zzDump(d), zzDump(f); got != want {
t.Fatalf("got\n%s\nwant\n%s", got, want)
}
}
// An HTML block of type 7 cannot interrupt a paragraph, a lazy
// continuation line included (commonmark.js's "maybe lazy", cmark's
// !maybe_lazy): the tag continues the item's paragraph.
func TestParserReviewHTMLBlock7InterruptsLazyParagraph(t *testing.T) {
for src, want := range map[string]string{
"- a\n<x y=\"\">\n": "<ul>\n<li>a\n<x y=\"\"></li>\n</ul>\n",
"> a\n<x>\n": "<blockquote>\n<p>a\n<x></p>\n</blockquote>\n",
} {
if got := render(src, 0); got != want {
t.Errorf("%q: got %q want %q", src, got, want)
}
}
}
// A math block's opening line adds an empty line (or a second, empty
// line after the TeX on it) to its content.
func TestParserReviewMathBlockOpeningLine(t *testing.T) {
for src, want := range map[string]string{
"$$\ny\n$$\n": "y\n",
"$$ x\ny\n$$\n": "x\ny\n",
} {
d := Parse(src)
if got := d.Lines(1); got != want {
t.Errorf("%q: lines %q (%d), want %q", src, got, d.LineCount(1), want)
}
}
}
// Lines ending in \r alone make the parser look for \n to the end of the
// source on every line.
func TestParserReviewCROnlyQuadratic(t *testing.T) {
checkLinearWork(t, "lines ending in CR", Default, false, repeat("a\r"))
}
// \[ display math never closes at \]: mathBracket compares with the raw
// string `\\]`, three bytes.
func TestParserReviewBracketMathNeverCloses(t *testing.T) {
got := render("\\[\na\n\\]\n\ntext\n", Default)
want := "<div class=\"math display\">a</div>\n<p>text</p>\n"
if got != want {
t.Fatalf("got %q want %q", got, want)
}
}
// A childless list item spans its own marker line through that line's
// end, rather than truncating Block.End to Start+1 inside multi-byte
// markers such as "1. " or "10. ".
func TestParserReviewEmptyItemEndsAtLineEnd(t *testing.T) {
for _, tt := range []struct {
src string
start, end int
}{
{"- \n\n", 0, 2},
{"-\t\n\n", 0, 2},
{"1. \n\n", 0, 3},
{"10. \n\n", 0, 4},
{"1. \n2. a\n", 0, 3},
{"1. a\n2. \n\n", 5, 8},
{"1. a\n2. \n3. b\n", 5, 8},
{"- - \n\n", 2, 4},
{"1. ", 0, 3},
{"- \r\n\n", 0, 2},
{"- \n\n", 0, 4},
{"-\n", 0, 1},
{"1.\n", 0, 2},
} {
for _, ext := range []Extensions{0, Default} {
d := New(ext)
d.Set(tt.src)
found := false
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
if b.Kind != Item || b.Start != tt.start {
continue
}
found = true
if b.End != tt.end {
t.Errorf("ext=%v %q: item span [%d,%d), want [%d,%d)", ext, tt.src, b.Start, b.End, tt.start, tt.end)
}
if p := d.Block(b.Parent); p.Kind == List && p.End < b.End {
t.Errorf("ext=%v %q: parent list End=%d < item End=%d", ext, tt.src, p.End, b.End)
}
}
if !found {
t.Errorf("ext=%v %q: no item starting at %d", ext, tt.src, tt.start)
}
}
}
}
// Partial and streaming parses (where d.src holds bytes past end) must
// never scan past end when finalizing a childless list item.
func TestParserReviewEmptyItemEndsAtPartialEnd(t *testing.T) {
for _, ext := range []Extensions{0, Default} {
// Streaming trims the incomplete trailing UTF-8 sequence at end=5
// ("100. "), while d.src still contains the trailing bytes.
d := New(ext)
d.SetStreaming(true)
d.Set("100. \xe2\x82")
if d.cut != 5 {
t.Fatalf("ext=%v streaming cut=%d, want 5", ext, d.cut)
}
found := false
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
if b.Kind != Item {
continue
}
found = true
if b.Start != 0 || b.End != 5 {
t.Errorf("ext=%v streaming: item span [%d,%d), want [0,5)", ext, b.Start, b.End)
}
if p := d.Block(b.Parent); p.Kind != List || p.End > 5 || p.End < b.End {
t.Errorf("ext=%v streaming: parent list span [%d,%d) exceeds cut 5", ext, p.Start, p.End)
}
}
if !found {
t.Errorf("ext=%v streaming: no item found", ext)
}
}
for _, tt := range []struct {
src string
end int
start, want int
}{
{"100. \xe2\x82", 5, 0, 5},
{"100. \xe2\x82", 4, 0, 4},
{"10. \xe2\x82", 4, 0, 4},
{"- \xe2\x82", 2, 0, 2},
{"1. a\n2. \xe2\x82", 8, 5, 8},
} {
for _, ext := range []Extensions{0, Default} {
d := New(ext)
d.src = tt.src
d.parse(0, tt.end, nil)
found := false
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
if b.Kind != Item || b.Start != tt.start {
continue
}
found = true
if b.End != tt.want || b.End > tt.end {
t.Errorf("ext=%v %q end=%d: item span [%d,%d), want [%d,%d)", ext, tt.src, tt.end, b.Start, b.End, tt.start, tt.want)
}
if p := d.Block(b.Parent); p.Kind != List || p.End > tt.end || p.End < b.End {
t.Errorf("ext=%v %q end=%d: parent list End=%d, item End=%d", ext, tt.src, tt.end, p.End, b.End)
}
}
if !found {
t.Errorf("ext=%v %q end=%d: no item starting at %d", ext, tt.src, tt.end, tt.start)
}
}
}
}
// A closed math block's End includes its closing delimiter line rather
// than stopping at its last content segment.
func TestParserReviewMathBlockEnd(t *testing.T) {
for _, c := range []struct {
name string
src string
wantStart int
wantEnd int
wantOpen bool
}{
{"dollar multiline", "$$\nx\n$$\n", 0, len("$$\nx\n$$"), false},
{"dollar multiline with trailing para", "$$\nx\ny\n$$\n\nafter\n", 0, len("$$\nx\ny\n$$"), false},
{"dollar closing line content", "$$\nx $$\n", 0, len("$$\nx $$"), false},
{"dollar single line", "$$ x $$\n", 0, len("$$ x $$"), false},
{"bracket multiline", "\\[\nx\n\\]\n", 0, len("\\[\nx\n\\]"), false},
{"bracket multiline with trailing para", "\\[\nx\ny \\]\n\nafter\n", 0, len("\\[\nx\ny \\]"), false},
{"bracket single line", "\\[ x \\]\n", 0, len("\\[ x \\]"), false},
{"dollar unclosed", "$$\nx\n", 0, len("$$\nx"), true},
} {
d := Parse(c.src)
if d.Len() < 2 {
t.Fatalf("%s: expected at least 2 blocks, got %d", c.name, d.Len())
}
b := d.Block(1)
if b.Kind != MathBlock {
t.Fatalf("%s: block 1 kind = %v, want MathBlock", c.name, b.Kind)
}
if b.Start != c.wantStart || b.End != c.wantEnd || b.Open != c.wantOpen {
t.Errorf("%s: got Start=%d End=%d Open=%v (%q), want Start=%d End=%d Open=%v (%q)",
c.name, b.Start, b.End, b.Open, c.src[b.Start:b.End],
c.wantStart, c.wantEnd, c.wantOpen, c.src[c.wantStart:c.wantEnd])
}
}
}
func TestParserReviewRandomSetStates(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(31+zzSeed(), 32))
for iter := range 6000 {
ext := zzExt
stream := r.IntN(2) == 0
states := []string{zzRandDoc(r, 1+r.IntN(12))}
for range 12 {
cur := states[len(states)-1]
from := r.IntN(len(cur) + 1)
to := min(len(cur), from+r.IntN(10))
if r.IntN(3) == 0 {
to = from
}
next := cur[:from] + zzPieces[r.IntN(len(zzPieces))] + cur[to:]
if utf8.ValidString(next) {
states = append(states, next)
}
}
if zzReplay(states, stream, ext) {
m := zzMinStates(states, stream, ext)
t.Fatalf("iter %d stream=%v minimal states %q", iter, stream, m)
}
}
}
type zzOp struct {
from, to int
text string
}
func zzOpsFail(init string, ops []zzOp, stream bool, ext Extensions) (failed bool) {
defer func() {
if recover() != nil {
failed = true
}
}()
d := New(ext)
d.Set(init)
zzSeen = false
zzKnown(init)
cur := init
for _, o := range ops {
if o.to > len(cur) || o.from > o.to {
return false
}
next := cur[:o.from] + o.text + cur[o.to:]
if !utf8.ValidString(next) {
return false
}
if stream {
d.SetStreaming(true)
}
d.Edit(o.from, o.to, o.text)
if stream {
d.HTML()
d.SetStreaming(false)
}
cur = next
if (d.HTML() != render(cur, ext) || zzStruct && zzStructFails(d, ext)) && !zzKnown(cur) {
return true
}
}
return false
}
func zzMinOps(init string, ops []zzOp, stream bool, ext Extensions) (string, []zzOp) {
for changed := true; changed; {
changed = false
for i := 0; i < len(ops); i++ {
ns := append(append([]zzOp(nil), ops[:i]...), ops[i+1:]...)
if zzOpsFail(init, ns, stream, ext) {
ops, changed, i = ns, true, i-1
}
}
for k := 0; k < len(init); k++ {
ni := init[:k] + init[k+1:]
ns := append([]zzOp(nil), ops...)
for x := range ns {
// Shift ops naively: only valid for the first op.
if x == 0 {
if ns[0].from > k {
ns[0].from--
}
if ns[0].to > k {
ns[0].to--
}
}
}
if zzOpsFail(ni, ns, stream, ext) {
init, ops, changed, k = ni, ns, true, k-1
}
}
for x := range ops {
for k := 0; k < len(ops[x].text); k++ {
ns := append([]zzOp(nil), ops...)
ns[x].text = ops[x].text[:k] + ops[x].text[k+1:]
if zzOpsFail(init, ns, stream, ext) {
ops, changed, k = ns, true, k-1
}
}
if ops[x].to > ops[x].from {
ns := append([]zzOp(nil), ops...)
ns[x].to--
if zzOpsFail(init, ns, stream, ext) {
ops, changed = ns, true
}
}
}
}
return init, ops
}
func TestParserReviewRandomEditOps(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(41+zzSeed(), 42))
for iter := range 6000 {
ext := zzExt
stream := r.IntN(3) == 0
init := zzRandDoc(r, 1+r.IntN(20))
cur := init
var ops []zzOp
for range 20 {
from := r.IntN(len(cur) + 1)
to := min(len(cur), from+r.IntN(12))
if r.IntN(3) == 0 {
to = from
}
text := zzPieces[r.IntN(len(zzPieces))]
next := cur[:from] + text + cur[to:]
if !utf8.ValidString(next) {
continue
}
ops = append(ops, zzOp{from, to, text})
cur = next
}
if zzOpsFail(init, ops, stream, ext) {
mi, mo := zzMinOps(init, ops, stream, ext)
t.Fatalf("iter %d stream=%v init %q ops %+v", iter, stream, mi, mo)
}
}
}
func TestParserReviewRandomEdit(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(21+zzSeed(), 22))
for iter := range 4000 {
ext := zzExt
src := zzRandDoc(r, 1+r.IntN(20))
d := New(ext)
d.Set(src)
zzSeen = false
zzKnown(src)
stream := r.IntN(3) == 0
for e := range 30 {
cur := d.Source()
from := r.IntN(len(cur) + 1)
to := min(len(cur), from+r.IntN(12))
if r.IntN(3) == 0 {
to = from
}
text := zzPieces[r.IntN(len(zzPieces))]
next := cur[:from] + text + cur[to:]
if !utf8.ValidString(next) {
continue
}
if stream {
d.SetStreaming(true)
}
switch r.IntN(3) {
case 0:
d.Set(next)
default:
d.Edit(from, to, text)
}
if stream {
d.HTML()
d.SetStreaming(false)
}
if d.Source() != next {
t.Fatalf("source mismatch")
}
zzCheck(t, d, ext, fmt.Sprintf("iter %d edit %d [%d,%d)->%q prev %q", iter, e, from, to, text, cur))
}
}
}
+577
View File
@@ -0,0 +1,577 @@
package parser
import (
"html"
"strings"
"unicode/utf8"
)
// scanATXStart returns the length of an ATX heading's opening sequence
// at i with the spaces after it, or 0.
func scanATXStart(ln string, i int) int {
j := i
for j < len(ln) && ln[j] == '#' && j-i < 7 {
j++
}
n := j - i
if n == 0 || n > 6 {
return 0
}
if j == len(ln) {
return n
}
if !isSpaceOrTab(ln[j]) {
return 0
}
for j < len(ln) && isSpaceOrTab(ln[j]) {
j++
}
return j - i
}
// scanOpenFence returns the length of an opening code fence at i, or 0.
func scanOpenFence(ln string, i int) int {
c := ln[i]
j := i
for j < len(ln) && ln[j] == c {
j++
}
n := j - i
if n < 3 {
return 0
}
if c == '`' && strings.IndexByte(ln[j:], '`') >= 0 {
return 0
}
return n
}
// scanCloseFence returns the length of a closing code fence at i, or 0.
func scanCloseFence(ln string, i int) int {
c := ln[i]
if c != '`' && c != '~' {
return 0
}
j := i
for j < len(ln) && ln[j] == c {
j++
}
n := j - i
if n < 3 {
return 0
}
for ; j < len(ln); j++ {
if !isSpaceOrTab(ln[j]) {
return 0
}
}
return n
}
// scanSetextLine returns 1 for a line of =, 2 for one of -, or 0.
func scanSetextLine(ln string, i int) int {
c := ln[i]
j := i
for j < len(ln) && ln[j] == c {
j++
}
for ; j < len(ln); j++ {
if !isSpaceOrTab(ln[j]) {
return 0
}
}
if c == '=' {
return 1
}
return 2
}
// scanFootnoteDef returns the length of a footnote definition's start at
// i, [^label]: and the spaces after it, or 0.
func scanFootnoteDef(ln string, i int) int {
if !strings.HasPrefix(ln[i:], "[^") {
return 0
}
j := i + 2
for j < len(ln) && ln[j] != ']' {
switch ln[j] {
case ' ', '\t', '\r', '\n', 0:
return 0
}
j++
}
if j == i+2 || j+1 >= len(ln) || ln[j+1] != ':' {
return 0
}
j += 2
for j < len(ln) && isSpaceOrTab(ln[j]) {
j++
}
return j - i
}
var htmlBlockTags = map[string]bool{
"address": true, "article": true, "aside": true, "base": true, "basefont": true, "blockquote": true, "body": true,
"caption": true, "center": true, "col": true, "colgroup": true, "dd": true, "details": true, "dialog": true, "dir": true,
"div": true, "dl": true, "dt": true, "fieldset": true, "figcaption": true, "figure": true, "footer": true, "form": true,
"frame": true, "frameset": true, "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true, "head": true,
"header": true, "hr": true, "html": true, "iframe": true, "legend": true, "li": true, "link": true, "main": true,
"menu": true, "menuitem": true, "nav": true, "noframes": true, "ol": true, "optgroup": true, "option": true, "p": true,
"param": true, "search": true, "section": true, "summary": true, "table": true, "tbody": true, "td": true, "tfoot": true,
"th": true, "thead": true, "title": true, "tr": true, "track": true, "ul": true,
}
// hasPrefixFold reports whether s starts with prefix, ignoring ASCII case.
func hasPrefixFold(s, prefix string) bool {
return len(s) >= len(prefix) && strings.EqualFold(s[:len(prefix)], prefix)
}
// scanHTMLBlockStart returns the type (1 to 6) of an HTML block starting
// at i, or 0.
func scanHTMLBlockStart(ln string, i int) int {
s := ln[i:]
if len(s) < 2 || s[0] != '<' {
return 0
}
for _, tag := range [...]string{"<script", "<pre", "<style", "<textarea"} {
if hasPrefixFold(s, tag) {
if len(s) == len(tag) || s[len(tag)] == ' ' || s[len(tag)] == '\t' || s[len(tag)] == '>' {
return 1
}
}
}
switch {
case strings.HasPrefix(s, "<!--"):
return 2
case strings.HasPrefix(s, "<?"):
return 3
case strings.HasPrefix(s, "<![CDATA["):
return 5
case len(s) > 2 && s[1] == '!' && isASCIILetter(s[2]):
return 4
}
j := 1
if s[j] == '/' {
j++
}
k := j
for k < len(s) && (isASCIILetter(s[k]) || isASCIIDigit(s[k])) {
k++
}
if k == j || !htmlBlockTags[strings.ToLower(s[j:k])] {
return 0
}
if k == len(s) || s[k] == ' ' || s[k] == '\t' || s[k] == '>' || strings.HasPrefix(s[k:], "/>") {
return 6
}
return 0
}
// scanHTMLBlockStart7 returns 7 for a line that is a complete open or
// closing tag, other than script, style, pre and textarea, followed only
// by spaces, or 0.
func scanHTMLBlockStart7(ln string, i int) int {
s := ln[i:]
var n int
if strings.HasPrefix(s, "</") {
n = scanClosingTag(s, 0)
} else {
n = scanOpenTag(s, 0)
if n > 0 {
name := s[1:]
k := 0
for k < len(name) && (isASCIILetter(name[k]) || isASCIIDigit(name[k]) || name[k] == '-') {
k++
}
switch strings.ToLower(name[:k]) {
case "script", "style", "pre", "textarea":
return 0
}
}
}
if n == 0 || strings.Trim(s[n:], " \t") != "" {
return 0
}
return 7
}
// htmlBlockEnds reports whether a line ends an HTML block of type t.
func htmlBlockEnds(t int, s string) bool {
switch t {
case 1:
l := strings.ToLower(s)
return strings.Contains(l, "</script>") || strings.Contains(l, "</pre>") || strings.Contains(l, "</style>") || strings.Contains(l, "</textarea>")
case 2:
return strings.Contains(s, "-->")
case 3:
return strings.Contains(s, "?>")
case 4:
return strings.Contains(s, ">")
case 5:
return strings.Contains(s, "]]>")
}
return false
}
// The scanners of inline HTML (CommonMark's raw HTML) return the length
// of what they find at i, or 0.
func scanTagName(s string, i int) int {
if i >= len(s) || !isASCIILetter(s[i]) {
return 0
}
j := i + 1
for j < len(s) && (isASCIILetter(s[j]) || isASCIIDigit(s[j]) || s[j] == '-') {
j++
}
return j - i
}
// skipTagSpace skips whitespace within a tag, at most one line ending.
func skipTagSpace(s string, i int) int {
for i < len(s) && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r') {
i++
}
return i
}
func scanOpenTag(s string, i int) int {
if i >= len(s) || s[i] != '<' {
return 0
}
n := scanTagName(s, i+1)
if n == 0 {
return 0
}
j := i + 1 + n
for {
k := skipTagSpace(s, j)
if k < len(s) && s[k] == '>' {
return k + 1 - i
}
if k+1 < len(s) && s[k] == '/' && s[k+1] == '>' {
return k + 2 - i
}
if k == j {
return 0 // attributes need whitespace before them
}
// An attribute name.
if k >= len(s) || !(isASCIILetter(s[k]) || s[k] == '_' || s[k] == ':') {
return 0
}
k++
for k < len(s) && (isASCIILetter(s[k]) || isASCIIDigit(s[k]) || strings.IndexByte("_.:-", s[k]) >= 0) {
k++
}
// An optional value.
v := skipTagSpace(s, k)
if v < len(s) && s[v] == '=' {
v = skipTagSpace(s, v+1)
if v >= len(s) {
return 0
}
switch s[v] {
case '"', '\'':
e := strings.IndexByte(s[v+1:], s[v])
if e < 0 {
return 0
}
k = v + 1 + e + 1
default:
e := v
for e < len(s) && strings.IndexByte(" \t\n\r\"'=<>`", s[e]) < 0 {
e++
}
if e == v {
return 0
}
k = e
}
}
j = k
}
}
func scanClosingTag(s string, i int) int {
if !strings.HasPrefix(s[i:], "</") {
return 0
}
n := scanTagName(s, i+2)
if n == 0 {
return 0
}
k := skipTagSpace(s, i+2+n)
if k < len(s) && s[k] == '>' {
return k + 1 - i
}
return 0
}
// scanHTMLTag returns the length of the raw HTML at i: a tag, a comment,
// a processing instruction, a declaration or a CDATA section, or 0. The
// scanners noted in no remember that a kind found no end after a point,
// so that unclosed comments repeated do not take quadratic time.
func scanHTMLTag(s string, i int, no *htmlMemo) int {
r := s[i:]
if len(r) < 2 {
return 0
}
switch {
case r[1] == '/':
return scanClosingTag(s, i)
case r[1] == '?':
return no.until(s, i, 2, "?>", &no.pi)
case strings.HasPrefix(r, "<!--"):
if strings.HasPrefix(r, "<!-->") {
return 5
}
if strings.HasPrefix(r, "<!--->") {
return 6
}
return no.until(s, i, 4, "-->", &no.comment)
case strings.HasPrefix(r, "<![CDATA["):
return no.until(s, i, 9, "]]>", &no.cdata)
case r[1] == '!':
if len(r) > 2 && isASCIILetter(r[2]) {
return no.until(s, i, 3, ">", &no.decl)
}
return 0
}
return scanOpenTag(s, i)
}
type htmlMemo struct {
pi, comment, cdata, decl int
steps int // the bytes searched, as Document.steps
}
func (m *htmlMemo) reset() { *m = htmlMemo{-1, -1, -1, -1, 0} }
// until returns the length up to and including end, searched from
// i+skip, or 0; *none notes the offset after which none is.
func (m *htmlMemo) until(s string, i, skip int, end string, none *int) int {
if *none >= 0 && i+skip >= *none {
return 0
}
k := strings.Index(s[i+skip:], end)
if k < 0 {
m.steps += len(s) - i - skip
*none = i + skip
return 0
}
m.steps += k
return skip + k + len(end)
}
// scanDelimiterRow reads a table's delimiter row: cells of dashes, with
// a colon at either end for alignment, between pipes.
func scanDelimiterRow(line string) ([]Align, bool) {
line = strings.TrimRight(line, " \t")
if line == "" {
return nil, false
}
pipes := strings.Count(line, "|")
s := line
if s[0] == '|' {
s = s[1:]
}
if s != "" && s[len(s)-1] == '|' && pipes > 0 && (len(line) > 1 || line[0] != '|') {
if len(s) > 0 {
s = s[:len(s)-1]
}
}
var aligns []Align
for part := range strings.SplitSeq(s, "|") {
part = strings.Trim(part, " \t")
left := strings.HasPrefix(part, ":")
right := strings.HasSuffix(part, ":") && len(part) > 1
if left {
part = part[1:]
}
if right {
part = part[:len(part)-1]
}
if part == "" || strings.Trim(part, "-") != "" {
return nil, false
}
a := AlignNone
switch {
case left && right:
a = AlignCenter
case left:
a = AlignLeft
case right:
a = AlignRight
}
aligns = append(aligns, a)
}
if len(aligns) == 0 {
return nil, false
}
return aligns, true
}
// splitRow splits a table row into its cells' byte ranges, trimmed: an
// optional pipe, then cells between pipes, whose \| do not split.
func splitRow(line string) [][2]int {
var cells [][2]int
i := 0
if i < len(line) && line[i] == '|' {
i++
for i < len(line) && isSpaceOrTab(line[i]) {
i++
}
}
for i < len(line) {
j := i
for j < len(line) && line[j] != '|' {
if line[j] == '\\' && j+1 < len(line) && isEscapable(line[j+1]) {
j++
}
j++
}
j = min(j, len(line))
pipe := j < len(line)
a, b := i, j
for a < b && isSpaceOrTab(line[a]) {
a++
}
for b > a && isSpaceOrTab(line[b-1]) {
b--
}
if j > i || pipe {
cells = append(cells, [2]int{a, b})
}
if !pipe {
break
}
i = j + 1
for i < len(line) && isSpaceOrTab(line[i]) {
i++
}
}
return cells
}
// rowHasCells reports whether a line makes a table row of cells.
func rowHasCells(line string) bool {
return len(splitRow(line)) > 0
}
// isEscapable reports whether a backslash escapes c: ASCII punctuation.
func isEscapable(c byte) bool {
return c >= '!' && c <= '/' || c >= ':' && c <= '@' || c >= '[' && c <= '`' || c >= '{' && c <= '~'
}
// unescapeString resolves backslash escapes and entities.
func unescapeString(s string) string {
if strings.IndexByte(s, '\\') < 0 && strings.IndexByte(s, '&') < 0 {
return s
}
var b strings.Builder
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == '\\' && i+1 < len(s) && isEscapable(s[i+1]):
b.WriteByte(s[i+1])
i++
case c == '&':
if n, text := scanEntity(s, i); n > 0 {
b.WriteString(text)
i += n - 1
} else {
b.WriteByte(c)
}
default:
b.WriteByte(c)
}
}
return b.String()
}
// Entity reads the entity or numeric character reference s starts with,
// as &amp; or &#35;, returning its length and the text it stands for, or
// 0 when s starts with none that Markdown reads.
func Entity(s string) (n int, text string) { return scanEntity(s, 0) }
// scanEntity reads an entity or a numeric character reference at i,
// returning its length and its text, or 0.
func scanEntity(s string, i int) (int, string) {
j := i + 1
if j < len(s) && s[j] == '#' {
j++
hex := j < len(s) && (s[j] == 'x' || s[j] == 'X')
if hex {
j++
}
start, v := j, 0
for j < len(s) {
c := s[j]
var d int
switch {
case isASCIIDigit(c):
d = int(c - '0')
case hex && c|0x20 >= 'a' && c|0x20 <= 'f':
d = int(c|0x20-'a') + 10
default:
goto end
}
if v < 0x110000 {
if hex {
v = v*16 + d
} else {
v = v*10 + d
}
}
j++
}
end:
n := j - start
if n == 0 || hex && n > 6 || !hex && n > 7 || j >= len(s) || s[j] != ';' {
return 0, ""
}
r := rune(v)
if v == 0 || v > utf8.MaxRune || v >= 0xD800 && v <= 0xDFFF {
r = utf8.RuneError
}
return j + 1 - i, string(r)
}
start := j
for j < len(s) && j-start <= 32 && (isASCIILetter(s[j]) || isASCIIDigit(s[j])) {
j++
}
if j == start || j >= len(s) || s[j] != ';' || !isASCIILetter(s[start]) {
return 0, ""
}
ent := s[i : j+1]
text := html.UnescapeString(ent)
// A legacy name's prefix decodes, leaving the rest: &notit; is ¬it;.
if text == ent || strings.HasSuffix(text, ";") && ent != "&semi;" {
return 0, ""
}
return j + 1 - i, text
}
// literalToSource returns the offset in source of byte j of text, the
// literal it reads as: escapes and entities decoded, the rest as it is.
func literalToSource(source, text string, j int) int {
if source == text {
return min(j, len(source))
}
i, k := 0, 0
for i < len(source) && k < j {
switch c := source[i]; {
case c == '\\' && i+1 < len(source) && isEscapable(source[i+1]) && k < len(text) && text[k] == source[i+1]:
i, k = i+2, k+1
case c == '&':
if n, lit := scanEntity(source, i); n > 0 && strings.HasPrefix(text[k:], lit) {
i, k = i+n, k+len(lit)
continue
}
i, k = i+1, k+1
default:
i, k = i+1, k+1
}
}
return i
}
+59
View File
@@ -0,0 +1,59 @@
package parser
import (
"encoding/json"
"os"
"strings"
"testing"
)
type specExample struct {
Markdown string `json:"markdown"`
HTML string `json:"html"`
Example int `json:"example"`
Section string `json:"section"`
}
func loadSpec(t testing.TB, name string) []specExample {
data, err := os.ReadFile("testdata/" + name)
if err != nil {
t.Fatal(err)
}
var ex []specExample
if err := json.Unmarshal(data, &ex); err != nil {
t.Fatal(err)
}
return ex
}
func render(src string, ext Extensions) string {
d := New(ext)
d.Set(src)
return d.HTML()
}
// TestCommonMark runs the examples of the CommonMark spec, 0.31.2.
func TestCommonMark(t *testing.T) {
failed := 0
for _, ex := range loadSpec(t, "commonmark.json") {
if got := render(ex.Markdown, 0); got != ex.HTML {
failed++
t.Errorf("example %d (%s):\n%q\ngot %q\nwant %q", ex.Example, ex.Section, ex.Markdown, got, ex.HTML)
}
}
if failed > 0 {
t.Logf("%d failed", failed)
}
}
// TestGFM runs the examples of GitHub's extensions in the GFM spec.
func TestGFM(t *testing.T) {
for _, ex := range loadSpec(t, "gfm.json") {
if !strings.Contains(ex.Section, "(extension)") || ex.Section == "Disallowed Raw HTML (extension)" {
continue
}
if got := render(ex.Markdown, GFM); got != ex.HTML {
t.Errorf("example %d (%s):\n%q\ngot %q\nwant %q", ex.Example, ex.Section, ex.Markdown, got, ex.HTML)
}
}
}
+173
View File
@@ -0,0 +1,173 @@
package parser
import (
"math/rand/v2"
"os"
"strings"
"testing"
"unicode/utf8"
)
// corpus returns the documents streamed in tests: an answer of a
// language model, and extras.md, which exercises what the spec examples
// do not (footnotes, math, definitions after their links, task lists,
// tables streaming).
func corpus(t testing.TB) []string {
var docs []string
for _, name := range []string{"testdata/llm.md", "testdata/extras.md"} {
b, err := os.ReadFile(name)
if err != nil {
t.Fatal(err)
}
docs = append(docs, string(b))
}
return docs
}
// TestAppendMatchesWhole appends documents a character at a time and
// checks each prefix parses as when parsed whole.
func TestAppendMatchesWhole(t *testing.T) {
examples := loadSpec(t, "commonmark.json")
for _, ex := range loadSpec(t, "gfm.json") {
if strings.Contains(ex.Section, "(extension)") {
examples = append(examples, ex)
}
}
for _, ex := range examples {
for _, ext := range []Extensions{0, Default} {
d := New(ext)
src := ex.Markdown
for i := 0; i < len(src); {
_, n := utf8.DecodeRuneInString(src[i:])
d.Append(src[i : i+n])
i += n
if want := render(src[:i], ext); d.HTML() != want {
t.Fatalf("example %d, ext %b, after %q:\ngot %q\nwant %q", ex.Example, ext, src[:i], d.HTML(), want)
}
}
}
}
}
func TestAppendCorpus(t *testing.T) {
for _, src := range corpus(t) {
d := New(Default)
for i := 0; i < len(src); {
_, n := utf8.DecodeRuneInString(src[i:])
d.Append(src[i : i+n])
i += n
if i%997 == 0 || i == len(src) {
if want := render(src[:i], Default); d.HTML() != want {
t.Fatalf("after %d bytes (%q):\ngot %q\nwant %q", i, src[max(0, i-40):i], d.HTML(), want)
}
}
}
}
}
// TestAppendChunks appends in random chunks, a stream's tokens.
func TestAppendChunks(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2))
for _, src := range corpus(t) {
for range 20 {
d := New(Default)
for i := 0; i < len(src); {
n := min(1+r.IntN(12), len(src)-i)
d.Append(src[i : i+n])
i += n
}
if want := render(src, Default); d.HTML() != want {
t.Fatalf("got %q\nwant %q", d.HTML(), want)
}
}
}
}
// TestStreamingEnds checks that a document streamed with healing parses
// exactly once streaming is turned off.
func TestStreamingEnds(t *testing.T) {
for _, src := range corpus(t) {
d := New(Default)
d.SetStreaming(true)
for i := 0; i < len(src); {
_, n := utf8.DecodeRuneInString(src[i:])
d.Append(src[i : i+n])
i += n
d.HTML() // inlines of the tail, healed
}
d.SetStreaming(false)
if want := render(src, Default); d.HTML() != want {
t.Fatalf("got %q\nwant %q", d.HTML(), want)
}
}
}
// TestEditsMatchWhole edits documents at random places and checks they
// parse as when parsed whole.
func TestEditsMatchWhole(t *testing.T) {
r := rand.New(rand.NewPCG(3, 4))
pieces := []string{"", "\n", "\n\n", "- ", "> ", "# ", "```", "**", "*", "_", "[a]", "[a]: /u\n", "|", "| a | b |\n|---|---|\n", " ", "1. ", "---\n", "text", "`", "<div>", "$$", "[^1]"}
for _, src := range corpus(t) {
d := New(Default)
d.Set(src)
for range 400 {
cur := d.Source()
from := r.IntN(len(cur) + 1)
to := min(len(cur), from+r.IntN(30))
if r.IntN(3) == 0 {
to = from
}
text := pieces[r.IntN(len(pieces))]
next := cur[:from] + text + cur[to:]
if !utf8.ValidString(next) {
continue
}
d.Edit(from, to, text)
if d.Source() != next {
t.Fatalf("source %q, want %q", d.Source(), next)
}
if want := render(next, Default); d.HTML() != want {
t.Fatalf("edit [%d, %d) to %q:\ngot %q\nwant %q", from, to, text, d.HTML(), want)
}
}
}
}
// TestEditJoinsTableParagraph edits the first line of a paragraph whose
// last line is a table's header into an item of the list above it, which
// the paragraph then joins.
func TestEditJoinsTableParagraph(t *testing.T) {
for _, c := range []struct{ src, text string }{
{"- one\n\ntwo\n| a | b |\n|---|---|\n| 1 | 2 |\n", "- "},
{"1. one\n\ntwo\n| a |\n|---|\n", "2. "},
} {
at := strings.Index(c.src, "\n\n") + 2
d := New(Default)
d.Set(c.src)
d.Edit(at, at, c.text)
if want := render(d.Source(), Default); d.HTML() != want {
t.Errorf("%q:\ngot %q\nwant %q", d.Source(), d.HTML(), want)
}
}
}
// TestDefinitionLater checks that a definition appended after its link
// makes the link a link, and that removing it unmakes it.
func TestDefinitionLater(t *testing.T) {
d := New(Default)
d.Append("See [docs].\n\nMore text.\n\n")
if got := d.HTML(); strings.Contains(got, "<a ") {
t.Fatalf("link before its definition: %q", got)
}
d.Append("[docs]: https://example.com\n")
if got := d.HTML(); !strings.Contains(got, `<a href="https://example.com">docs</a>`) {
t.Fatalf("no link after the definition: %q", got)
}
if d.Block(1).Revision() == 0 {
t.Error("the paragraph's revision did not change")
}
d.Set("See [docs].\n\nMore text.\n\n")
if got := d.HTML(); strings.Contains(got, "<a ") {
t.Fatalf("link after its definition went: %q", got)
}
}
File diff suppressed because it is too large. Load diff
+56
View File
@@ -0,0 +1,56 @@
# Notes on streaming
Text with a footnote[^1] and another[^note], math $$e^{i\pi}+1=0$$ and \(a^2\),
and a [link defined later][later] with *emphasis*, **strong**, ~~struck~~ and `code`.
$$
\int_0^1 x^2\,dx = \frac{1}{3}
$$
\[
a + b
\]
- [ ] a task
- [x] a done task
continued lazily
| a | b |
|---|:-:|
| 1 | 2 |
| 3 | 4 |
> A quote
with a lazy line
> - and a list
> inside
1. one
2. two
still two
3) three
10. ten
```go
func main() {
fmt.Println("hi")
}
```
indented code
<div>
raw <b>HTML</b>
</div>
Setext heading
--------------
Visit www.example.com, https://example.com/a_(b) or mail someone@example.com.
[later]: https://example.com/later "Later"
[^1]: The footnote.
[^note]: A footnote
of two lines.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff