| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 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 caddyfile |
| 16 | |
| 17 | import ( |
| 18 | "errors" |
| 19 | "fmt" |
| 20 | "io" |
| 21 | "log" |
| 22 | "strconv" |
| 23 | "strings" |
| 24 | ) |
| 25 | |
| 26 | // Dispenser is a type that dispenses tokens, similarly to a lexer, |
| 27 | // except that it can do so with some notion of structure. An empty |
| 28 | // Dispenser is invalid; call NewDispenser to make a proper instance. |
| 29 | type Dispenser struct { |
| 30 | tokens []Token |
| 31 | cursor int |
| 32 | nesting int |
| 33 | |
| 34 | // A map of arbitrary context data that can be used |
| 35 | // to pass through some information to unmarshalers. |
| 36 | context map[string]any |
| 37 | } |
| 38 | |
| 39 | // NewDispenser returns a Dispenser filled with the given tokens. |
| 40 | func NewDispenser(tokens []Token) *Dispenser { |
| 41 | return &Dispenser{ |
| 42 | tokens: tokens, |
| 43 | cursor: -1, |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // NewTestDispenser parses input into tokens and creates a new |
| 48 | // Dispenser for test purposes only; any errors are fatal. |
| 49 | func NewTestDispenser(input string) *Dispenser { |
| 50 | tokens, err := allTokens("Testfile", []byte(input)) |
| 51 | if err != nil && err != io.EOF { |
| 52 | log.Fatalf("getting all tokens from input: %v", err) |
| 53 | } |
| 54 | return NewDispenser(tokens) |
| 55 | } |
| 56 | |
| 57 | // Next loads the next token. Returns true if a token |
| 58 | // was loaded; false otherwise. If false, all tokens |
| 59 | // have been consumed. |
| 60 | func (d *Dispenser) Next() bool { |
| 61 | if d.cursor < len(d.tokens)-1 { |
| 62 | d.cursor++ |
| 63 | return true |
| 64 | } |
| 65 | return false |
| 66 | } |
| 67 | |
| 68 | // Prev moves to the previous token. It does the inverse |
| 69 | // of Next(), except this function may decrement the cursor |
| 70 | // to -1 so that the next call to Next() points to the |
| 71 | // first token; this allows dispensing to "start over". This |
| 72 | // method returns true if the cursor ends up pointing to a |
| 73 | // valid token. |
| 74 | func (d *Dispenser) Prev() bool { |
| 75 | if d.cursor > -1 { |
| 76 | d.cursor-- |
| 77 | return d.cursor > -1 |
| 78 | } |
| 79 | return false |
| 80 | } |
| 81 | |
| 82 | // NextArg loads the next token if it is on the same |
| 83 | // line and if it is not a block opening (open curly |
| 84 | // brace). Returns true if an argument token was |
| 85 | // loaded; false otherwise. If false, all tokens on |
| 86 | // the line have been consumed except for potentially |
| 87 | // a block opening. It handles imported tokens |
| 88 | // correctly. |
| 89 | func (d *Dispenser) NextArg() bool { |
| 90 | if !d.nextOnSameLine() { |
| 91 | return false |
| 92 | } |
| 93 | if d.Val() == "{" { |
| 94 | // roll back; a block opening is not an argument |
| 95 | d.cursor-- |
| 96 | return false |
| 97 | } |
| 98 | return true |
| 99 | } |
| 100 | |
| 101 | // nextOnSameLine advances the cursor if the next |
| 102 | // token is on the same line of the same file. |
| 103 | func (d *Dispenser) nextOnSameLine() bool { |
| 104 | if d.cursor < 0 { |
| 105 | d.cursor++ |
| 106 | return true |
| 107 | } |
| 108 | if d.cursor >= len(d.tokens)-1 { |
| 109 | return false |
| 110 | } |
| 111 | curr := d.tokens[d.cursor] |
| 112 | next := d.tokens[d.cursor+1] |
| 113 | if !isNextOnNewLine(curr, next) { |
| 114 | d.cursor++ |
| 115 | return true |
| 116 | } |
| 117 | return false |
| 118 | } |
| 119 | |
| 120 | // NextLine loads the next token only if it is not on the same |
| 121 | // line as the current token, and returns true if a token was |
| 122 | // loaded; false otherwise. If false, there is not another token |
| 123 | // or it is on the same line. It handles imported tokens correctly. |
| 124 | func (d *Dispenser) NextLine() bool { |
| 125 | if d.cursor < 0 { |
| 126 | d.cursor++ |
| 127 | return true |
| 128 | } |
| 129 | if d.cursor >= len(d.tokens)-1 { |
| 130 | return false |
| 131 | } |
| 132 | curr := d.tokens[d.cursor] |
| 133 | next := d.tokens[d.cursor+1] |
| 134 | if isNextOnNewLine(curr, next) { |
| 135 | d.cursor++ |
| 136 | return true |
| 137 | } |
| 138 | return false |
| 139 | } |
| 140 | |
| 141 | // NextBlock can be used as the condition of a for loop |
| 142 | // to load the next token as long as it opens a block or |
| 143 | // is already in a block nested more than initialNestingLevel. |
| 144 | // In other words, a loop over NextBlock() will iterate |
| 145 | // all tokens in the block assuming the next token is an |
| 146 | // open curly brace, until the matching closing brace. |
| 147 | // The open and closing brace tokens for the outer-most |
| 148 | // block will be consumed internally and omitted from |
| 149 | // the iteration. |
| 150 | // |
| 151 | // Proper use of this method looks like this: |
| 152 | // |
| 153 | // for nesting := d.Nesting(); d.NextBlock(nesting); { |
| 154 | // } |
| 155 | // |
| 156 | // However, in simple cases where it is known that the |
| 157 | // Dispenser is new and has not already traversed state |
| 158 | // by a loop over NextBlock(), this will do: |
| 159 | // |
| 160 | // for d.NextBlock(0) { |
| 161 | // } |
| 162 | // |
| 163 | // As with other token parsing logic, a loop over |
| 164 | // NextBlock() should be contained within a loop over |
| 165 | // Next(), as it is usually prudent to skip the initial |
| 166 | // token. |
| 167 | func (d *Dispenser) NextBlock(initialNestingLevel int) bool { |
| 168 | if d.nesting > initialNestingLevel { |
| 169 | if !d.Next() { |
| 170 | return false // should be EOF error |
| 171 | } |
| 172 | if d.Val() == "}" && !d.nextOnSameLine() { |
| 173 | d.nesting-- |
| 174 | } else if d.Val() == "{" && !d.nextOnSameLine() { |
| 175 | d.nesting++ |
| 176 | } |
| 177 | return d.nesting > initialNestingLevel |
| 178 | } |
| 179 | if !d.nextOnSameLine() { // block must open on same line |
| 180 | return false |
| 181 | } |
| 182 | if d.Val() != "{" { |
| 183 | d.cursor-- // roll back if not opening brace |
| 184 | return false |
| 185 | } |
| 186 | d.Next() // consume open curly brace |
| 187 | if d.Val() == "}" { |
| 188 | return false // open and then closed right away |
| 189 | } |
| 190 | d.nesting++ |
| 191 | return true |
| 192 | } |
| 193 | |
| 194 | // Nesting returns the current nesting level. Necessary |
| 195 | // if using NextBlock() |
| 196 | func (d *Dispenser) Nesting() int { |
| 197 | return d.nesting |
| 198 | } |
| 199 | |
| 200 | // Val gets the text of the current token. If there is no token |
| 201 | // loaded, it returns empty string. |
| 202 | func (d *Dispenser) Val() string { |
| 203 | if d.cursor < 0 || d.cursor >= len(d.tokens) { |
| 204 | return "" |
| 205 | } |
| 206 | return d.tokens[d.cursor].Text |
| 207 | } |
| 208 | |
| 209 | // ValRaw gets the raw text of the current token (including quotes). |
| 210 | // If the token was a heredoc, then the delimiter is not included, |
| 211 | // because that is not relevant to any unmarshaling logic at this time. |
| 212 | // If there is no token loaded, it returns empty string. |
| 213 | func (d *Dispenser) ValRaw() string { |
| 214 | if d.cursor < 0 || d.cursor >= len(d.tokens) { |
| 215 | return "" |
| 216 | } |
| 217 | quote := d.tokens[d.cursor].wasQuoted |
| 218 | if quote > 0 && quote != '<' { |
| 219 | // string literal |
| 220 | return string(quote) + d.tokens[d.cursor].Text + string(quote) |
| 221 | } |
| 222 | return d.tokens[d.cursor].Text |
| 223 | } |
| 224 | |
| 225 | // ScalarVal gets value of the current token, converted to the closest |
| 226 | // scalar type. If there is no token loaded, it returns nil. |
| 227 | func (d *Dispenser) ScalarVal() any { |
| 228 | if d.cursor < 0 || d.cursor >= len(d.tokens) { |
| 229 | return nil |
| 230 | } |
| 231 | quote := d.tokens[d.cursor].wasQuoted |
| 232 | text := d.tokens[d.cursor].Text |
| 233 | |
| 234 | if quote > 0 { |
| 235 | return text // string literal |
| 236 | } |
| 237 | if num, err := strconv.Atoi(text); err == nil { |
| 238 | return num |
| 239 | } |
| 240 | if num, err := strconv.ParseFloat(text, 64); err == nil { |
| 241 | return num |
| 242 | } |
| 243 | if bool, err := strconv.ParseBool(text); err == nil { |
| 244 | return bool |
| 245 | } |
| 246 | return text |
| 247 | } |
| 248 | |
| 249 | // Line gets the line number of the current token. |
| 250 | // If there is no token loaded, it returns 0. |
| 251 | func (d *Dispenser) Line() int { |
| 252 | if d.cursor < 0 || d.cursor >= len(d.tokens) { |
| 253 | return 0 |
| 254 | } |
| 255 | return d.tokens[d.cursor].Line |
| 256 | } |
| 257 | |
| 258 | // File gets the filename where the current token originated. |
| 259 | func (d *Dispenser) File() string { |
| 260 | if d.cursor < 0 || d.cursor >= len(d.tokens) { |
| 261 | return "" |
| 262 | } |
| 263 | return d.tokens[d.cursor].File |
| 264 | } |
| 265 | |
| 266 | // Args is a convenience function that loads the next arguments |
| 267 | // (tokens on the same line) into an arbitrary number of strings |
| 268 | // pointed to in targets. If there are not enough argument tokens |
| 269 | // available to fill targets, false is returned and the remaining |
| 270 | // targets are left unchanged. If all the targets are filled, |
| 271 | // then true is returned. |
| 272 | func (d *Dispenser) Args(targets ...*string) bool { |
| 273 | for i := range targets { |
| 274 | if !d.NextArg() { |
| 275 | return false |
| 276 | } |
| 277 | *targets[i] = d.Val() |
| 278 | } |
| 279 | return true |
| 280 | } |
| 281 | |
| 282 | // AllArgs is like Args, but if there are more argument tokens |
| 283 | // available than there are targets, false is returned. The |
| 284 | // number of available argument tokens must match the number of |
| 285 | // targets exactly to return true. |
| 286 | func (d *Dispenser) AllArgs(targets ...*string) bool { |
| 287 | if !d.Args(targets...) { |
| 288 | return false |
| 289 | } |
| 290 | if d.NextArg() { |
| 291 | d.Prev() |
| 292 | return false |
| 293 | } |
| 294 | return true |
| 295 | } |
| 296 | |
| 297 | // CountRemainingArgs counts the amount of remaining arguments |
| 298 | // (tokens on the same line) without consuming the tokens. |
| 299 | func (d *Dispenser) CountRemainingArgs() int { |
| 300 | count := 0 |
| 301 | for d.NextArg() { |
| 302 | count++ |
| 303 | } |
| 304 | for i := 0; i < count; i++ { |
| 305 | d.Prev() |
| 306 | } |
| 307 | return count |
| 308 | } |
| 309 | |
| 310 | // RemainingArgs loads any more arguments (tokens on the same line) |
| 311 | // into a slice of strings and returns them. Open curly brace tokens |
| 312 | // also indicate the end of arguments, and the curly brace is not |
| 313 | // included in the return value nor is it loaded. |
| 314 | func (d *Dispenser) RemainingArgs() []string { |
| 315 | var args []string |
| 316 | for d.NextArg() { |
| 317 | args = append(args, d.Val()) |
| 318 | } |
| 319 | return args |
| 320 | } |
| 321 | |
| 322 | // RemainingArgsRaw loads any more arguments (tokens on the same line, |
| 323 | // retaining quotes) into a slice of strings and returns them. |
| 324 | // Open curly brace tokens also indicate the end of arguments, |
| 325 | // and the curly brace is not included in the return value nor is it loaded. |
| 326 | func (d *Dispenser) RemainingArgsRaw() []string { |
| 327 | var args []string |
| 328 | for d.NextArg() { |
| 329 | args = append(args, d.ValRaw()) |
| 330 | } |
| 331 | return args |
| 332 | } |
| 333 | |
| 334 | // RemainingArgsAsTokens loads any more arguments (tokens on the same line) |
| 335 | // into a slice of Token-structs and returns them. Open curly brace tokens |
| 336 | // also indicate the end of arguments, and the curly brace is not included |
| 337 | // in the return value nor is it loaded. |
| 338 | func (d *Dispenser) RemainingArgsAsTokens() []Token { |
| 339 | var args []Token |
| 340 | for d.NextArg() { |
| 341 | args = append(args, d.Token()) |
| 342 | } |
| 343 | return args |
| 344 | } |
| 345 | |
| 346 | // NewFromNextSegment returns a new dispenser with a copy of |
| 347 | // the tokens from the current token until the end of the |
| 348 | // "directive" whether that be to the end of the line or |
| 349 | // the end of a block that starts at the end of the line; |
| 350 | // in other words, until the end of the segment. |
| 351 | func (d *Dispenser) NewFromNextSegment() *Dispenser { |
| 352 | return NewDispenser(d.NextSegment()) |
| 353 | } |
| 354 | |
| 355 | // NextSegment returns a copy of the tokens from the current |
| 356 | // token until the end of the line or block that starts at |
| 357 | // the end of the line. |
| 358 | func (d *Dispenser) NextSegment() Segment { |
| 359 | tkns := Segment{d.Token()} |
| 360 | for d.NextArg() { |
| 361 | tkns = append(tkns, d.Token()) |
| 362 | } |
| 363 | var openedBlock bool |
| 364 | for nesting := d.Nesting(); d.NextBlock(nesting); { |
| 365 | if !openedBlock { |
| 366 | // because NextBlock() consumes the initial open |
| 367 | // curly brace, we rewind here to append it, since |
| 368 | // our case is special in that we want the new |
| 369 | // dispenser to have all the tokens including |
| 370 | // surrounding curly braces |
| 371 | d.Prev() |
| 372 | tkns = append(tkns, d.Token()) |
| 373 | d.Next() |
| 374 | openedBlock = true |
| 375 | } |
| 376 | tkns = append(tkns, d.Token()) |
| 377 | } |
| 378 | if openedBlock { |
| 379 | // include closing brace |
| 380 | tkns = append(tkns, d.Token()) |
| 381 | |
| 382 | // do not consume the closing curly brace; the |
| 383 | // next iteration of the enclosing loop will |
| 384 | // call Next() and consume it |
| 385 | } |
| 386 | return tkns |
| 387 | } |
| 388 | |
| 389 | // Token returns the current token. |
| 390 | func (d *Dispenser) Token() Token { |
| 391 | if d.cursor < 0 || d.cursor >= len(d.tokens) { |
| 392 | return Token{} |
| 393 | } |
| 394 | return d.tokens[d.cursor] |
| 395 | } |
| 396 | |
| 397 | // Reset sets d's cursor to the beginning, as |
| 398 | // if this was a new and unused dispenser. |
| 399 | func (d *Dispenser) Reset() { |
| 400 | d.cursor = -1 |
| 401 | d.nesting = 0 |
| 402 | } |
| 403 | |
| 404 | // ArgErr returns an argument error, meaning that another |
| 405 | // argument was expected but not found. In other words, |
| 406 | // a line break or open curly brace was encountered instead of |
| 407 | // an argument. |
| 408 | func (d *Dispenser) ArgErr() error { |
| 409 | if d.Val() == "{" { |
| 410 | return d.Err("unexpected token '{', expecting argument") |
| 411 | } |
| 412 | return d.Errf("wrong argument count or unexpected line ending after '%s'", d.Val()) |
| 413 | } |
| 414 | |
| 415 | // SyntaxErr creates a generic syntax error which explains what was |
| 416 | // found and what was expected. |
| 417 | func (d *Dispenser) SyntaxErr(expected string) error { |
| 418 | msg := fmt.Sprintf("syntax error: unexpected token '%s', expecting '%s', at %s:%d import chain: ['%s']", d.Val(), expected, d.File(), d.Line(), strings.Join(d.Token().imports, "','")) |
| 419 | return errors.New(msg) |
| 420 | } |
| 421 | |
| 422 | // EOFErr returns an error indicating that the dispenser reached |
| 423 | // the end of the input when searching for the next token. |
| 424 | func (d *Dispenser) EOFErr() error { |
| 425 | return d.Errf("unexpected EOF") |
| 426 | } |
| 427 | |
| 428 | // Err generates a custom parse-time error with a message of msg. |
| 429 | func (d *Dispenser) Err(msg string) error { |
| 430 | return d.WrapErr(errors.New(msg)) |
| 431 | } |
| 432 | |
| 433 | // Errf is like Err, but for formatted error messages |
| 434 | func (d *Dispenser) Errf(format string, args ...any) error { |
| 435 | return d.WrapErr(fmt.Errorf(format, args...)) |
| 436 | } |
| 437 | |
| 438 | // WrapErr takes an existing error and adds the Caddyfile file and line number. |
| 439 | func (d *Dispenser) WrapErr(err error) error { |
| 440 | if len(d.Token().imports) > 0 { |
| 441 | return fmt.Errorf("%w, at %s:%d import chain ['%s']", err, d.File(), d.Line(), strings.Join(d.Token().imports, "','")) |
| 442 | } |
| 443 | return fmt.Errorf("%w, at %s:%d", err, d.File(), d.Line()) |
| 444 | } |
| 445 | |
| 446 | // Delete deletes the current token and returns the updated slice |
| 447 | // of tokens. The cursor is not advanced to the next token. |
| 448 | // Because deletion modifies the underlying slice, this method |
| 449 | // should only be called if you have access to the original slice |
| 450 | // of tokens and/or are using the slice of tokens outside this |
| 451 | // Dispenser instance. If you do not re-assign the slice with the |
| 452 | // return value of this method, inconsistencies in the token |
| 453 | // array will become apparent (or worse, hide from you like they |
| 454 | // did me for 3 and a half freaking hours late one night). |
| 455 | func (d *Dispenser) Delete() []Token { |
| 456 | if d.cursor >= 0 && d.cursor <= len(d.tokens)-1 { |
| 457 | d.tokens = append(d.tokens[:d.cursor], d.tokens[d.cursor+1:]...) |
| 458 | d.cursor-- |
| 459 | } |
| 460 | return d.tokens |
| 461 | } |
| 462 | |
| 463 | // DeleteN is the same as Delete, but can delete many tokens at once. |
| 464 | // If there aren't N tokens available to delete, none are deleted. |
| 465 | func (d *Dispenser) DeleteN(amount int) []Token { |
| 466 | if amount > 0 && d.cursor >= (amount-1) && d.cursor <= len(d.tokens)-1 { |
| 467 | d.tokens = append(d.tokens[:d.cursor-(amount-1)], d.tokens[d.cursor+1:]...) |
| 468 | d.cursor -= amount |
| 469 | } |
| 470 | return d.tokens |
| 471 | } |
| 472 | |
| 473 | // SetContext sets a key-value pair in the context map. |
| 474 | func (d *Dispenser) SetContext(key string, value any) { |
| 475 | if d.context == nil { |
| 476 | d.context = make(map[string]any) |
| 477 | } |
| 478 | d.context[key] = value |
| 479 | } |
| 480 | |
| 481 | // GetContext gets the value of a key in the context map. |
| 482 | func (d *Dispenser) GetContext(key string) any { |
| 483 | if d.context == nil { |
| 484 | return nil |
| 485 | } |
| 486 | return d.context[key] |
| 487 | } |
| 488 | |
| 489 | // GetContextString gets the value of a key in the context map |
| 490 | // as a string, or an empty string if the key does not exist. |
| 491 | func (d *Dispenser) GetContextString(key string) string { |
| 492 | if d.context == nil { |
| 493 | return "" |
| 494 | } |
| 495 | if val, ok := d.context[key].(string); ok { |
| 496 | return val |
| 497 | } |
| 498 | return "" |
| 499 | } |
| 500 | |
| 501 | // isNewLine determines whether the current token is on a different |
| 502 | // line (higher line number) than the previous token. It handles imported |
| 503 | // tokens correctly. If there isn't a previous token, it returns true. |
| 504 | func (d *Dispenser) isNewLine() bool { |
| 505 | if d.cursor < 1 { |
| 506 | return true |
| 507 | } |
| 508 | if d.cursor > len(d.tokens)-1 { |
| 509 | return false |
| 510 | } |
| 511 | |
| 512 | prev := d.tokens[d.cursor-1] |
| 513 | curr := d.tokens[d.cursor] |
| 514 | return isNextOnNewLine(prev, curr) |
| 515 | } |
| 516 | |
| 517 | // isNextOnNewLine determines whether the current token is on a different |
| 518 | // line (higher line number) than the next token. It handles imported |
| 519 | // tokens correctly. If there isn't a next token, it returns true. |
| 520 | func (d *Dispenser) isNextOnNewLine() bool { |
| 521 | if d.cursor < 0 { |
| 522 | return false |
| 523 | } |
| 524 | if d.cursor >= len(d.tokens)-1 { |
| 525 | return true |
| 526 | } |
| 527 | |
| 528 | curr := d.tokens[d.cursor] |
| 529 | next := d.tokens[d.cursor+1] |
| 530 | return isNextOnNewLine(curr, next) |
| 531 | } |
| 532 | |
| 533 | const MatcherNameCtxKey = "matcher_name" |