MCPcopy Create free account
hub / github.com/astral-sh/ruff / lex_string

Method lex_string

crates/ruff_python_parser/src/lexer.rs:873–984  ·  view source on GitHub ↗

Lex a string literal.

(&mut self, quote: char)

Source from the content-addressed store, hash-verified

871
872 /// Lex a string literal.
873 fn lex_string(&mut self, quote: char) -> TokenKind {
874 #[cfg(debug_assertions)]
875 debug_assert_eq!(self.cursor.previous(), quote);
876
877 if quote == '"' {
878 self.current_flags |= TokenFlags::DOUBLE_QUOTES;
879 }
880
881 // If the next two characters are also the quote character, then we have a triple-quoted
882 // string; consume those two characters and ensure that we require a triple-quote to close
883 if self.cursor.eat_char2(quote, quote) {
884 self.current_flags |= TokenFlags::TRIPLE_QUOTED_STRING;
885 }
886
887 let quote_byte = u8::try_from(quote).expect("char that fits in u8");
888 if self.current_flags.is_triple_quoted() {
889 // For triple-quoted strings, scan until we find the closing quote (ignoring escaped
890 // quotes) or the end of the file.
891 loop {
892 let Some(index) = memchr::memchr(quote_byte, self.cursor.rest().as_bytes()) else {
893 self.cursor.skip_to_end();
894
895 self.current_flags |= TokenFlags::UNCLOSED_STRING;
896 self.push_error(LexicalError::new(
897 LexicalErrorType::UnclosedStringError,
898 self.token_range(),
899 ));
900 break;
901 };
902
903 // Rare case: if there are an odd number of backslashes before the quote, then
904 // the quote is escaped and we should continue scanning.
905 let num_backslashes = self.cursor.rest().as_bytes()[..index]
906 .iter()
907 .rev()
908 .take_while(|&&c| c == b'\\')
909 .count();
910
911 // Advance the cursor past the quote and continue scanning.
912 self.cursor.skip_bytes(index + 1);
913
914 // If the character is escaped, continue scanning.
915 if num_backslashes % 2 == 1 {
916 continue;
917 }
918
919 // Otherwise, if it's followed by two more quotes, then we're done.
920 if self.cursor.eat_char2(quote, quote) {
921 break;
922 }
923 }
924 } else {
925 // For non-triple-quoted strings, scan until we find the closing quote, but end early
926 // if we encounter a newline or the end of the file.
927 loop {
928 let Some(index) =
929 memchr::memchr3(quote_byte, b'\r', b'\n', self.cursor.rest().as_bytes())
930 else {

Callers 2

lex_identifierMethod · 0.80

Calls 14

expectMethod · 0.80
restMethod · 0.80
skip_to_endMethod · 0.80
push_errorMethod · 0.80
eat_char2Method · 0.45
is_triple_quotedMethod · 0.45
as_bytesMethod · 0.45
token_rangeMethod · 0.45
countMethod · 0.45
iterMethod · 0.45
skip_bytesMethod · 0.45
firstMethod · 0.45

Tested by

no test coverage detected