Skip to content

Commit e05986a

Browse files
Avoid panic by not exceeding bounds of string..
Signed-off-by: James Phillips <jamesdphillips@gmail.com>
1 parent 0629778 commit e05986a

File tree

2 files changed

+36
-17
lines changed

2 files changed

+36
-17
lines changed

language/lexer/lexer.go

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,23 @@ func blockStringValue(in string) string {
381381
// Expand a block string's raw value into independent lines.
382382
lines := splitLinesRegex.Split(in, -1)
383383

384+
// Remove leading blank lines.
385+
for {
386+
if isBlank := lineIsBlank(lines[0]); !isBlank {
387+
break
388+
}
389+
lines = lines[1:]
390+
}
391+
392+
// Remove trailing blank lines.
393+
for {
394+
i := len(lines) - 1
395+
if isBlank := lineIsBlank(lines[i]); !isBlank {
396+
break
397+
}
398+
lines = append(lines[:i], lines[i+1:]...)
399+
}
400+
384401
// Remove common indentation from all lines but first
385402
commonIndent := -1
386403
for i := 1; i < len(lines); i++ {
@@ -395,27 +412,13 @@ func blockStringValue(in string) string {
395412
}
396413
if commonIndent > 0 {
397414
for i, line := range lines {
415+
if commonIndent > len(line) {
416+
continue
417+
}
398418
lines[i] = line[commonIndent:]
399419
}
400420
}
401421

402-
// Remove leading blank lines.
403-
for {
404-
if isBlank := lineIsBlank(lines[0]); !isBlank {
405-
break
406-
}
407-
lines = lines[1:]
408-
}
409-
410-
// Remove trailing blank lines.
411-
for {
412-
i := len(lines) - 1
413-
if isBlank := lineIsBlank(lines[i]); !isBlank {
414-
break
415-
}
416-
lines = append(lines[:i], lines[i+1:]...)
417-
}
418-
419422
// Return a string of the lines joined with U+000A.
420423
return strings.Join(lines, "\n")
421424
}

language/lexer/lexer_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,22 @@ func TestLexer_LexesBlockStrings(t *testing.T) {
480480
Value: " white space ",
481481
},
482482
},
483+
{
484+
Body: `
485+
"""
486+
my great description
487+
spans multiple lines
488+
489+
with breaks
490+
"""
491+
`,
492+
Expected: Token{
493+
Kind: TokenKind[BLOCK_STRING],
494+
Start: 5,
495+
End: 89,
496+
Value: "my great description\nspans multiple lines\n\nwith breaks",
497+
},
498+
},
483499
{
484500
Body: `"""contains " quote"""`,
485501
Expected: Token{

0 commit comments

Comments
 (0)