3
0
mirror of https://github.com/larvit/adf-codec.git synced 2026-11-19 06:35:44 +01:00

Read a link destination holding an unbalanced unescaped parenthesis as no destination

This commit is contained in:
2026-10-28 13:04:54 +01:00
committed by Lillem4n
parent 744476658c
commit 6fe527c945
6 changed files with 30 additions and 13 deletions
+11 -1
View File
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { readInlineTarget, targetMemo } from './link-syntax.ts'
import { readDestination, readInlineTarget, targetMemo } from './link-syntax.ts'
// Every `](` of the text, read in order through one memo, as a reader closes its brackets.
function targets(text: string): unknown[] {
@@ -28,6 +28,16 @@ test('an unbracketed destination ends at its first unmatched `)`', () => {
assert.deepEqual(targets('[a](b\\)c)'), [{ destination: 'b)c', length: 6 }])
})
test('a destination holding an unbalanced unescaped `(` at a space or the end reads as none', () => {
assert.deepEqual(targets('[a](b(c "t")'), [undefined])
assert.deepEqual(targets('[a](b(c "t") [d](e)'), [undefined, { destination: 'e', length: 3 }])
assert.deepEqual(targets('[a](b(c) "t")'), [{ destination: 'b(c)', length: 10, title: 't' }])
assert.deepEqual(targets('[a](b((c) "t")'), [undefined])
assert.equal(readDestination('b(c', 0), undefined)
assert.equal(readDestination('b(c d', 0), undefined)
assert.deepEqual(readDestination('b(c) d', 0), { length: 4, value: 'b(c)' })
})
test('a target reads whitespace and a title around its destination, bracketed, unbracketed or empty', () => {
assert.deepEqual(targets('[a]( b\n "t" ) [c](<d e> \'f\') [g]()'), [
{ destination: 'b', length: 10, title: 't' },
+9 -2
View File
@@ -72,6 +72,13 @@ export function targetMemo(text: string): TargetMemo {
return { destinationEnds: undefined, tails: new Map(), text }
}
// Of the starts still open at a stop, only the innermost has its parentheses balanced; the others hold a `(` nothing closed and keep no end.
function stopAt(ends: Int32Array, open: number[], index: number): void {
const innermost = open.pop()
if (innermost !== undefined) ends[innermost] = index
open.length = 0
}
// `ends[start]` is where an unbracketed destination from `start` stops, filled in one pass for every start a target can have: just after a `(`, a space or a control character, and 0, where `readDestination`'s run begins.
function destinationEnds(text: string): Int32Array {
const ends = new Int32Array(text.length + 1)
@@ -82,10 +89,10 @@ function destinationEnds(text: string): Int32Array {
const start = character === ')' ? open.pop() : undefined
if (start !== undefined) ends[start] = index
if (character !== ' ' && !holdsControlCharacter(character)) continue
for (const stopped of open.splice(0)) ends[stopped] = index
stopAt(ends, open, index)
open.push(index + 1)
}
for (const stopped of open) ends[stopped] = text.length
stopAt(ends, open, text.length)
return ends
}