mirror of
https://github.com/hanzoai/expr.git
synced 2026-09-24 16:58:58 +00:00
* 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
37 lines
571 B
Go
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
|
|
}
|