Files
Diego Augusto MolinaandGitHub fefc347053 Improve parser and lexer (#811)
* convert source to a struct and fix minor issue displaying error

* lexer: add byte and char pos

* improve parser to use string instead of []rune

* add lexer benchmarks

* make lexer work as an iterator

* make parser use the new iterator API in lexer

* allow reusing the parser

* cleanup code

* add parser benchmarks
2025-06-30 20:08:46 +02:00

37 lines
571 B
Go

package file
import "strings"
type Source struct {
raw string
}
func NewSource(contents string) Source {
return Source{
raw: contents,
}
}
func (s Source) String() string {
return s.raw
}
func (s Source) Snippet(line int) (string, bool) {
if s.raw == "" {
return "", false
}
var start int
for i := 1; i < line; i++ {
pos := strings.IndexByte(s.raw[start:], '\n')
if pos < 0 {
return "", false
}
start += pos + 1
}
end := start + strings.IndexByte(s.raw[start:], '\n')
if end < start {
end = len(s.raw)
}
return s.raw[start:end], true
}