| 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 | "fmt" |
| 19 | "strings" |
| 20 | ) |
| 21 | |
| 22 | type LexImports struct { |
| 23 | Imports map[string]*LexImport |
| 24 | } |
| 25 | |
| 26 | func NewLexImports(lexImport interface{}) (*LexImports, error) { |
| 27 | imports, err := newLexImports().Add(lexImport.(*LexImport)) |
| 28 | return imports, err |
| 29 | } |
| 30 | |
| 31 | func newLexImports() *LexImports { |
| 32 | return &LexImports{ |
| 33 | Imports: make(map[string]*LexImport), |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | func AddLexImport(imports, lexImport interface{}) (*LexImports, error) { |
| 38 | return imports.(*LexImports).Add(lexImport.(*LexImport)) |
| 39 | } |
| 40 | |
| 41 | // Add will return true if a new lex import has been added, otherwise false. |
| 42 | func (this *LexImports) Add(lexImport *LexImport) (*LexImports, error) { |
| 43 | if _, exist := this.Imports[lexImport.Id]; exist { |
| 44 | return nil, fmt.Errorf("duplicate builtin declaration: %s", lexImport.String()) |
| 45 | } |
| 46 | this.Imports[lexImport.Id] = lexImport |
| 47 | return this, nil |
| 48 | } |
| 49 | |
| 50 | func (this *LexImports) String() string { |
| 51 | w := new(strings.Builder) |
| 52 | fmt.Fprintf(w, "import(\n") |
| 53 | for _, imp := range this.Imports { |
| 54 | fmt.Fprintf(w, "\t%s\n", imp.String()) |
| 55 | } |
| 56 | fmt.Fprintf(w, ")") |
| 57 | return w.String() |
| 58 | } |