location.go

 1package location
 2
 3import (
 4	"regexp"
 5
 6	"github.com/graphql-go/graphql/language/source"
 7)
 8
 9type SourceLocation struct {
10	Line   int `json:"line"`
11	Column int `json:"column"`
12}
13
14func GetLocation(s *source.Source, position int) SourceLocation {
15	body := []byte{}
16	if s != nil {
17		body = s.Body
18	}
19	line := 1
20	column := position + 1
21	lineRegexp := regexp.MustCompile("\r\n|[\n\r]")
22	matches := lineRegexp.FindAllIndex(body, -1)
23	for _, match := range matches {
24		matchIndex := match[0]
25		if matchIndex < position {
26			line++
27			l := len(s.Body[match[0]:match[1]])
28			column = position + 1 - (matchIndex + l)
29			continue
30		} else {
31			break
32		}
33	}
34	return SourceLocation{Line: line, Column: column}
35}