Skip to content

Parsing of backslashes in custom string literals seems inconsistent #22926

Description

@Keno
julia> parse(readline(STDIN))
raw"\""

:(@raw_str "\"")

julia>

julia> parse(readline(STDIN))
raw"\\""
:($(Expr(:incomplete, "incomplete: invalid string syntax")))

julia> parse(readline(STDIN))
raw"\\\""
:(@raw_str "\\\\\"")

julia> dump(ans)
Expr
  head: Symbol macrocall
  args: Array{Any}((2,))
    1: Symbol @raw_str
    2: String "\\\\\""
  typ: Any

In particular there is a confusion about what backslash actually does. It certainly escapes ", but as we see in the second example, it also escapes itself. However, in the third example it suddenly doesn't appear to escape itself anymore. In particular, it does not seem to be possible to obtain a string literal that parses to @raw_str "\\\"" at the moment.

The options I see are

  1. Make raw"\\"" parse to @raw_str "\\\"" (rather than an error)
  2. Make raw"\\\"" parse to @raw_str "\\\"".
  3. Decouple parsing from the content and always give what was actually written, i.e. make raw"\"" parse to @raw_str "\\\"" and raw"\\\"" parse to @raw_str "\\\\\\\""
  4. Disallow " in custom string literals entirely.
  5. Do nothing.

FWIW, I think I prefer option 3.

Whatever the decision with respect to parsing, I think we should adjust raw_str to have the invariant that whenever print(r"<x>") is a valid expression for some sequence of characters <x>, the output of that expression is <x>. That's currently not the case in the above example:

julia> print(raw"\\\"")
\\"
julia> print(raw"\"")
"

This discrepancy was noted when raw_str was originally introduced and is documented, but it bothers me.

Metadata

Metadata

Assignees

Labels

breakingThis change will break codeneeds decisionA decision on this change is neededparserLanguage parsing and surface syntax

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions