Skip to content

add raw-string literal support - #9956

Merged
fdncred merged 37 commits into
nushell:mainfrom
fdncred:raw_string_support
May 2, 2024
Merged

fdncred merged 37 commits into
nushell:mainfrom
fdncred:raw_string_support

Conversation

@fdncred

@fdncred fdncred commented Aug 8, 2023 •

Copy link
Copy Markdown
Contributor

Description

This PR adds raw string support by using r# at the beginning of single quoted strings and # at the end.

Notice that escapes do not process, even within single quotes, parentheses don't mean anything, $variables don't mean anything. It's just a string.

❯ echo r#'one\ntwo (blah) ($var)'#
one\ntwo (blah) ($var)

Notice how they work without echo or print and how they work without carriage returns.

❯ r#'adsfa'#
adsfa
❯ r##"asdfa'@qpejq'##
asdfa'@qpejq
❯ r#'asdfasdfasf
∙ foqwejfqo@'23rfjqf'#

They also have a special configurable color in the repl. (use single quotes though)
image

They should work like rust raw literals and allow r##, r###, r####, etc, to help with having one or many #'s in the middle of your raw-string.

They should work with let as well.

r#'some\nraw\nstring'# | str upcase

closes #5091

User-Facing Changes

Tests + Formatting

After Submitting

@fdncred
fdncred marked this pull request as draft August 8, 2023 14:49
@amtoine

amtoine commented Aug 8, 2023 •

Copy link
Copy Markdown
Member

Again, I'm not sure this is helpful because this is kind of what single quotes do now anyway.

i vote 👍 because, if you want to have single and double quotes in strings, you are currently forced to escape some of them right now 😮

@fdncred

fdncred commented Aug 8, 2023

Copy link
Copy Markdown
Contributor Author

@amtoine Good point. This works too.

