Debian Codegraph @

internal/ast/grammar.go

raw symbols SCIP
1 //Copyright 2013 Vastech SA (PTY) LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package ast
16
17 import (
18 "errors"
19 "fmt"
20 "os"
21 )
22
23 type Grammar struct {
24 *LexPart
25 *SyntaxPart
26 }
27
28 func NewGrammar(lexPart, syntaxPart interface{}) (*Grammar, error) {
29 g := &Grammar{}
30 if lexPart != nil {
31 g.LexPart = lexPart.(*LexPart)
32 } else {
33 lp, _ := NewLexPart(nil, nil, nil)
34 g.LexPart = lp
35 }
36 if syntaxPart != nil {
37 g.SyntaxPart = syntaxPart.(*SyntaxPart).augment()
38 }
39
40 return g, consistent(g)
41 }
42
43 var (
44 errUndefined = errors.New("undefined symbol used in production")
45 )
46
47 func consistent(g *Grammar) (err error) {
48 if g.SyntaxPart == nil {
49 return
50 }
51
52 defs := make(map[string]bool)
53 used := make(map[string][]string)
54
55 for _, tok := range g.LexPart.TokDefsList {
56 defs[tok.id] = true
57 }
58 for _, prod := range g.SyntaxPart.ProdList {
59 if len(prod.Body.Symbols) == 0 {
60 return fmt.Errorf("empty production alternative: Maybe you are missing the \"empty\" keyword in %q", prod)
61 }
62 defs[prod.Id] = true
63 for _, s := range prod.Body.Symbols {
64 if s.String()[0] == '"' {
65 continue
66 }
67 used[s.String()] = append(used[s.String()], prod.Id)
68 }
69 }
70 for s := range defs {
71 if s == "S'" {
72 continue
73 }
74 if _, ok := used[s]; !ok {
75 fmt.Fprintf(os.Stderr, "warning: symbol %q defined but never used\n", s)
76 }
77 }
78 for s, in := range used {
79 if _, ok := defs[s]; !ok {
80 if s == "empty" || s == "error" {
81 continue
82 }
83 if s[0] >= 'A' && s[0] <= 'Z' {
84 fmt.Fprintf(os.Stderr, "error: undefined symbol %q used in productions %q\n", s, in)
85 err = errUndefined
86 } else {
87 fmt.Fprintf(os.Stderr, "warning: undefined symbol %q used in productions %q\n", s, in)
88 }
89 }
90 }
91 return
92 }