| 1 | // Copyright (c) 2025 Ernest Micklei |
| 2 | // |
| 3 | // MIT License |
| 4 | // |
| 5 | // Permission is hereby granted, free of charge, to any person obtaining |
| 6 | // a copy of this software and associated documentation files (the |
| 7 | // "Software"), to deal in the Software without restriction, including |
| 8 | // without limitation the rights to use, copy, modify, merge, publish, |
| 9 | // distribute, sublicense, and/or sell copies of the Software, and to |
| 10 | // permit persons to whom the Software is furnished to do so, subject to |
| 11 | // the following conditions: |
| 12 | // |
| 13 | // The above copyright notice and this permission notice shall be |
| 14 | // included in all copies or substantial portions of the Software. |
| 15 | // |
| 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 17 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 18 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 19 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE |
| 20 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION |
| 21 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION |
| 22 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 23 | |
| 24 | package proto |
| 25 | |
| 26 | import ( |
| 27 | "bytes" |
| 28 | "sort" |
| 29 | "text/scanner" |
| 30 | ) |
| 31 | |
| 32 | // Literal represents intLit,floatLit,strLit or boolLit or a nested structure thereof. |
| 33 | type Literal struct { |
| 34 | Position scanner.Position |
| 35 | Source string |
| 36 | IsString bool |
| 37 | |
| 38 | // It not nil then the entry is actually a comment with line(s) |
| 39 | // modelled this way because Literal is not an elementContainer |
| 40 | Comment *Comment |
| 41 | |
| 42 | // The rune use to delimit the string value (only valid iff IsString) |
| 43 | QuoteRune rune |
| 44 | |
| 45 | // literal value can be an array literal value (even nested) |
| 46 | Array []*Literal |
| 47 | |
| 48 | // literal value can be a map of literals (even nested) |
| 49 | // DEPRECATED: use OrderedMap instead |
| 50 | Map map[string]*Literal |
| 51 | |
| 52 | // literal value can be a map of literals (even nested) |
| 53 | // this is done as pairs of name keys and literal values so the original ordering is preserved |
| 54 | OrderedMap LiteralMap |
| 55 | } |
| 56 | |
| 57 | var emptyRune rune |
| 58 | |
| 59 | // LiteralMap is like a map of *Literal but preserved the ordering. |
| 60 | // Can be iterated yielding *NamedLiteral values. |
| 61 | type LiteralMap []*NamedLiteral |
| 62 | |
| 63 | // Get returns a Literal from the map. |
| 64 | func (m LiteralMap) Get(key string) (*Literal, bool) { |
| 65 | for _, each := range m { |
| 66 | if each.Name == key { |
| 67 | // exit on the first match |
| 68 | return each.Literal, true |
| 69 | } |
| 70 | } |
| 71 | return new(Literal), false |
| 72 | } |
| 73 | |
| 74 | // SourceRepresentation returns the source (use the same rune that was used to delimit the string). |
| 75 | func (l Literal) SourceRepresentation() string { |
| 76 | var buf bytes.Buffer |
| 77 | if l.IsString { |
| 78 | if l.QuoteRune == emptyRune { |
| 79 | buf.WriteRune('"') |
| 80 | } else { |
| 81 | buf.WriteRune(l.QuoteRune) |
| 82 | } |
| 83 | } |
| 84 | buf.WriteString(l.Source) |
| 85 | if l.IsString { |
| 86 | if l.QuoteRune == emptyRune { |
| 87 | buf.WriteRune('"') |
| 88 | } else { |
| 89 | buf.WriteRune(l.QuoteRune) |
| 90 | } |
| 91 | } |
| 92 | return buf.String() |
| 93 | } |
| 94 | |
| 95 | // parse expects to read a literal constant after =. |
| 96 | func (l *Literal) parse(p *Parser) error { |
| 97 | pos, tok, lit := p.next() |
| 98 | // handle special element inside literal, a comment line |
| 99 | if isComment(lit) { |
| 100 | nc := newComment(pos, lit) |
| 101 | if l.Comment == nil { |
| 102 | l.Comment = nc |
| 103 | } else { |
| 104 | l.Comment.Merge(nc) |
| 105 | } |
| 106 | // peek at next token to see if it's structural (indicating end of current context) |
| 107 | // if so, don't recurse, just return with comment set |
| 108 | nextPos, nextTok, nextLit := p.next() |
| 109 | if nextTok == tRIGHTSQUARE || nextTok == tRIGHTCURLY || nextTok == tSEMICOLON || nextTok == tCOMMA { |
| 110 | // put it back and return - let the caller handle these structural tokens |
| 111 | p.nextPut(nextPos, nextTok, nextLit) |
| 112 | return nil |
| 113 | } |
| 114 | // put it back and continue with remaining entries (could be another comment or a literal) |
| 115 | p.nextPut(nextPos, nextTok, nextLit) |
| 116 | return l.parse(p) |
| 117 | } |
| 118 | if tok == tLEFTSQUARE { |
| 119 | // collect array elements |
| 120 | array := []*Literal{} |
| 121 | |
| 122 | // if it's an empty array, consume the close bracket, set the Array to |
| 123 | // an empty array, and return |
| 124 | r := p.peekNonWhitespace() |
| 125 | if r == ']' { |
| 126 | pos, _, _ := p.next() |
| 127 | l.Array = array |
| 128 | l.IsString = false |
| 129 | l.Position = pos |
| 130 | return nil |
| 131 | } |
| 132 | for { |
| 133 | e := new(Literal) |
| 134 | if err := e.parse(p); err != nil { |
| 135 | return err |
| 136 | } |
| 137 | // if this is a comment-only literal, don't add it to array |
| 138 | // but keep reading to attach comment to next literal |
| 139 | if e.Comment != nil && e.Source == "" && e.Array == nil && e.OrderedMap == nil { |
| 140 | // check what comes next |
| 141 | _, tok, lit := p.next() |
| 142 | if tok == tRIGHTSQUARE { |
| 143 | // array ends with comment, just break |
| 144 | break |
| 145 | } |
| 146 | if tok == tCOMMA { |
| 147 | // comma after comment, continue to next element |
| 148 | continue |
| 149 | } |
| 150 | // put back the token |
| 151 | p.nextPut(pos, tok, lit) |
| 152 | // continue loop - next iteration will parse the real literal |
| 153 | // and the comment will already be in 'e' from the recursive parse() call |
| 154 | continue |
| 155 | } |
| 156 | array = append(array, e) |
| 157 | _, tok, lit := p.next() |
| 158 | if tok == tCOMMA { |
| 159 | continue |
| 160 | } |
| 161 | if tok == tRIGHTSQUARE { |
| 162 | break |
| 163 | } |
| 164 | // handle comments inside arrays |
| 165 | if tok == tCOMMENT { |
| 166 | p.nextPut(pos, tok, lit) |
| 167 | continue |
| 168 | } |
| 169 | return p.unexpected(lit, ", or ]", l) |
| 170 | } |
| 171 | l.Array = array |
| 172 | l.IsString = false |
| 173 | l.Position = pos |
| 174 | return nil |
| 175 | } |
| 176 | if tLEFTCURLY == tok { |
| 177 | l.Position, l.Source, l.IsString = pos, "", false |
| 178 | constants, err := parseAggregateConstants(p, l) |
| 179 | if err != nil { |
| 180 | return nil |
| 181 | } |
| 182 | l.OrderedMap = LiteralMap(constants) |
| 183 | return nil |
| 184 | } |
| 185 | if "-" == lit { |
| 186 | // negative number |
| 187 | if err := l.parse(p); err != nil { |
| 188 | return err |
| 189 | } |
| 190 | // modify source and position |
| 191 | l.Position, l.Source = pos, "-"+l.Source |
| 192 | return nil |
| 193 | } |
| 194 | source := lit |
| 195 | iss := isString(lit) |
| 196 | if iss { |
| 197 | source, l.QuoteRune = unQuote(source) |
| 198 | } |
| 199 | l.Position, l.Source, l.IsString = pos, source, iss |
| 200 | |
| 201 | // peek for multiline strings |
| 202 | for { |
| 203 | pos, tok, lit := p.next() |
| 204 | if isString(lit) { |
| 205 | line, _ := unQuote(lit) |
| 206 | l.Source += line |
| 207 | } else { |
| 208 | p.nextPut(pos, tok, lit) |
| 209 | break |
| 210 | } |
| 211 | } |
| 212 | return nil |
| 213 | } |
| 214 | |
| 215 | // NamedLiteral associates a name with a Literal |
| 216 | type NamedLiteral struct { |
| 217 | *Literal |
| 218 | Name string |
| 219 | // PrintsColon is true when the Name must be printed with a colon suffix |
| 220 | PrintsColon bool |
| 221 | } |
| 222 | |
| 223 | // flatten the maps of each literal, recursively |
| 224 | // this func exists for deprecated Option.AggregatedConstants. |
| 225 | func collectAggregatedConstants(m map[string]*Literal) (list []*NamedLiteral) { |
| 226 | for k, v := range m { |
| 227 | if v.Map != nil { |
| 228 | sublist := collectAggregatedConstants(v.Map) |
| 229 | for _, each := range sublist { |
| 230 | list = append(list, &NamedLiteral{ |
| 231 | Name: k + "." + each.Name, |
| 232 | PrintsColon: true, |
| 233 | Literal: each.Literal, |
| 234 | }) |
| 235 | } |
| 236 | } else { |
| 237 | list = append(list, &NamedLiteral{ |
| 238 | Name: k, |
| 239 | PrintsColon: true, |
| 240 | Literal: v, |
| 241 | }) |
| 242 | } |
| 243 | } |
| 244 | // sort list by position of literal |
| 245 | sort.Sort(byPosition(list)) |
| 246 | return |
| 247 | } |
| 248 | |
| 249 | type byPosition []*NamedLiteral |
| 250 | |
| 251 | func (b byPosition) Less(i, j int) bool { |
| 252 | return b[i].Literal.Position.Line < b[j].Literal.Position.Line |
| 253 | } |
| 254 | func (b byPosition) Len() int { return len(b) } |
| 255 | func (b byPosition) Swap(i, j int) { b[i], b[j] = b[j], b[i] } |
| 256 | |
| 257 | func parseAggregateConstants(p *Parser, container interface{}) (list []*NamedLiteral, err error) { |
| 258 | for { |
| 259 | _, tok, lit := p.nextMessageLiteralFieldName() |
| 260 | // if tRIGHTSQUARE == tok { |
| 261 | // p.nextPut(pos, tok, lit) |
| 262 | // // caller has checked for open square ; will consume rightsquare, rightcurly and semicolon |
| 263 | // return |
| 264 | // } |
| 265 | if tRIGHTCURLY == tok { |
| 266 | return |
| 267 | } |
| 268 | if tSEMICOLON == tok { |
| 269 | // just consume it |
| 270 | continue |
| 271 | //return |
| 272 | } |
| 273 | if tCOMMENT == tok { |
| 274 | // assign to last parsed literal |
| 275 | // TODO: see TestUseOfSemicolonsInAggregatedConstants |
| 276 | continue |
| 277 | } |
| 278 | if tCOMMA == tok { |
| 279 | if len(list) == 0 { |
| 280 | err = p.unexpected(lit, "non-empty option aggregate key", container) |
| 281 | return |
| 282 | } |
| 283 | continue |
| 284 | } |
| 285 | if tIDENT != tok && !isKeyword(tok) { |
| 286 | err = p.unexpected(lit, "option aggregate key", container) |
| 287 | return |
| 288 | } |
| 289 | // workaround issue #59 TODO |
| 290 | if isString(lit) && len(list) > 0 { |
| 291 | // concatenate with previous constant |
| 292 | s, _ := unQuote(lit) |
| 293 | list[len(list)-1].Source += s |
| 294 | continue |
| 295 | } |
| 296 | key := lit |
| 297 | printsColon := false |
| 298 | // expect colon, aggregate or plain literal |
| 299 | pos, tok, lit := p.next() |
| 300 | if tCOLON == tok { |
| 301 | // consume it |
| 302 | printsColon = true |
| 303 | pos, tok, lit = p.next() |
| 304 | } |
| 305 | // see if nested aggregate is started |
| 306 | if tLEFTCURLY == tok { |
| 307 | nested, fault := parseAggregateConstants(p, container) |
| 308 | if fault != nil { |
| 309 | err = fault |
| 310 | return |
| 311 | } |
| 312 | |
| 313 | // create the map |
| 314 | m := map[string]*Literal{} |
| 315 | for _, each := range nested { |
| 316 | m[each.Name] = each.Literal |
| 317 | } |
| 318 | list = append(list, &NamedLiteral{ |
| 319 | Name: key, |
| 320 | PrintsColon: printsColon, |
| 321 | Literal: &Literal{Map: m, OrderedMap: LiteralMap(nested)}}) |
| 322 | continue |
| 323 | } |
| 324 | // no aggregate, put back token |
| 325 | p.nextPut(pos, tok, lit) |
| 326 | // now we see plain literal |
| 327 | l := new(Literal) |
| 328 | l.Position = pos |
| 329 | if err = l.parse(p); err != nil { |
| 330 | return |
| 331 | } |
| 332 | list = append(list, &NamedLiteral{Name: key, Literal: l, PrintsColon: printsColon}) |
| 333 | } |
| 334 | } |