❯ echo r'"""``""dafssa""``"""'
"""``""dafssa""``"""
❯ echo r"'''''''```one\ntwo''' (blah)``` ($var)'"
'''''''```one\ntwo''' (blah)``` ($var)'

Right now the requirement is that the raw string start and end with the same single or double quote mark. Backtick quotes aren't part of it.

@sophiajt

sophiajt commented Aug 8, 2023 •

Copy link
Copy Markdown
Contributor

Feels like we get a lot of what you're looking for with:

echo `one\ntwo (blah) ($var)`

@fdncred

fdncred commented Aug 8, 2023 •

Copy link
Copy Markdown
Contributor Author

Feels like we get a lot of what you're looking for with:

@jntrnr agreed. the same with single quotes. it's just more verbose, plus using backticks always makes me think of bash as "evaluate this". backticks should just be banned altogether, imo. like I said above, I'm not sure if it's helpful or not.

I do like the coloring of the string though. I think that part is helpful. e.g. light purple means you don't evaluate, green means it evaluates. That could be a good fix if we could do it somehow. for escaping-strings, interpolated strings, non-escaping strings, and paths.

@fdncred

fdncred commented Aug 9, 2023

Copy link
Copy Markdown
Contributor Author

After talking about this, we've decided to close this PR. The best thing about this PR (IMO), that we're going to continue working on, is adding the ability to highlight different types of strings in separate colors. We think this would be a nice QOL repl improvement.

@fdncred fdncred closed this Aug 9, 2023
@hustcer

hustcer commented Aug 12, 2023 •

Copy link
Copy Markdown
Contributor

@jntrnr echo a raw string works, however assignment does not work:

$> let raw = `one\ntwo (blah) ($var)`
Error: nu::shell::external_command

  × External command failed
   ╭─[entry #12:1:1]
 1 │ let raw = `one\ntwo (blah) ($var)`
   ·           ────────────┬───────────
   ·                       ╰── executable was not found
   ╰────
  help: 系统找不到指定的路径。 (os error 3)

Feels like we get a lot of what you're looking for with:

echo `one\ntwo (blah) ($var)`

@fdncred

fdncred commented Oct 4, 2023

Copy link
Copy Markdown
Contributor Author

Apparently we never did anything with "the best thing about the PR" nor did we answer hustcer's point. I'd still like to see this added as a QOL improvement.

@hustcer

hustcer commented Oct 4, 2023

Copy link
Copy Markdown
Contributor

Agreed, we need this feature.

@fdncred

fdncred commented Oct 6, 2023

Copy link
Copy Markdown
Contributor Author

@hustcer I just learned that this works now

> let raw = echo `one\ntwo (blah) ($var)`
> $raw
one\ntwo (blah) ($var)

@hustcer

hustcer commented Oct 7, 2023

Copy link
Copy Markdown
Contributor

@hustcer I just learned that this works now

> let raw = echo `one\ntwo (blah) ($var)`
> $raw
one\ntwo (blah) ($var)

Thanks, still not perfect enough, as:

# This one works
let raw = echo `one\ntwo (blah) ($var)`
# However, this one doesn't
let raw = `one\ntwo (blah) ($var)`
Error: nu::shell::external_command

  × External command failed
   ╭─[entry #2:1:1]
 1 │ let raw = `one\ntwo (blah) ($var)`
   ·           ────────────┬───────────
   ·                       ╰── executable was not found
   ╰────
  help: 系统找不到指定的路径。 (os error 3)

@blueberrycarrot

Copy link
Copy Markdown

Raw strings are much needed, would love to see this in the language. Except, can we go all the way and add Rust's r# syntax? Reasoning being, the arbitrary amount of #s can help with escaping problems in edge cases, and after all, raw strings's primary goal is to avoid escaping problems.

@fdncred

fdncred commented Feb 2, 2024

Copy link
Copy Markdown
Contributor Author

Raw strings are much needed, would love to see this in the language. Except, can we go all the way and add Rust's r# syntax? Reasoning being, the arbitrary amount of #s can help with escaping problems in edge cases, and after all, raw strings's primary goal is to avoid escaping problems.

I'd initially be against # since it means comment in nushell plus all the nixos crap with # scattered throughout. Seems like it would just make it more difficult.

@blueberrycarrot

Copy link
Copy Markdown

What about the essence of #, which is to make "begin" and "end" markers configurable at the declaration site? Could be something else, for example:

let rawstring = rFOO"Look, I can use "double quotes"!"FOO

Or, if the user writing the script doesn't care about a custom marker, it can be omitted:

let rawstring = r"Look, I can use "double quotes"!"

This also intuitively resonates with Bash people that use arbitrary heredoc markers like

cat <<EOF
See one coronation and you've seen them all.
EOF

where EOF can be anything. It's certainly more meaningful than Rust's repetition of #s.

@fdncred fdncred reopened this Feb 2, 2024
@fdncred

fdncred commented Feb 2, 2024 •

Copy link
Copy Markdown
Contributor Author

I tried to update this old PR to the latest main. May have missed some things. One thing that doesn't work is:

let a = r"one\ntwo\n (blah) ($var)"

I'm not sure let ever worked. I can't remember.

This doesn't work either

echo r"Look, I can use "double quotes"!"

@andrasio

andrasio commented Feb 2, 2024 •

Copy link
Copy Markdown
Member

What about the essence of #, which is to make "begin" and "end" markers configurable at the declaration site? Could be something else, for example:

let rawstring = rFOO"Look, I can use "double quotes"!"FOO

Or, if the user writing the script doesn't care about a custom marker, it can be omitted:

let rawstring = r"Look, I can use "double quotes"!"

This also intuitively resonates with Bash people that use arbitrary heredoc markers like

cat <<EOF
See one coronation and you've seen them all.
EOF

where EOF can be anything. It's certainly more meaningful than Rust's repetition of #s.

+1 to this and it'd be great if it can support interpolation in it as well (and be able to disable it too)

@blueberrycarrot

Copy link
Copy Markdown

it'd be great if it can support interpolation in it as well.

That's a murky area, as it kind of defeats the purpose of it being a raw string. I know what you mean, and I've been at the receiving end of this: it's both a blessing and annoying at the same time that in Bash, you can use variables in heredoc:

ssh user@remotehost <<EOF
echo $myvar # myvar taken from outer script scope
echo \$myvar # myvar taken from the inner Bash scope (assuming remote host runs Bash)
EOF

And this $myvar and \$myvar escaping can be hard to debug and do right. I love-hate it.

What if raw strings were pure raw with no embellishments whatsoever? You could still insert computed values by concatenating raw strings using +.

@fdncred

fdncred commented Feb 2, 2024

Copy link
Copy Markdown
Contributor Author

Ugh, this is going to take some surgery. parse_value is not passing the right span to parse_raw_string.

If anyone wants to pick this up and take it over, please volunteer. I doubt I'll work on it.

@andrasio

andrasio commented Feb 2, 2024 •

Copy link
Copy Markdown
Member

it'd be great if it can support interpolation in it as well.

That's a murky area, as it kind of defeats the purpose of it being a raw string. I know what you mean, and I've been at the receiving end of this: it's both a blessing and annoying at the same time that in Bash, you can use variables in heredoc:

ssh user@remotehost <<EOF
echo $myvar # myvar taken from outer script scope
echo \$myvar # myvar taken from the inner Bash scope (assuming remote host runs Bash)
EOF

And this $myvar and \$myvar escaping can be hard to debug and do right. I love-hate it.

What if raw strings were pure raw with no embellishments whatsoever? You could still insert computed values by concatenating raw strings using +.

The primary reason I'd be interested in having interpolation in heredocs is exactly what I'm looking for! 😅

Generally for the nu language most of the time I think about them in the sense of modern programming/scripting languages and not syntax or following how things work in things like bash. In programs I've written, heredocs, both with optional delimiter for multiline strings and optionally disable/enable interpolation can be really useful and code easy to read.

So it would be a really welcomed addition IMO. Big fan of Ruby's heredocs and I use them a lot and is helpful for other folks reading my code.

@blueberrycarrot

Copy link
Copy Markdown

By the way, in Bash you have control over interpolation, where

cat <<EOF
echo $PATH
EOF

will expand $PATH to its value, but

cat <<'EOF'
echo $PATH
EOF

will not, due to single quotes around EOF.

@WindSoilder

WindSoilder commented Apr 27, 2024 •

Copy link
Copy Markdown
Contributor

It should close: #5091

Fix raw string with let like: let x = r@'abc'@
@sholderbach

Copy link
Copy Markdown
Member

A small concern I have with the r@""@ syntax is that it has an overlap with the custom completer passing syntax. Might not manifest right now but worth checking or considering if overloading the @ sigil is worth it for the raw strings.

def test [my_arg: number@"my func"] is a valid way to specify a custom completer, as we strip quotes for quoted function names. This shares the r@" prefix.

@fdncred

fdncred commented Apr 27, 2024

Copy link
Copy Markdown
Contributor Author

We can always pick another symbol like !. @IanManske @WindSoilder what are your thoughts on Stefan's comment?

echo r!'one\ntwo (blah) ($var)'!

@IanManske

IanManske commented Apr 27, 2024 •

Copy link
Copy Markdown
Member

The only potential issue I see is if we allow r to be valid type (i.e., if we add custom types in the future):

def cmd [arg: r@'options'] {}

If we remove r from the syntax, then there shouldn't be any ambiguity.

Then again, it could still look confusing/inconsistent:

def cmd [arg: number@'options'] {} # almost looks like `r@''@` or `@''@`

So, I would also be fine with changing the symbol/syntax.

@sholderbach

Copy link
Copy Markdown
Member

As we should be parsimonous with the available special sauce characters, and have something as identifiable as possible for the users, among the options I prefer the Rust-like raw strings

  • r#"raw like rust"#, familiar to Rust users. # already associated with quoting as a comment, comments already enforce that you have a space before the # so no conflict when provided with r# and "# (or was there a deeper problem you identified during torture testing), (small partial conflict with unquoted nix # specs may need to be ruled out.)
  • r@"raw but Anders"@ I think the @ read as at may be useful to preserve for the completers or general future evolution as a type operator.
  • @"is this C# verbatim?"@ - character soup to me
  • r!"..."! uses up a so far unused special char that we don't have available for future endeavours into syntax (even though I would advise against using more sigils for strings and only use special prefix chars or names with a mnemonic like r(aw)-string for future string additons)

@WindSoilder

Copy link
Copy Markdown
Contributor

To be honest, I don't think it's a big issue, because we only use raw string outside of function signature, and custom completer only exists inside function signature. They don't have overlap inside the same space.

C# using @ in various places: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim

@fdncred

fdncred commented Apr 28, 2024

Copy link
Copy Markdown
Contributor Author

My personal favorite is still prefix: r# suffix: #. I was trying to compromise with Ian.

I think the point about double quotes vs single quotes is probably a good one, so I'm good with single quotes.

I spent 20+ years writing C# but I still like r#'raw-string'# best. Maybe we should talk about it Wednesday.

@IanManske

IanManske commented Apr 28, 2024 •

Copy link
Copy Markdown
Member

Maybe we should talk about it Wednesday.

Yeah, sounds good.

Just to reiterate my point, I sympathize with the fact that r#"raw like rust"# is familiar to Rust users, but I'm not sure if this syntax fits in language. IMO it looks too much like a comment.

let a = dir #"this is a comment"
let b = r#"this is a raw string"#

Had I not known that comments required a preceding space (I just learned that now lol), then I would have assumed that let b = ... had a comment. I'm trying to look at this from the perspective of a new user where they may have seen many examples of comments in action and learned that # means ignore the rest of the line. The r#""# syntax breaks this assumption and may come as a surprise to some.

The r@''@ syntax has a similar problem, since it's similar to our completion syntax. As @WindSoilder said, they aren't used in the same context, so it's slightly better. Then again, Stefan makes a good point that we may want to reserve or extend the @ sign for other uses in the future.

So now I'm leaning towards r!'...'! of all things 😅 (or some other symbol).

@fdncred

fdncred commented May 1, 2024

Copy link
Copy Markdown
Contributor Author

@WindSoilder can we change this one more time to r#'raw-string'#? so r# prefix, # suffix, and single quotes only.

@fdncred
fdncred merged commit 8ed0d84 into nushell:main May 2, 2024
@fdncred
fdncred deleted the raw_string_support branch May 2, 2024 13:36
@hustcer hustcer added this to the v0.94.0 milestone May 9, 2024
@yizhepku

yizhepku commented May 9, 2024 •

Copy link
Copy Markdown
Contributor

I noticed that even though we've added Expr::RawString, I'm still getting Expr::String. Is this normal?

Here's the output of dbg!(call) from run_external. I typed ^ls r#'foo bar'# into the shell.

[crates\nu-command\src\system\run_external.rs:50:9] call = Call {
    decl_id: 0,
    head: Span {
        start: 123381,
        end: 123383,
    },
    arguments: [
        Positional(
            Expression {
                expr: String(
                    "ls",
                ),
                span: Span {
                    start: 123381,
                    end: 123383,
                },
                ty: String,
                custom_completion: None,
            },
        ),
        Positional(
            Expression {
                expr: String(         <--- Shouldn't this be RawString?
                    "r#'foo bar'#",
                ),
                span: Span {
                    start: 123384,
                    end: 123396,
                },
                ty: String,
                custom_completion: None,
            },
        ),
    ],
    parser_info: {},
}

WindSoilder pushed a commit that referenced this pull request May 9, 2024
# Description
As discovered by @yizhepku in a
[comment](#9956 (comment))
in #9956, raw strings are not parsed properly when they are used as an
argument to an external command. This PR fixes that.

# Tests + Formatting
Added a test.
FilipAndersson245 pushed a commit to FilipAndersson245/nushell that referenced this pull request May 18, 2024
# Description
As discovered by @yizhepku in a
[comment](nushell#9956 (comment))
in nushell#9956, raw strings are not parsed properly when they are used as an
argument to an external command. This PR fixes that.

# Tests + Formatting
Added a test.
@rgwood

rgwood commented May 29, 2024

Copy link
Copy Markdown
Contributor

This is a great feature. Thanks all!

@fdncred

fdncred commented May 29, 2024

Copy link
Copy Markdown
Contributor Author

It was definitely an uphill battle and took almost a year but I'm glad we got it landed thanks mostly to @WindSoilder.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Design better raw string syntax