github.com/tcnksm/go@v0.0.0-20141208075154-439b32936367/src/text/template/parse/lex.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package parse 6 7 import ( 8 "fmt" 9 "strings" 10 "unicode" 11 "unicode/utf8" 12 ) 13 14 // item represents a token or text string returned from the scanner. 15 type item struct { 16 typ itemType // The type of this item. 17 pos Pos // The starting position, in bytes, of this item in the input string. 18 val string // The value of this item. 19 } 20 21 func (i item) String() string { 22 switch { 23 case i.typ == itemEOF: 24 return "EOF" 25 case i.typ == itemError: 26 return i.val 27 case i.typ > itemKeyword: 28 return fmt.Sprintf("<%s>", i.val) 29 case len(i.val) > 10: 30 return fmt.Sprintf("%.10q...", i.val) 31 } 32 return fmt.Sprintf("%q", i.val) 33 } 34 35 // itemType identifies the type of lex items. 36 type itemType int 37 38 const ( 39 itemError itemType = iota // error occurred; value is text of error 40 itemBool // boolean constant 41 itemChar // printable ASCII character; grab bag for comma etc. 42 itemCharConstant // character constant 43 itemComplex // complex constant (1+2i); imaginary is just a number 44 itemColonEquals // colon-equals (':=') introducing a declaration 45 itemEOF 46 itemField // alphanumeric identifier starting with '.' 47 itemIdentifier // alphanumeric identifier not starting with '.' 48 itemLeftDelim // left action delimiter 49 itemLeftParen // '(' inside action 50 itemNumber // simple number, including imaginary 51 itemPipe // pipe symbol 52 itemRawString // raw quoted string (includes quotes) 53 itemRightDelim // right action delimiter 54 itemRightParen // ')' inside action 55 itemSpace // run of spaces separating arguments 56 itemString // quoted string (includes quotes) 57 itemText // plain text 58 itemVariable // variable starting with '$', such as '$' or '$1' or '$hello' 59 // Keywords appear after all the rest. 60 itemKeyword // used only to delimit the keywords 61 itemDot // the cursor, spelled '.' 62 itemDefine // define keyword 63 itemElse // else keyword 64 itemEnd // end keyword 65 itemIf // if keyword 66 itemNil // the untyped nil constant, easiest to treat as a keyword 67 itemRange // range keyword 68 itemTemplate // template keyword 69 itemWith // with keyword 70 ) 71 72 var key = map[string]itemType{ 73 ".": itemDot, 74 "define": itemDefine, 75 "else": itemElse, 76 "end": itemEnd, 77 "if": itemIf, 78 "range": itemRange, 79 "nil": itemNil, 80 "template": itemTemplate, 81 "with": itemWith, 82 } 83 84 const eof = -1 85 86 // stateFn represents the state of the scanner as a function that returns the next state. 87 type stateFn func(*lexer) stateFn 88 89 // lexer holds the state of the scanner. 90 type lexer struct { 91 name string // the name of the input; used only for error reports 92 input string // the string being scanned 93 leftDelim string // start of action 94 rightDelim string // end of action 95 state stateFn // the next lexing function to enter 96 pos Pos // current position in the input 97 start Pos // start position of this item 98 width Pos // width of last rune read from input 99 lastPos Pos // position of most recent item returned by nextItem 100 items chan item // channel of scanned items 101 parenDepth int // nesting depth of ( ) exprs 102 } 103 104 // next returns the next rune in the input. 105 func (l *lexer) next() rune { 106 if int(l.pos) >= len(l.input) { 107 l.width = 0 108 return eof 109 } 110 r, w := utf8.DecodeRuneInString(l.input[l.pos:]) 111 l.width = Pos(w) 112 l.pos += l.width 113 return r 114 } 115 116 // peek returns but does not consume the next rune in the input. 117 func (l *lexer) peek() rune { 118 r := l.next() 119 l.backup() 120 return r 121 } 122 123 // backup steps back one rune. Can only be called once per call of next. 124 func (l *lexer) backup() { 125 l.pos -= l.width 126 } 127 128 // emit passes an item back to the client. 129 func (l *lexer) emit(t itemType) { 130 l.items <- item{t, l.start, l.input[l.start:l.pos]} 131 l.start = l.pos 132 } 133 134 // ignore skips over the pending input before this point. 135 func (l *lexer) ignore() { 136 l.start = l.pos 137 } 138 139 // accept consumes the next rune if it's from the valid set. 140 func (l *lexer) accept(valid string) bool { 141 if strings.IndexRune(valid, l.next()) >= 0 { 142 return true 143 } 144 l.backup() 145 return false 146 } 147 148 // acceptRun consumes a run of runes from the valid set. 149 func (l *lexer) acceptRun(valid string) { 150 for strings.IndexRune(valid, l.next()) >= 0 { 151 } 152 l.backup() 153 } 154 155 // lineNumber reports which line we're on, based on the position of 156 // the previous item returned by nextItem. Doing it this way 157 // means we don't have to worry about peek double counting. 158 func (l *lexer) lineNumber() int { 159 return 1 + strings.Count(l.input[:l.lastPos], "\n") 160 } 161 162 // errorf returns an error token and terminates the scan by passing 163 // back a nil pointer that will be the next state, terminating l.nextItem. 164 func (l *lexer) errorf(format string, args ...interface{}) stateFn { 165 l.items <- item{itemError, l.start, fmt.Sprintf(format, args...)} 166 return nil 167 } 168 169 // nextItem returns the next item from the input. 170 func (l *lexer) nextItem() item { 171 item := <-l.items 172 l.lastPos = item.pos 173 return item 174 } 175 176 // lex creates a new scanner for the input string. 177 func lex(name, input, left, right string) *lexer { 178 if left == "" { 179 left = leftDelim 180 } 181 if right == "" { 182 right = rightDelim 183 } 184 l := &lexer{ 185 name: name, 186 input: input, 187 leftDelim: left, 188 rightDelim: right, 189 items: make(chan item), 190 } 191 go l.run() 192 return l 193 } 194 195 // run runs the state machine for the lexer. 196 func (l *lexer) run() { 197 for l.state = lexText; l.state != nil; { 198 l.state = l.state(l) 199 } 200 } 201 202 // state functions 203 204 const ( 205 leftDelim = "{{" 206 rightDelim = "}}" 207 leftComment = "/*" 208 rightComment = "*/" 209 ) 210 211 // lexText scans until an opening action delimiter, "{{". 212 func lexText(l *lexer) stateFn { 213 for { 214 if strings.HasPrefix(l.input[l.pos:], l.leftDelim) { 215 if l.pos > l.start { 216 l.emit(itemText) 217 } 218 return lexLeftDelim 219 } 220 if l.next() == eof { 221 break 222 } 223 } 224 // Correctly reached EOF. 225 if l.pos > l.start { 226 l.emit(itemText) 227 } 228 l.emit(itemEOF) 229 return nil 230 } 231 232 // lexLeftDelim scans the left delimiter, which is known to be present. 233 func lexLeftDelim(l *lexer) stateFn { 234 l.pos += Pos(len(l.leftDelim)) 235 if strings.HasPrefix(l.input[l.pos:], leftComment) { 236 return lexComment 237 } 238 l.emit(itemLeftDelim) 239 l.parenDepth = 0 240 return lexInsideAction 241 } 242 243 // lexComment scans a comment. The left comment marker is known to be present. 244 func lexComment(l *lexer) stateFn { 245 l.pos += Pos(len(leftComment)) 246 i := strings.Index(l.input[l.pos:], rightComment) 247 if i < 0 { 248 return l.errorf("unclosed comment") 249 } 250 l.pos += Pos(i + len(rightComment)) 251 if !strings.HasPrefix(l.input[l.pos:], l.rightDelim) { 252 return l.errorf("comment ends before closing delimiter") 253 254 } 255 l.pos += Pos(len(l.rightDelim)) 256 l.ignore() 257 return lexText 258 } 259 260 // lexRightDelim scans the right delimiter, which is known to be present. 261 func lexRightDelim(l *lexer) stateFn { 262 l.pos += Pos(len(l.rightDelim)) 263 l.emit(itemRightDelim) 264 return lexText 265 } 266 267 // lexInsideAction scans the elements inside action delimiters. 268 func lexInsideAction(l *lexer) stateFn { 269 // Either number, quoted string, or identifier. 270 // Spaces separate arguments; runs of spaces turn into itemSpace. 271 // Pipe symbols separate and are emitted. 272 if strings.HasPrefix(l.input[l.pos:], l.rightDelim) { 273 if l.parenDepth == 0 { 274 return lexRightDelim 275 } 276 return l.errorf("unclosed left paren") 277 } 278 switch r := l.next(); { 279 case r == eof || isEndOfLine(r): 280 return l.errorf("unclosed action") 281 case isSpace(r): 282 return lexSpace 283 case r == ':': 284 if l.next() != '=' { 285 return l.errorf("expected :=") 286 } 287 l.emit(itemColonEquals) 288 case r == '|': 289 l.emit(itemPipe) 290 case r == '"': 291 return lexQuote 292 case r == '`': 293 return lexRawQuote 294 case r == '$': 295 return lexVariable 296 case r == '\'': 297 return lexChar 298 case r == '.': 299 // special look-ahead for ".field" so we don't break l.backup(). 300 if l.pos < Pos(len(l.input)) { 301 r := l.input[l.pos] 302 if r < '0' || '9' < r { 303 return lexField 304 } 305 } 306 fallthrough // '.' can start a number. 307 case r == '+' || r == '-' || ('0' <= r && r <= '9'): 308 l.backup() 309 return lexNumber 310 case isAlphaNumeric(r): 311 l.backup() 312 return lexIdentifier 313 case r == '(': 314 l.emit(itemLeftParen) 315 l.parenDepth++ 316 return lexInsideAction 317 case r == ')': 318 l.emit(itemRightParen) 319 l.parenDepth-- 320 if l.parenDepth < 0 { 321 return l.errorf("unexpected right paren %#U", r) 322 } 323 return lexInsideAction 324 case r <= unicode.MaxASCII && unicode.IsPrint(r): 325 l.emit(itemChar) 326 return lexInsideAction 327 default: 328 return l.errorf("unrecognized character in action: %#U", r) 329 } 330 return lexInsideAction 331 } 332 333 // lexSpace scans a run of space characters. 334 // One space has already been seen. 335 func lexSpace(l *lexer) stateFn { 336 for isSpace(l.peek()) { 337 l.next() 338 } 339 l.emit(itemSpace) 340 return lexInsideAction 341 } 342 343 // lexIdentifier scans an alphanumeric. 344 func lexIdentifier(l *lexer) stateFn { 345 Loop: 346 for { 347 switch r := l.next(); { 348 case isAlphaNumeric(r): 349 // absorb. 350 default: 351 l.backup() 352 word := l.input[l.start:l.pos] 353 if !l.atTerminator() { 354 return l.errorf("bad character %#U", r) 355 } 356 switch { 357 case key[word] > itemKeyword: 358 l.emit(key[word]) 359 case word[0] == '.': 360 l.emit(itemField) 361 case word == "true", word == "false": 362 l.emit(itemBool) 363 default: 364 l.emit(itemIdentifier) 365 } 366 break Loop 367 } 368 } 369 return lexInsideAction 370 } 371 372 // lexField scans a field: .Alphanumeric. 373 // The . has been scanned. 374 func lexField(l *lexer) stateFn { 375 return lexFieldOrVariable(l, itemField) 376 } 377 378 // lexVariable scans a Variable: $Alphanumeric. 379 // The $ has been scanned. 380 func lexVariable(l *lexer) stateFn { 381 if l.atTerminator() { // Nothing interesting follows -> "$". 382 l.emit(itemVariable) 383 return lexInsideAction 384 } 385 return lexFieldOrVariable(l, itemVariable) 386 } 387 388 // lexVariable scans a field or variable: [.$]Alphanumeric. 389 // The . or $ has been scanned. 390 func lexFieldOrVariable(l *lexer, typ itemType) stateFn { 391 if l.atTerminator() { // Nothing interesting follows -> "." or "$". 392 if typ == itemVariable { 393 l.emit(itemVariable) 394 } else { 395 l.emit(itemDot) 396 } 397 return lexInsideAction 398 } 399 var r rune 400 for { 401 r = l.next() 402 if !isAlphaNumeric(r) { 403 l.backup() 404 break 405 } 406 } 407 if !l.atTerminator() { 408 return l.errorf("bad character %#U", r) 409 } 410 l.emit(typ) 411 return lexInsideAction 412 } 413 414 // atTerminator reports whether the input is at valid termination character to 415 // appear after an identifier. Breaks .X.Y into two pieces. Also catches cases 416 // like "$x+2" not being acceptable without a space, in case we decide one 417 // day to implement arithmetic. 418 func (l *lexer) atTerminator() bool { 419 r := l.peek() 420 if isSpace(r) || isEndOfLine(r) { 421 return true 422 } 423 switch r { 424 case eof, '.', ',', '|', ':', ')', '(': 425 return true 426 } 427 // Does r start the delimiter? This can be ambiguous (with delim=="//", $x/2 will 428 // succeed but should fail) but only in extremely rare cases caused by willfully 429 // bad choice of delimiter. 430 if rd, _ := utf8.DecodeRuneInString(l.rightDelim); rd == r { 431 return true 432 } 433 return false 434 } 435 436 // lexChar scans a character constant. The initial quote is already 437 // scanned. Syntax checking is done by the parser. 438 func lexChar(l *lexer) stateFn { 439 Loop: 440 for { 441 switch l.next() { 442 case '\\': 443 if r := l.next(); r != eof && r != '\n' { 444 break 445 } 446 fallthrough 447 case eof, '\n': 448 return l.errorf("unterminated character constant") 449 case '\'': 450 break Loop 451 } 452 } 453 l.emit(itemCharConstant) 454 return lexInsideAction 455 } 456 457 // lexNumber scans a number: decimal, octal, hex, float, or imaginary. This 458 // isn't a perfect number scanner - for instance it accepts "." and "0x0.2" 459 // and "089" - but when it's wrong the input is invalid and the parser (via 460 // strconv) will notice. 461 func lexNumber(l *lexer) stateFn { 462 if !l.scanNumber() { 463 return l.errorf("bad number syntax: %q", l.input[l.start:l.pos]) 464 } 465 if sign := l.peek(); sign == '+' || sign == '-' { 466 // Complex: 1+2i. No spaces, must end in 'i'. 467 if !l.scanNumber() || l.input[l.pos-1] != 'i' { 468 return l.errorf("bad number syntax: %q", l.input[l.start:l.pos]) 469 } 470 l.emit(itemComplex) 471 } else { 472 l.emit(itemNumber) 473 } 474 return lexInsideAction 475 } 476 477 func (l *lexer) scanNumber() bool { 478 // Optional leading sign. 479 l.accept("+-") 480 // Is it hex? 481 digits := "0123456789" 482 if l.accept("0") && l.accept("xX") { 483 digits = "0123456789abcdefABCDEF" 484 } 485 l.acceptRun(digits) 486 if l.accept(".") { 487 l.acceptRun(digits) 488 } 489 if l.accept("eE") { 490 l.accept("+-") 491 l.acceptRun("0123456789") 492 } 493 // Is it imaginary? 494 l.accept("i") 495 // Next thing mustn't be alphanumeric. 496 if isAlphaNumeric(l.peek()) { 497 l.next() 498 return false 499 } 500 return true 501 } 502 503 // lexQuote scans a quoted string. 504 func lexQuote(l *lexer) stateFn { 505 Loop: 506 for { 507 switch l.next() { 508 case '\\': 509 if r := l.next(); r != eof && r != '\n' { 510 break 511 } 512 fallthrough 513 case eof, '\n': 514 return l.errorf("unterminated quoted string") 515 case '"': 516 break Loop 517 } 518 } 519 l.emit(itemString) 520 return lexInsideAction 521 } 522 523 // lexRawQuote scans a raw quoted string. 524 func lexRawQuote(l *lexer) stateFn { 525 Loop: 526 for { 527 switch l.next() { 528 case eof, '\n': 529 return l.errorf("unterminated raw quoted string") 530 case '`': 531 break Loop 532 } 533 } 534 l.emit(itemRawString) 535 return lexInsideAction 536 } 537 538 // isSpace reports whether r is a space character. 539 func isSpace(r rune) bool { 540 return r == ' ' || r == '\t' 541 } 542 543 // isEndOfLine reports whether r is an end-of-line character. 544 func isEndOfLine(r rune) bool { 545 return r == '\r' || r == '\n' 546 } 547 548 // isAlphaNumeric reports whether r is an alphabetic, digit, or underscore. 549 func isAlphaNumeric(r rune) bool { 550 return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) 551 }