Skip to content

Commit

Permalink
SONARPY-1538: Fix lexing error when encountering escaped characters (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
joke1196 authored Oct 30, 2023
1 parent 1ebb12e commit 09ede81
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public class FStringChannel extends Channel<Lexer> {

private static final Set<Character> QUOTES = Set.of('\"', '\'');
private static final Set<Character> PREFIXES = Set.of('F', 'R');
private static final Set<String> ESCAPED_CHARS = Set.of("{{", "}}","\\\"","\\\'");
private static final Set<String> ESCAPED_CHARS = Set.of("{{", "}}");

public FStringChannel(LexerState lexerState) {
this.lexerState = lexerState;
Expand Down Expand Up @@ -153,7 +153,7 @@ private static boolean isUnicodeChar(StringBuilder sb ){
}

private static boolean isEscapedChar(CodeReader code) {
return ESCAPED_CHARS.contains(String.valueOf(code.peek(2)));
return ESCAPED_CHARS.contains(String.valueOf(code.peek(2))) || code.peek() == '\\';
}

private static boolean areClosingQuotes(CodeReader code, FStringState state) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,17 @@ void fstring_complex_format_specifier() {
hasToken("}", PythonPunctuator.RCURLYBRACE),
hasToken("\"", PythonTokenType.FSTRING_END)));
}

@Test
void fstring_double_backslash() {
assertThat(lexer.lex("f\"{a}\\\\\""), allOf(
hasToken("f\"", PythonTokenType.FSTRING_START),
hasToken("{", PythonPunctuator.LCURLYBRACE),
hasToken("a", GenericTokenType.IDENTIFIER),
hasToken("}", PythonPunctuator.RCURLYBRACE),
hasToken("\\\\", PythonTokenType.FSTRING_MIDDLE),
hasToken("\"", PythonTokenType.FSTRING_END)));
}
/**
* http://docs.python.org/reference/lexical_analysis.html#integer-and-long-integer-literals
*/
Expand Down
3 changes: 2 additions & 1 deletion python-frontend/src/test/resources/parser/own/fstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@
}"
f"Current value: \"{value}\" (type: {type(value)}). "
f'\N{RIGHTWARDS ARROW}'

f" \\"
F"\\ \"{a}\":\\"

0 comments on commit 09ede81

Please sign in to comment.