| 1 | package ast |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | |
| 6 | "github.com/goccmack/gocc/example/usercontext/token" |
| 7 | ) |
| 8 | |
| 9 | type Attrib interface{} |
| 10 | |
| 11 | // Demonstrates how Lexical and Parser context might differ. |
| 12 | type LexicalContext struct { |
| 13 | SourceFile string |
| 14 | ForbiddenWords []string |
| 15 | } |
| 16 | |
| 17 | // Source implements the lexer.Sourcer interface. |
| 18 | func (lc *LexicalContext) Source() string { |
| 19 | return lc.SourceFile |
| 20 | } |
| 21 | |
| 22 | type ParserContext struct { |
| 23 | ImportedFiles []*token.Token // files and where we imported them from |
| 24 | ExtensionToForbidden map[string]string |
| 25 | Visitors []string |
| 26 | CallbackFn func() |
| 27 | } |
| 28 | |
| 29 | // Simple type that will convey both kinds of context. |
| 30 | type Identifier struct { |
| 31 | Name *token.Token |
| 32 | ParserContext *ParserContext |
| 33 | } |
| 34 | |
| 35 | func NewIdentifier(name Attrib, context interface{}) (*Identifier, error) { |
| 36 | switch pc := context.(type) { |
| 37 | case *ParserContext: |
| 38 | pc.Visitors = append(pc.Visitors, string(name.(*token.Token).Lit)) |
| 39 | if pc.CallbackFn != nil { |
| 40 | pc.CallbackFn() |
| 41 | } |
| 42 | return &Identifier{Name: name.(*token.Token), ParserContext: pc}, nil |
| 43 | |
| 44 | default: |
| 45 | return nil, fmt.Errorf("%s: NewIdentifier expected ParserContext, got %+v", |
| 46 | string(name.(*token.Token).Lit), context) |
| 47 | } |
| 48 | } |