Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Created August 17, 2021 05:03
Show Gist options
  • Save percybolmer/fb63a158d4cde8e35d93dab87e4b0a27 to your computer and use it in GitHub Desktop.
Save percybolmer/fb63a158d4cde8e35d93dab87e4b0a27 to your computer and use it in GitHub Desktop.
func (s *Scanner) scanComment() string {
// initial '/' already consumed; s.ch == '/' || s.ch == '*'
offs := s.offset - 1 // position of initial '/'
next := -1 // position immediately following the comment; < 0 means invalid comment
numCR := 0
if s.ch == '/' {
//-style comment
// (the final '\n' is not considered part of the comment)
s.next()
for s.ch != '\n' && s.ch >= 0 {
if s.ch == '\r' {
numCR++
}
s.next()
}
// if we are at '\n', the position following the comment is afterwards
next = s.offset
if s.ch == '\n' {
next++
}
goto exit
}
/*-style comment */
s.next()
for s.ch >= 0 {
ch := s.ch
if ch == '\r' {
numCR++
}
s.next()
if ch == '*' && s.ch == '/' {
s.next()
next = s.offset
goto exit
}
}
s.error(offs, "comment not terminated")
exit:
lit := s.src[offs:s.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 numCR > 0 && len(lit) >= 2 && lit[1] == '/' && lit[len(lit)-1] == '\r' {
lit = lit[:len(lit)-1]
numCR--
}
// interpret line directives
// (//line directives must start at the beginning of the current line)
if next >= 0 /* implies valid comment */ && (lit[1] == '*' || offs == s.lineOffset) && bytes.HasPrefix(lit[2:], prefix) {
s.updateLineInfo(next, offs, lit)
}
if numCR > 0 {
lit = stripCR(lit, lit[1] == '*')
}
return string(lit)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment