String literals

This commit is contained in:
Mariano Uvalle 2023-05-07 00:00:35 +00:00
parent 021216c94a
commit 25e3b6068d
2 changed files with 25 additions and 0 deletions

View file

@ -91,6 +91,8 @@ func (s *Scanner) scanToken() {
} else {
s.addToken(SLASH)
}
case '"':
s.scanString()
// Ignore whitespace.
case ' ':
case '\t':
@ -132,6 +134,28 @@ func (s *Scanner) peek() byte {
return s.source[s.current]
}
func (s *Scanner) scanString() {
for s.peek() != '"' && !s.isAtEnd() {
// Lox allows multi-line strings.
if s.peek() == '\n' {
s.line += 1
}
s.advance()
}
if s.isAtEnd() {
lerrors.EmitError(s.line, "Unterminated string.")
return
}
// Consume the closing "
s.advance()
// Trim enclosing quotes
val := s.source[s.start+1 : s.current-1]
s.addTokenWithLiteral(STRING, val)
}
// addToken produces a single token without a literal value.
func (s *Scanner) addToken(typ TokenType) {
s.addTokenWithLiteral(typ, nil)

View file

@ -1,3 +1,4 @@
// this is a comment
(( )){} // grouping stuff
!*+-/=<> <= == // operators
"some string literal"