| 1 | Lexical and Parser user-defined context data |
| 2 | ============================================ |
| 3 | |
| 4 | For advanced use cases, it is sometimes helpful to be able to have |
| 5 | additional data available in either the parsing context, such as |
| 6 | sdt actions, or the lexical context, on the lexer or the tokens |
| 7 | it produces. |
| 8 | |
| 9 | Distinction between Lexical and Parser Context |
| 10 | ---------------------------------------------- |
| 11 | |
| 12 | Both `parser` and `token` define `Context` as `interface{}`. |
| 13 | |
| 14 | Gocc does not care if the parser and lexical contexts are the same, or |
| 15 | whether you use one and not the other. |
| 16 | |
| 17 | Lexical Context |
| 18 | --------------- |
| 19 | |
| 20 | When the lexer.Lexer object is configured with a non-nil Context value, |
| 21 | the value will be assigned to the Pos.Context property of every token |
| 22 | the lexer generates. |
| 23 | |
| 24 | If you are parsing multiple files, this could allow you to inform the |
| 25 | user that tokenA is redeclared in file2.txt after being previously |
| 26 | declared in file1.txt, rather than simply "I've seen tokenA before". |
| 27 | |
| 28 | Assigning: |
| 29 | ``` |
| 30 | // assigning |
| 31 | l := lexer.NewLexer() |
| 32 | l.Context = &MyContext{ /* populate fields */ } |
| 33 | // or just |
| 34 | l.Context = filename |
| 35 | ``` |
| 36 | |
| 37 | Use (assumes MyContext has method 'Source()' that returns filename) |
| 38 | ``` |
| 39 | func duplicate(newToken, oldToken *token.Token) error { |
| 40 | newPos, oldPos := newToken.Pos, oldToken.Pos |
| 41 | |
| 42 | return fmt.Errorf("%s:%d:%d: error: '%s' redefined.\n%s:%d:%d: previous definition", |
| 43 | newPos.Context.(*MyContext).Source(), newPos.Line, newPos.Column, |
| 44 | string(newToken.Lit), |
| 45 | oldPos.Context.(*MyContext).Source(), oldPos.Line, oldPos.Column) |
| 46 | ``` |
| 47 | |
| 48 | Parser Context |
| 49 | -------------- |
| 50 | |
| 51 | This allows you to surface contextual information when invoking SDT actions. It |
| 52 | corresponds to the `Context` property of the `parser.Parser` class, and can be |
| 53 | accessed with the SDT token `$Context`. |
| 54 | |
| 55 | Example: |
| 56 | |
| 57 | _bnf_ |
| 58 | ``` |
| 59 | Identifier: identifier << ast.NewIdentifier($0, $Context); |
| 60 | ``` |
| 61 | |
| 62 | _ast/main.go_ |
| 63 | ``` |
| 64 | func NewIdentifier(nameAttr Attrib, context interface{}) (string, error) { |
| 65 | name := string(nameAttr.(*token.Token).Lit) |
| 66 | if previous, exists := context.(*ParseContext).Identifiers[name]; exists { |
| 67 | ... |
| 68 | ``` |
| 69 |