Skip to content

Commit 3aec511

Browse files
committed
Fix error positions for non-printable characters, #801
1 parent 11aa483 commit 3aec511

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

‎src/parser/parser.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,12 @@ function skipUntilLineEnd (state: ParserState) {
417417
}
418418

419419
function checkPrintable (state: ParserState, start: number, end: number) {
420-
if (PATTERN_NON_PRINTABLE.test(state.input.slice(start, end))) {
420+
const match = PATTERN_NON_PRINTABLE.exec(state.input.slice(start, end))
421+
422+
if (match !== null) {
423+
// The lone low surrogate alternative also matches the preceding character,
424+
// so the offending character is always the last one in the match.
425+
state.position = start + match.index + match[0].length - 1
421426
throwError(state, 'the stream contains non-printable characters')
422427
}
423428
}

‎test/core/units/load-error.test.mjs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,26 @@ describe('load errors', () => {
174174
assert.throws(() => { load('\x9f') }, YAMLException)
175175
})
176176

177+
it('points non-printable character errors at the offending character', () => {
178+
function assertMark (source, position, line, column) {
179+
assert.throws(() => { load(source) }, error => {
180+
assert.ok(error instanceof YAMLException)
181+
assert.equal(error.mark.position, position)
182+
assert.equal(error.mark.line, line)
183+
assert.equal(error.mark.column, column)
184+
return true
185+
})
186+
}
187+
188+
assertMark('a: b\x01\nc: d', 4, 0, 4)
189+
assertMark('a: b\x01\n c', 4, 0, 4)
190+
assertMark('a: |\n x\x01\n y\n', 8, 1, 3)
191+
assertMark('a: b\r\n c\x01', 9, 1, 3)
192+
assertMark('a: x\udc00', 4, 0, 4)
193+
assertMark('a: \udc00', 3, 0, 3)
194+
assertMark('a: x\ud800', 4, 0, 4)
195+
})
196+
177197
it('forbid flow indicators at the start of block plain scalars', () => {
178198
assert.throws(() => { load('k: ]') }, YAMLException)
179199
assert.throws(() => { load('k: }') }, YAMLException)

0 commit comments

Comments
 (0)