Debian Codegraph @

pkg/highlight/parser.go

raw
1 package highlight
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "regexp"
8
9 "gopkg.in/yaml.v2"
10 )
11
12 // A Group represents a syntax group
13 type Group uint8
14
15 // Groups contains all of the groups that are defined
16 // You can access them in the map via their string name
17 var Groups map[string]Group
18 var numGroups Group
19
20 // String returns the group name attached to the specific group
21 func (g Group) String() string {
22 for k, v := range Groups {
23 if v == g {
24 return k
25 }
26 }
27 return ""
28 }
29
30 // A Def is a full syntax definition for a language
31 // It has a filetype, information about how to detect the filetype based
32 // on filename or header (the first line of the file)
33 // Then it has the rules which define how to highlight the file
34 type Def struct {
35 *Header
36 rules *rules
37 }
38
39 type Header struct {
40 FileType string
41 FileNameRegex *regexp.Regexp
42 HeaderRegex *regexp.Regexp
43 SignatureRegex *regexp.Regexp
44 }
45
46 type HeaderYaml struct {
47 FileType string `yaml:"filetype"`
48 Detect struct {
49 FNameRegexStr string `yaml:"filename"`
50 HeaderRegexStr string `yaml:"header"`
51 SignatureRegexStr string `yaml:"signature"`
52 } `yaml:"detect"`
53 }
54
55 type File struct {
56 FileType string
57 yamlSrc map[any]any
58 }
59
60 // A Pattern is one simple syntax rule
61 // It has a group that the rule belongs to, as well as
62 // the regular expression to match the pattern
63 type pattern struct {
64 group Group
65 regex *regexp.Regexp
66 }
67
68 // rules defines which patterns and regions can be used to highlight
69 // a filetype
70 type rules struct {
71 regions []*region
72 patterns []*pattern
73 includes []string
74 }
75
76 // A region is a highlighted region (such as a multiline comment, or a string)
77 // It belongs to a group, and has start and end regular expressions
78 // A region also has rules of its own that only apply when matching inside the
79 // region and also rules from the above region do not match inside this region
80 // Note that a region may contain more regions
81 type region struct {
82 group Group
83 limitGroup Group
84 parent *region
85 start *regexp.Regexp
86 end *regexp.Regexp
87 skip *regexp.Regexp
88 rules *rules
89 }
90
91 func init() {
92 Groups = make(map[string]Group)
93 }
94
95 // MakeHeader takes a header (.hdr file) file and parses the header
96 // Header files make parsing more efficient when you only want to compute
97 // on the headers of syntax files
98 // A yaml file might take ~400us to parse while a header file only takes ~20us
99 func MakeHeader(data []byte) (*Header, error) {
100 lines := bytes.Split(data, []byte{'\n'})
101 if len(lines) < 4 {
102 return nil, errors.New("Header file has incorrect format")
103 }
104 header := new(Header)
105 var err error
106 header.FileType = string(lines[0])
107 fnameRegexStr := string(lines[1])
108 headerRegexStr := string(lines[2])
109 signatureRegexStr := string(lines[3])
110
111 if fnameRegexStr != "" {
112 header.FileNameRegex, err = regexp.Compile(fnameRegexStr)
113 }
114 if err == nil && headerRegexStr != "" {
115 header.HeaderRegex, err = regexp.Compile(headerRegexStr)
116 }
117 if err == nil && signatureRegexStr != "" {
118 header.SignatureRegex, err = regexp.Compile(signatureRegexStr)
119 }
120
121 if err != nil {
122 return nil, err
123 }
124
125 return header, nil
126 }
127
128 // MakeHeaderYaml takes a yaml spec for a syntax file and parses the
129 // header
130 func MakeHeaderYaml(data []byte) (*Header, error) {
131 var hdrYaml HeaderYaml
132 err := yaml.Unmarshal(data, &hdrYaml)
133 if err != nil {
134 return nil, err
135 }
136
137 header := new(Header)
138 header.FileType = hdrYaml.FileType
139
140 if hdrYaml.Detect.FNameRegexStr != "" {
141 header.FileNameRegex, err = regexp.Compile(hdrYaml.Detect.FNameRegexStr)
142 }
143 if err == nil && hdrYaml.Detect.HeaderRegexStr != "" {
144 header.HeaderRegex, err = regexp.Compile(hdrYaml.Detect.HeaderRegexStr)
145 }
146 if err == nil && hdrYaml.Detect.SignatureRegexStr != "" {
147 header.SignatureRegex, err = regexp.Compile(hdrYaml.Detect.SignatureRegexStr)
148 }
149
150 if err != nil {
151 return nil, err
152 }
153
154 return header, nil
155 }
156
157 // MatchFileName will check the given file name with the stored regex
158 func (header *Header) MatchFileName(filename string) bool {
159 if header.FileNameRegex != nil {
160 return header.FileNameRegex.MatchString(filename)
161 }
162
163 return false
164 }
165
166 func (header *Header) MatchFileHeader(firstLine []byte) bool {
167 if header.HeaderRegex != nil {
168 return header.HeaderRegex.Match(firstLine)
169 }
170
171 return false
172 }
173
174 // HasFileSignature checks the presence of a stored signature
175 func (header *Header) HasFileSignature() bool {
176 return header.SignatureRegex != nil
177 }
178
179 // MatchFileSignature will check the given line with the stored regex
180 func (header *Header) MatchFileSignature(line []byte) bool {
181 if header.SignatureRegex != nil {
182 return header.SignatureRegex.Match(line)
183 }
184
185 return false
186 }
187
188 func ParseFile(input []byte) (f *File, err error) {
189 // This is just so if we have an error, we can exit cleanly and return the parse error to the user
190 defer func() {
191 if r := recover(); r != nil {
192 var ok bool
193 err, ok = r.(error)
194 if !ok {
195 err = fmt.Errorf("pkg: %v", r)
196 }
197 }
198 }()
199
200 var rules map[any]any
201 if err = yaml.Unmarshal(input, &rules); err != nil {
202 return nil, err
203 }
204
205 f = new(File)
206 f.yamlSrc = rules
207
208 for k, v := range rules {
209 if k == "filetype" {
210 filetype := v.(string)
211
212 if filetype == "" {
213 return nil, errors.New("empty filetype")
214 }
215
216 f.FileType = filetype
217 break
218 }
219 }
220
221 if f.FileType == "" {
222 return nil, errors.New("missing filetype")
223 }
224
225 return f, err
226 }
227
228 // ParseDef parses an input syntax file into a highlight Def
229 func ParseDef(f *File, header *Header) (s *Def, err error) {
230 // This is just so if we have an error, we can exit cleanly and return the parse error to the user
231 defer func() {
232 if r := recover(); r != nil {
233 var ok bool
234 err, ok = r.(error)
235 if !ok {
236 err = fmt.Errorf("pkg: %v", r)
237 }
238 }
239 }()
240
241 src := f.yamlSrc
242
243 s = new(Def)
244 s.Header = header
245
246 for k, v := range src {
247 if k == "rules" {
248 inputRules := v.([]any)
249
250 rules, err := parseRules(inputRules, nil)
251 if err != nil {
252 return nil, err
253 }
254
255 s.rules = rules
256 }
257 }
258
259 if s.rules == nil {
260 // allow empty rules
261 s.rules = &rules{}
262 }
263
264 return s, err
265 }
266
267 // HasIncludes returns whether this syntax def has any include statements
268 func HasIncludes(d *Def) bool {
269 hasIncludes := len(d.rules.includes) > 0
270 for _, r := range d.rules.regions {
271 hasIncludes = hasIncludes || hasIncludesInRegion(r)
272 }
273 return hasIncludes
274 }
275
276 func hasIncludesInRegion(region *region) bool {
277 hasIncludes := len(region.rules.includes) > 0
278 for _, r := range region.rules.regions {
279 hasIncludes = hasIncludes || hasIncludesInRegion(r)
280 }
281 return hasIncludes
282 }
283
284 // GetIncludes returns a list of filetypes that are included by this syntax def
285 func GetIncludes(d *Def) []string {
286 includes := d.rules.includes
287 for _, r := range d.rules.regions {
288 includes = append(includes, getIncludesInRegion(r)...)
289 }
290 return includes
291 }
292
293 func getIncludesInRegion(region *region) []string {
294 includes := region.rules.includes
295 for _, r := range region.rules.regions {
296 includes = append(includes, getIncludesInRegion(r)...)
297 }
298 return includes
299 }
300
301 // ResolveIncludes will sort out the rules for including other filetypes
302 // You should call this after parsing all the Defs
303 func ResolveIncludes(def *Def, files []*File) {
304 resolveIncludesInDef(files, def)
305 }
306
307 func resolveIncludesInDef(files []*File, d *Def) {
308 for _, lang := range d.rules.includes {
309 for _, searchFile := range files {
310 if lang == searchFile.FileType {
311 searchDef, _ := ParseDef(searchFile, nil)
312 d.rules.patterns = append(d.rules.patterns, searchDef.rules.patterns...)
313 d.rules.regions = append(d.rules.regions, searchDef.rules.regions...)
314 }
315 }
316 }
317 for _, r := range d.rules.regions {
318 resolveIncludesInRegion(files, r)
319 r.parent = nil
320 }
321 }
322
323 func resolveIncludesInRegion(files []*File, region *region) {
324 for _, lang := range region.rules.includes {
325 for _, searchFile := range files {
326 if lang == searchFile.FileType {
327 searchDef, _ := ParseDef(searchFile, nil)
328 region.rules.patterns = append(region.rules.patterns, searchDef.rules.patterns...)
329 region.rules.regions = append(region.rules.regions, searchDef.rules.regions...)
330 }
331 }
332 }
333 for _, r := range region.rules.regions {
334 resolveIncludesInRegion(files, r)
335 r.parent = region
336 }
337 }
338
339 func parseRules(input []any, curRegion *region) (ru *rules, err error) {
340 defer func() {
341 if r := recover(); r != nil {
342 var ok bool
343 err, ok = r.(error)
344 if !ok {
345 err = fmt.Errorf("pkg: %v", r)
346 }
347 }
348 }()
349 ru = new(rules)
350
351 for _, v := range input {
352 rule := v.(map[any]any)
353 for k, val := range rule {
354 group := k
355
356 switch object := val.(type) {
357 case string:
358 if object == "" {
359 return nil, fmt.Errorf("Empty rule %s", k)
360 }
361
362 if k == "include" {
363 ru.includes = append(ru.includes, object)
364 } else {
365 // Pattern
366 r, err := regexp.Compile(object)
367 if err != nil {
368 return nil, err
369 }
370
371 groupStr := group.(string)
372 if _, ok := Groups[groupStr]; !ok {
373 numGroups++
374 Groups[groupStr] = numGroups
375 }
376 groupNum := Groups[groupStr]
377 ru.patterns = append(ru.patterns, &pattern{groupNum, r})
378 }
379 case map[any]any:
380 // region
381 region, err := parseRegion(group.(string), object, curRegion)
382 if err != nil {
383 return nil, err
384 }
385 ru.regions = append(ru.regions, region)
386 default:
387 return nil, fmt.Errorf("Bad type %T", object)
388 }
389 }
390 }
391
392 return ru, nil
393 }
394
395 func parseRegion(group string, regionInfo map[any]any, prevRegion *region) (r *region, err error) {
396 defer func() {
397 if r := recover(); r != nil {
398 var ok bool
399 err, ok = r.(error)
400 if !ok {
401 err = fmt.Errorf("pkg: %v", r)
402 }
403 }
404 }()
405
406 r = new(region)
407 if _, ok := Groups[group]; !ok {
408 numGroups++
409 Groups[group] = numGroups
410 }
411 groupNum := Groups[group]
412 r.group = groupNum
413 r.parent = prevRegion
414
415 // start is mandatory
416 if start, ok := regionInfo["start"]; ok {
417 start := start.(string)
418 if start == "" {
419 return nil, fmt.Errorf("Empty start in %s", group)
420 }
421
422 r.start, err = regexp.Compile(start)
423 if err != nil {
424 return nil, err
425 }
426 } else {
427 return nil, fmt.Errorf("Missing start in %s", group)
428 }
429
430 // end is mandatory
431 if end, ok := regionInfo["end"]; ok {
432 end := end.(string)
433 if end == "" {
434 return nil, fmt.Errorf("Empty end in %s", group)
435 }
436
437 r.end, err = regexp.Compile(end)
438 if err != nil {
439 return nil, err
440 }
441 } else {
442 return nil, fmt.Errorf("Missing end in %s", group)
443 }
444
445 // skip is optional
446 if skip, ok := regionInfo["skip"]; ok {
447 skip := skip.(string)
448 if skip == "" {
449 return nil, fmt.Errorf("Empty skip in %s", group)
450 }
451
452 r.skip, err = regexp.Compile(skip)
453 if err != nil {
454 return nil, err
455 }
456 }
457
458 // limit-color is optional
459 if groupStr, ok := regionInfo["limit-group"]; ok {
460 groupStr := groupStr.(string)
461 if groupStr == "" {
462 return nil, fmt.Errorf("Empty limit-group in %s", group)
463 }
464
465 if _, ok := Groups[groupStr]; !ok {
466 numGroups++
467 Groups[groupStr] = numGroups
468 }
469 groupNum := Groups[groupStr]
470 r.limitGroup = groupNum
471
472 if err != nil {
473 return nil, err
474 }
475 } else {
476 r.limitGroup = r.group
477 }
478
479 // rules are optional
480 if rules, ok := regionInfo["rules"]; ok {
481 r.rules, err = parseRules(rules.([]any), r)
482 if err != nil {
483 return nil, err
484 }
485 }
486
487 if r.rules == nil {
488 // allow empty rules
489 r.rules = &rules{}
490 }
491
492 return r, nil
493 }