Reputation: 7674
Based on the relevant section of the Julia docs, my understanding is that a non-standard string literal like foo"hello, world"
is equivalent to explicitly calling the corresponding macro: @foo_str("hello, world")
. However, there must be some extra magic that I'm not understanding. Consider a date format dateformat"\m"
. By itself, "\m"
throws a syntax error:
julia> "\m"
ERROR: syntax: invalid escape sequence
And the same syntax error is thrown if I call @dateformat_str("\m")
, since the string literal "\m"
appears to be evaluated or error checked before it is passed to the macro:
julia> using Dates
julia> @dateformat_str("\m")
ERROR: syntax: invalid escape sequence
However, using the non-standard string literal works:
julia> dateformat"\m"
dateformat"\m"
This is counter-intuitive, because I thought that dateformat"\m"
was equivalent to @dateformat_str("\m")
. How does the non-standard string literal avoid the syntax error generated by the standard string literal?
Upvotes: 8
Views: 367
Reputation: 28212
In short, because the parser recognizes that situation and parses the string literal differently
For string macros invocations it does this.
Calling: parse-raw-literal
Where as for normal string literals it does this.
Calling parse-string-literal
@dateformat_str("\m")
on the other hand parses as a macro invocation on a normal string literal. so it uses the later parse-string-literal
, which errors.
Note that ones parsed it has parsed the string into what is escaped as "\\m"
julia> dump(:(dateformat"\m"))
Expr
head: Symbol macrocall
args: Array{Any}((3,))
1: Symbol @dateformat_str
2: LineNumberNode
line: Int64 1
file: Symbol REPL[6]
3: String "\\m
Of related interest is the raw string macro , which does nothing at all, but is still going to be string parsed using parse-raw-literal
It is basically defined as
macro raw_str(s)
return s
end
Upvotes: 8