// Copyright 2009 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.
// Package scanner implements a scanner for Go source text.// It takes a []byte as source which can then be tokenized// through repeated calls to the Scan method.
package scannerimport ()// An ErrorHandler may be provided to [Scanner.Init]. If a syntax error is// encountered and a handler was installed, the handler is called with a// position and an error message. The position points to the beginning of// the offending token.typeErrorHandlerfunc(pos token.Position, msg string)// A Scanner holds the scanner's internal state while processing// a given text. It can be allocated as part of another data// structure but must be initialized via [Scanner.Init] before use.typeScannerstruct {// immutable state file *token.File// source file handle dir string// directory portion of file.Name() src []byte// source err ErrorHandler// error reporting; or nil mode Mode// scanning mode// scanning state ch rune// current character offset int// character offset rdOffset int// reading offset (position after current character) lineOffset int// current line offset insertSemi bool// insert a semicolon before next newline nlPos token.Pos// position of newline in preceding comment// public state - ok to modify ErrorCount int// number of errors encountered}const ( bom = 0xFEFF// byte order mark, only permitted as very first character eof = -1// end of file)// Read the next Unicode char into s.ch.// s.ch < 0 means end-of-file.//// For optimization, there is some overlap between this method and// s.scanIdentifier.func ( *Scanner) () {if .rdOffset < len(.src) { .offset = .rdOffsetif .ch == '\n' { .lineOffset = .offset .file.AddLine(.offset) } , := rune(.src[.rdOffset]), 1switch {case == 0: .error(.offset, "illegal character NUL")case >= utf8.RuneSelf:// not ASCII , = utf8.DecodeRune(.src[.rdOffset:])if == utf8.RuneError && == 1 { .error(.offset, "illegal UTF-8 encoding") } elseif == bom && .offset > 0 { .error(.offset, "illegal byte order mark") } } .rdOffset += .ch = } else { .offset = len(.src)if .ch == '\n' { .lineOffset = .offset .file.AddLine(.offset) } .ch = eof }}// peek returns the byte following the most recently read character without// advancing the scanner. If the scanner is at EOF, peek returns 0.func ( *Scanner) () byte {if .rdOffset < len(.src) {return .src[.rdOffset] }return0}// A mode value is a set of flags (or 0).// They control scanner behavior.typeModeuintconst (ScanCommentsMode = 1 << iota// return comments as COMMENT tokens dontInsertSemis // do not automatically insert semicolons - for testing only)// Init prepares the scanner s to tokenize the text src by setting the// scanner at the beginning of src. The scanner uses the file set file// for position information and it adds line information for each line.// It is ok to re-use the same file when re-scanning the same file as// line information which is already present is ignored. Init causes a// panic if the file size does not match the src size.//// Calls to [Scanner.Scan] will invoke the error handler err if they encounter a// syntax error and err is not nil. Also, for each error encountered,// the [Scanner] field ErrorCount is incremented by one. The mode parameter// determines how comments are handled.//// Note that Init may call err if there is an error in the first character// of the file.func ( *Scanner) ( *token.File, []byte, ErrorHandler, Mode) {// Explicitly initialize all fields since a scanner may be reused.if .Size() != len() {panic(fmt.Sprintf("file size (%d) does not match src len (%d)", .Size(), len())) } .file = .dir, _ = filepath.Split(.Name()) .src = .err = .mode = .ch = ' ' .offset = 0 .rdOffset = 0 .lineOffset = 0 .insertSemi = false .ErrorCount = 0 .next()if .ch == bom { .next() // ignore BOM at file beginning }}func ( *Scanner) ( int, string) {if .err != nil { .err(.file.Position(.file.Pos()), ) } .ErrorCount++}func ( *Scanner) ( int, string, ...any) { .error(, fmt.Sprintf(, ...))}// scanComment returns the text of the comment and (if nonzero)// the offset of the first newline within it, which implies a// /*...*/ comment.func ( *Scanner) () (string, int) {// initial '/' already consumed; s.ch == '/' || s.ch == '*' := .offset - 1// position of initial '/' := -1// position immediately following the comment; < 0 means invalid comment := 0 := 0// offset of first newline within /*...*/ commentif .ch == '/' {//-style comment // (the final '\n' is not considered part of the comment) .next()for .ch != '\n' && .ch >= 0 {if .ch == '\r' { ++ } .next() }// if we are at '\n', the position following the comment is afterwards = .offsetif .ch == '\n' { ++ }goto }/*-style comment */ .next()for .ch >= 0 { := .chif == '\r' { ++ } elseif == '\n' && == 0 { = .offset } .next()if == '*' && .ch == '/' { .next() = .offsetgoto } } .error(, "comment not terminated"): := .src[:.offset]// On Windows, a (//-comment) line may end in "\r\n". // Remove the final '\r' before analyzing the text for // line directives (matching the compiler). Remove any // other '\r' afterwards (matching the pre-existing be- // havior of the scanner).if > 0 && len() >= 2 && [1] == '/' && [len()-1] == '\r' { = [:len()-1] -- }// interpret line directives // (//line directives must start at the beginning of the current line)if >= 0/* implies valid comment */ && ([1] == '*' || == .lineOffset) && bytes.HasPrefix([2:], prefix) { .updateLineInfo(, , ) }if > 0 { = stripCR(, [1] == '*') }returnstring(), }var prefix = []byte("line ")// updateLineInfo parses the incoming comment text at offset offs// as a line directive. If successful, it updates the line info table// for the position next per the line directive.func ( *Scanner) (, int, []byte) {// extract comment textif [1] == '*' { = [:len()-2] // lop off trailing "*/" } = [7:] // lop off leading "//line " or "/*line " += 7 , , := trailingDigits()if == 0 {return// ignore (not a line directive) }// i > 0if ! {// text has a suffix :xxx but xxx is not a number .error(+, "invalid line number: "+string([:]))return }// Put a cap on the maximum size of line and column numbers. // 30 bits allows for some additional space before wrapping an int32. // Keep this consistent with cmd/compile/internal/syntax.PosMax.const = 1 << 30var , int , , := trailingDigits([:-1])if {//line filename:line:col , = , , = , if == 0 || > { .error(+, "invalid column number: "+string([:]))return } = [:-1] // lop off ":col" } else {//line filename:line = }if == 0 || > { .error(+, "invalid line number: "+string([:]))return }// If we have a column (//line filename:line:col form), // an empty filename means to use the previous filename. := string([:-1]) // lop off ":line", and trim white spaceif == "" && { = .file.Position(.file.Pos()).Filename } elseif != "" {// Put a relative filename in the current directory. // This is for compatibility with earlier releases. // See issue 26671. = filepath.Clean()if !filepath.IsAbs() { = filepath.Join(.dir, ) } } .file.AddLineColumnInfo(, , , )}func trailingDigits( []byte) (int, int, bool) { := bytes.LastIndexByte(, ':') // look from right (Windows filenames may contain ':')if < 0 {return0, 0, false// no ":" }// i >= 0 , := strconv.ParseUint(string([+1:]), 10, 0)return + 1, int(), == nil}func isLetter( rune) bool {return'a' <= lower() && lower() <= 'z' || == '_' || >= utf8.RuneSelf && unicode.IsLetter()}func isDigit( rune) bool {returnisDecimal() || >= utf8.RuneSelf && unicode.IsDigit()}// scanIdentifier reads the string of valid identifier characters at s.offset.// It must only be called when s.ch is known to be a valid letter.//// Be careful when making changes to this function: it is optimized and affects// scanning performance significantly.func ( *Scanner) () string { := .offset// Optimize for the common case of an ASCII identifier. // // Ranging over s.src[s.rdOffset:] lets us avoid some bounds checks, and // avoids conversions to runes. // // In case we encounter a non-ASCII character, fall back on the slower path // of calling into s.next().for , := range .src[.rdOffset:] {if'a' <= && <= 'z' || 'A' <= && <= 'Z' || == '_' || '0' <= && <= '9' {// Avoid assigning a rune for the common case of an ascii character.continue } .rdOffset += if0 < && < utf8.RuneSelf {// Optimization: we've encountered an ASCII character that's not a letter // or number. Avoid the call into s.next() and corresponding set up. // // Note that s.next() does some line accounting if s.ch is '\n', so this // shortcut is only possible because we know that the preceding character // is not '\n'. .ch = rune() .offset = .rdOffset .rdOffset++goto }// We know that the preceding character is valid for an identifier because // scanIdentifier is only called when s.ch is a letter, so calling s.next() // at s.rdOffset resets the scanner state. .next()forisLetter(.ch) || isDigit(.ch) { .next() }goto } .offset = len(.src) .rdOffset = len(.src) .ch = eof:returnstring(.src[:.offset])}func digitVal( rune) int {switch {case'0' <= && <= '9':returnint( - '0')case'a' <= lower() && lower() <= 'f':returnint(lower() - 'a' + 10) }return16// larger than any legal digit val}func lower( rune) rune { return ('a' - 'A') | } // returns lower-case ch iff ch is ASCII letterfunc isDecimal( rune) bool { return'0' <= && <= '9' }func isHex( rune) bool { return'0' <= && <= '9' || 'a' <= lower() && lower() <= 'f' }// digits accepts the sequence { digit | '_' }.// If base <= 10, digits accepts any decimal digit but records// the offset (relative to the source start) of a digit >= base// in *invalid, if *invalid < 0.// digits returns a bitset describing whether the sequence contained// digits (bit 0 is set), or separators '_' (bit 1 is set).func ( *Scanner) ( int, *int) ( int) {if <= 10 { := rune('0' + )forisDecimal(.ch) || .ch == '_' { := 1if .ch == '_' { = 2 } elseif .ch >= && * < 0 { * = .offset// record invalid rune offset } |= .next() } } else {forisHex(.ch) || .ch == '_' { := 1if .ch == '_' { = 2 } |= .next() } }return}func ( *Scanner) () (token.Token, string) { := .offset := token.ILLEGAL := 10// number base := rune(0) // one of 0 (decimal), '0' (0-octal), 'x', 'o', or 'b' := 0// bit 0: digit present, bit 1: '_' present := -1// index of invalid digit in literal, or < 0// integer partif .ch != '.' { = token.INTif .ch == '0' { .next()switchlower(.ch) {case'x': .next() , = 16, 'x'case'o': .next() , = 8, 'o'case'b': .next() , = 2, 'b'default: , = 8, '0' = 1// leading 0 } } |= .digits(, &) }// fractional partif .ch == '.' { = token.FLOATif == 'o' || == 'b' { .error(.offset, "invalid radix point in "+litname()) } .next() |= .digits(, &) }if &1 == 0 { .error(.offset, litname()+" has no digits") }// exponentif := lower(.ch); == 'e' || == 'p' {switch {case == 'e' && != 0 && != '0': .errorf(.offset, "%q exponent requires decimal mantissa", .ch)case == 'p' && != 'x': .errorf(.offset, "%q exponent requires hexadecimal mantissa", .ch) } .next() = token.FLOATif .ch == '+' || .ch == '-' { .next() } := .digits(10, nil) |= if &1 == 0 { .error(.offset, "exponent has no digits") } } elseif == 'x' && == token.FLOAT { .error(.offset, "hexadecimal mantissa requires a 'p' exponent") }// suffix 'i'if .ch == 'i' { = token.IMAG .next() } := string(.src[:.offset])if == token.INT && >= 0 { .errorf(, "invalid digit %q in %s", [-], litname()) }if &2 != 0 {if := invalidSep(); >= 0 { .error(+, "'_' must separate successive digits") } }return , }func litname( rune) string {switch {case'x':return"hexadecimal literal"case'o', '0':return"octal literal"case'b':return"binary literal" }return"decimal literal"}// invalidSep returns the index of the first invalid separator in x, or -1.func invalidSep( string) int { := ' '// prefix char, we only care if it's 'x' := '.'// digit, one of '_', '0' (a digit), or '.' (anything else) := 0// a prefix counts as a digitiflen() >= 2 && [0] == '0' { = lower(rune([1]))if == 'x' || == 'o' || == 'b' { = '0' = 2 } }// mantissa and exponentfor ; < len(); ++ { := // previous digit = rune([])switch {case == '_':if != '0' {return }caseisDecimal() || == 'x' && isHex(): = '0'default:if == '_' {return - 1 } = '.' } }if == '_' {returnlen() - 1 }return -1}// scanEscape parses an escape sequence where rune is the accepted// escaped quote. In case of a syntax error, it stops at the offending// character (without consuming it) and returns false. Otherwise// it returns true.func ( *Scanner) ( rune) bool { := .offsetvarintvar , uint32switch .ch {case'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', : .next()returntruecase'0', '1', '2', '3', '4', '5', '6', '7': , , = 3, 8, 255case'x': .next() , , = 2, 16, 255case'u': .next() , , = 4, 16, unicode.MaxRunecase'U': .next() , , = 8, 16, unicode.MaxRunedefault: := "unknown escape sequence"if .ch < 0 { = "escape sequence not terminated" } .error(, )returnfalse }varuint32for > 0 { := uint32(digitVal(.ch))if >= { := fmt.Sprintf("illegal character %#U in escape sequence", .ch)if .ch < 0 { = "escape sequence not terminated" } .error(.offset, )returnfalse } = * + .next() -- }if > || 0xD800 <= && < 0xE000 { .error(, "escape sequence is invalid Unicode code point")returnfalse }returntrue}func ( *Scanner) () string {// '\'' opening already consumed := .offset - 1 := true := 0for { := .chif == '\n' || < 0 {// only report error if we don't have one alreadyif { .error(, "rune literal not terminated") = false }break } .next()if == '\'' {break } ++if == '\\' {if !.scanEscape('\'') { = false }// continue to read to closing quote } }if && != 1 { .error(, "illegal rune literal") }returnstring(.src[:.offset])}func ( *Scanner) () string {// '"' opening already consumed := .offset - 1for { := .chif == '\n' || < 0 { .error(, "string literal not terminated")break } .next()if == '"' {break }if == '\\' { .scanEscape('"') } }returnstring(.src[:.offset])}func stripCR( []byte, bool) []byte { := make([]byte, len()) := 0for , := range {// In a /*-style comment, don't strip \r from *\r/ (incl. // sequences of \r from *\r\r...\r/) since the resulting // */ would terminate the comment too early unless the \r // is immediately following the opening /* in which case // it's ok because /*/ is not closed yet (issue #11151).if != '\r' || && > len("/*") && [-1] == '*' && +1 < len() && [+1] == '/' { [] = ++ } }return [:]}func ( *Scanner) () string {// '`' opening already consumed := .offset - 1 := falsefor { := .chif < 0 { .error(, "raw string literal not terminated")break } .next()if == '`' {break }if == '\r' { = true } } := .src[:.offset]if { = stripCR(, false) }returnstring()}func ( *Scanner) () {for .ch == ' ' || .ch == '\t' || .ch == '\n' && !.insertSemi || .ch == '\r' { .next() }}// Helper functions for scanning multi-byte tokens such as >> += >>= .// Different routines recognize different length tok_i based on matches// of ch_i. If a token ends in '=', the result is tok1 or tok3// respectively. Otherwise, the result is tok0 if there was no other// matching character, or tok2 if the matching character was ch2.func ( *Scanner) (, token.Token) token.Token {if .ch == '=' { .next()return }return}func ( *Scanner) (, token.Token, rune, token.Token) token.Token {if .ch == '=' { .next()return }if .ch == { .next()return }return}func ( *Scanner) (, token.Token, rune, , token.Token) token.Token {if .ch == '=' { .next()return }if .ch == { .next()if .ch == '=' { .next()return }return }return}// Scan scans the next token and returns the token position, the token,// and its literal string if applicable. The source end is indicated by// [token.EOF].//// If the returned token is a literal ([token.IDENT], [token.INT], [token.FLOAT],// [token.IMAG], [token.CHAR], [token.STRING]) or [token.COMMENT], the literal string// has the corresponding value.//// If the returned token is a keyword, the literal string is the keyword.//// If the returned token is [token.SEMICOLON], the corresponding// literal string is ";" if the semicolon was present in the source,// and "\n" if the semicolon was inserted because of a newline or// at EOF.//// If the returned token is [token.ILLEGAL], the literal string is the// offending character.//// In all other cases, Scan returns an empty literal string.//// For more tolerant parsing, Scan will return a valid token if// possible even if a syntax error was encountered. Thus, even// if the resulting token sequence contains no illegal tokens,// a client may not assume that no error occurred. Instead it// must check the scanner's ErrorCount or the number of calls// of the error handler, if there was one installed.//// Scan adds line information to the file added to the file// set with Init. Token positions are relative to that file// and thus relative to the file set.func ( *Scanner) () ( token.Pos, token.Token, string) {:if .nlPos.IsValid() {// Return artificial ';' token after /*...*/ comment // containing newline, at position of first newline. , , = .nlPos, token.SEMICOLON, "\n" .nlPos = token.NoPosreturn } .skipWhitespace()// current token start = .file.Pos(.offset)// determine token value := falseswitch := .ch; {caseisLetter(): = .scanIdentifier()iflen() > 1 {// keywords are longer than one letter - avoid lookup otherwise = token.Lookup()switch {casetoken.IDENT, token.BREAK, token.CONTINUE, token.FALLTHROUGH, token.RETURN: = true } } else { = true = token.IDENT }caseisDecimal() || == '.' && isDecimal(rune(.peek())): = true , = .scanNumber()default: .next() // always make progressswitch {caseeof:if .insertSemi { .insertSemi = false// EOF consumedreturn , token.SEMICOLON, "\n" } = token.EOFcase'\n':// we only reach here if s.insertSemi was // set in the first place and exited early // from s.skipWhitespace() .insertSemi = false// newline consumedreturn , token.SEMICOLON, "\n"case'"': = true = token.STRING = .scanString()case'\'': = true = token.CHAR = .scanRune()case'`': = true = token.STRING = .scanRawString()case':': = .switch2(token.COLON, token.DEFINE)case'.':// fractions starting with a '.' are handled by outer switch = token.PERIODif .ch == '.' && .peek() == '.' { .next() .next() // consume last '.' = token.ELLIPSIS }case',': = token.COMMAcase';': = token.SEMICOLON = ";"case'(': = token.LPARENcase')': = true = token.RPARENcase'[': = token.LBRACKcase']': = true = token.RBRACKcase'{': = token.LBRACEcase'}': = true = token.RBRACEcase'+': = .switch3(token.ADD, token.ADD_ASSIGN, '+', token.INC)if == token.INC { = true }case'-': = .switch3(token.SUB, token.SUB_ASSIGN, '-', token.DEC)if == token.DEC { = true }case'*': = .switch2(token.MUL, token.MUL_ASSIGN)case'/':if .ch == '/' || .ch == '*' {// comment , := .scanComment()if .insertSemi && != 0 {// For /*...*/ containing \n, return // COMMENT then artificial SEMICOLON. .nlPos = .file.Pos() .insertSemi = false } else { = .insertSemi// preserve insertSemi info }if .mode&ScanComments == 0 {// skip commentgoto } = token.COMMENT = } else {// division = .switch2(token.QUO, token.QUO_ASSIGN) }case'%': = .switch2(token.REM, token.REM_ASSIGN)case'^': = .switch2(token.XOR, token.XOR_ASSIGN)case'<':if .ch == '-' { .next() = token.ARROW } else { = .switch4(token.LSS, token.LEQ, '<', token.SHL, token.SHL_ASSIGN) }case'>': = .switch4(token.GTR, token.GEQ, '>', token.SHR, token.SHR_ASSIGN)case'=': = .switch2(token.ASSIGN, token.EQL)case'!': = .switch2(token.NOT, token.NEQ)case'&':if .ch == '^' { .next() = .switch2(token.AND_NOT, token.AND_NOT_ASSIGN) } else { = .switch3(token.AND, token.AND_ASSIGN, '&', token.LAND) }case'|': = .switch3(token.OR, token.OR_ASSIGN, '|', token.LOR)case'~': = token.TILDEdefault:// next reports unexpected BOMs - don't repeatif != bom {// Report an informative error for U+201[CD] quotation // marks, which are easily introduced via copy and paste.if == '“' || == '”' { .errorf(.file.Offset(), "curly quotation mark %q (use neutral %q)", , '"') } else { .errorf(.file.Offset(), "illegal character %#U", ) } } = .insertSemi// preserve insertSemi info = token.ILLEGAL = string() } }if .mode&dontInsertSemis == 0 { .insertSemi = }return}
The pages are generated with Goldsv0.7.0-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.