Skip to content

Commit

Permalink
Fix error message code snippet
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Nov 10, 2023
1 parent 2e25c7e commit 90b6ecc
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 18 deletions.
22 changes: 21 additions & 1 deletion json.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package main
import (
"fmt"
"strconv"
"strings"
"unicode/utf8"
)

type jsonParser struct {
Expand Down Expand Up @@ -49,6 +51,9 @@ func (p *jsonParser) next() {
} else {
p.lastChar = 0
}
if p.lastChar == '\n' {
p.lineNumber++
}
p.sourceTail.writeByte(p.lastChar)
}

Expand Down Expand Up @@ -357,5 +362,20 @@ func (p *jsonParser) skipComment() {
}

func (p *jsonParser) errorSnippet(message string) error {
return fmt.Errorf("%s on node %d.\n%s\n", message, p.lineNumber, p.sourceTail.string())
lines := strings.Split(p.sourceTail.string(), "\n")
lastLineLen := utf8.RuneCountInString(lines[len(lines)-1])
pointer := strings.Repeat(".", lastLineLen-1) + "^"
lines = append(lines, pointer)

paddedLines := make([]string, len(lines))
for i, line := range lines {
paddedLines[i] = " " + line
}

return fmt.Errorf(
"%s on line %d.\n\n%s\n\n",
message,
p.lineNumber,
strings.Join(paddedLines, "\n"),
)
}
51 changes: 34 additions & 17 deletions ring.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,49 @@
package main

import (
"strings"
)

type ring struct {
buf [100]byte
buf [70]byte
start, end int
}

func (r *ring) writeByte(b byte) {
if b == '\n' {
r.end = 0
r.start = r.end
return
}
r.buf[r.end] = b
r.end++
if r.end >= len(r.buf) {
r.end = 0
}
r.end = (r.end + 1) % len(r.buf)

if r.end == r.start {
r.start++
if r.start >= len(r.buf) {
r.start = 0
}
r.start = (r.start + 1) % len(r.buf)
}
}

func (r *ring) string() string {
if r.start < r.end {
return string(r.buf[r.start:r.end])
var lines []byte
newlineCount := 0

for i := r.end - 1; ; i-- {
if i < 0 {
i = len(r.buf) - 1
}

if r.buf[i] == '\n' {
newlineCount++
if newlineCount == 2 {
break
}
}

lines = append(lines, r.buf[i])

if i == r.start {
break
}
}
return string(r.buf[r.start:]) + string(r.buf[:r.end])

for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 {
lines[i], lines[j] = lines[j], lines[i]
}

return strings.TrimRight(string(lines), "\t \n")
}

0 comments on commit 90b6ecc

Please sign in to comment.