fileset, revset, templater: add support for single-quoted raw string literals

Since fileset/revset/template expressions are specified as command-line
arguments, it's sometimes convenient to use single quotes instead of double
quotes. Various scripting languages parse single-quoted strings in various ways,
but I choose the TOML rule because it's simple and practically useful. TOML is
our config language, so copying the TOML syntax would be less surprising than
borrowing it from another language.

https://github.com/toml-lang/toml/issues/188
This commit is contained in:
Yuya Nishihara 2024-04-17 21:17:40 +09:00
parent a74bf89df5
commit 5b769c5c9e
10 changed files with 140 additions and 19 deletions

View file

@ -35,6 +35,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
expressions](docs/filesets.md). Note that filesets are currently experimental, expressions](docs/filesets.md). Note that filesets are currently experimental,
but will be enabled by default in a future release. but will be enabled by default in a future release.
* Revsets and templates now support single-quoted raw string literals.
* `jj prev` and `jj next` now work when the working copy revision is a merge. * `jj prev` and `jj next` now work when the working copy revision is a merge.
* Operation objects in templates now have a `snapshot() -> Boolean` method that * Operation objects in templates now have a `snapshot() -> Boolean` method that

View file

@ -24,6 +24,9 @@ string_content_char = @{ !("\"" | "\\") ~ ANY }
string_content = @{ string_content_char+ } string_content = @{ string_content_char+ }
string_literal = ${ "\"" ~ (string_content | string_escape)* ~ "\"" } string_literal = ${ "\"" ~ (string_content | string_escape)* ~ "\"" }
raw_string_content = @{ (!"'" ~ ANY)* }
raw_string_literal = ${ "'" ~ raw_string_content ~ "'" }
integer_literal = @{ integer_literal = @{
ASCII_NONZERO_DIGIT ~ ASCII_DIGIT* ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*
| "0" | "0"
@ -59,6 +62,7 @@ primary = _{
| lambda | lambda
| identifier | identifier
| string_literal | string_literal
| raw_string_literal
| integer_literal | integer_literal
} }

View file

@ -42,6 +42,8 @@ impl Rule {
Rule::string_content_char => None, Rule::string_content_char => None,
Rule::string_content => None, Rule::string_content => None,
Rule::string_literal => None, Rule::string_literal => None,
Rule::raw_string_content => None,
Rule::raw_string_literal => None,
Rule::integer_literal => None, Rule::integer_literal => None,
Rule::identifier => None, Rule::identifier => None,
Rule::concat_op => Some("++"), Rule::concat_op => Some("++"),
@ -383,6 +385,12 @@ fn parse_term_node(pair: Pair<Rule>) -> TemplateParseResult<ExpressionNode> {
let text = STRING_LITERAL_PARSER.parse(expr.into_inner()); let text = STRING_LITERAL_PARSER.parse(expr.into_inner());
ExpressionNode::new(ExpressionKind::String(text), span) ExpressionNode::new(ExpressionKind::String(text), span)
} }
Rule::raw_string_literal => {
let (content,) = expr.into_inner().collect_tuple().unwrap();
assert_eq!(content.as_rule(), Rule::raw_string_content);
let text = content.as_str().to_owned();
ExpressionNode::new(ExpressionKind::String(text), span)
}
Rule::integer_literal => { Rule::integer_literal => {
let value = expr.as_str().parse().map_err(|err| { let value = expr.as_str().parse().map_err(|err| {
TemplateParseError::expression("Invalid integer literal", span).with_source(err) TemplateParseError::expression("Invalid integer literal", span).with_source(err)
@ -1178,6 +1186,24 @@ mod tests {
parse_into_kind(r#" "\y" "#), parse_into_kind(r#" "\y" "#),
Err(TemplateParseErrorKind::SyntaxError), Err(TemplateParseErrorKind::SyntaxError),
); );
// Single-quoted raw string
assert_eq!(
parse_into_kind(r#" '' "#),
Ok(ExpressionKind::String("".to_owned())),
);
assert_eq!(
parse_into_kind(r#" 'a\n' "#),
Ok(ExpressionKind::String(r"a\n".to_owned())),
);
assert_eq!(
parse_into_kind(r#" '\' "#),
Ok(ExpressionKind::String(r"\".to_owned())),
);
assert_eq!(
parse_into_kind(r#" '"' "#),
Ok(ExpressionKind::String(r#"""#.to_owned())),
);
} }
#[test] #[test]

View file

@ -13,14 +13,16 @@ ui.allow-filesets = true
``` ```
Many `jj` commands accept fileset expressions as positional arguments. File Many `jj` commands accept fileset expressions as positional arguments. File
names passed to these commands must be quoted if they contain whitespace or meta names passed to these commands [must be quoted][string-literals] if they contain
characters. However, as a special case, quotes can be omitted if the expression whitespace or meta characters. However, as a special case, quotes can be omitted
has no operators nor function calls. For example: if the expression has no operators nor function calls. For example:
* `jj diff 'Foo Bar'` (shell quotes are required, but inner quotes are optional) * `jj diff 'Foo Bar'` (shell quotes are required, but inner quotes are optional)
* `jj diff '~"Foo Bar"'` (both shell and inner quotes are required) * `jj diff '~"Foo Bar"'` (both shell and inner quotes are required)
* `jj diff '"Foo(1)"'` (both shell and inner quotes are required) * `jj diff '"Foo(1)"'` (both shell and inner quotes are required)
[string-literals]: templates.md#string-literals
## File patterns ## File patterns
The following patterns are supported: The following patterns are supported:

View file

@ -29,10 +29,12 @@ A full change ID refers to all visible commits with that change ID (there is
typically only one visible commit with a given change ID). A unique prefix of typically only one visible commit with a given change ID). A unique prefix of
the full change ID can also be used. It is an error to use a non-unique prefix. the full change ID can also be used. It is an error to use a non-unique prefix.
Use double quotes to prevent a symbol from being interpreted as an expression. Use [single or double quotes][string-literals] to prevent a symbol from being
For example, `"x-"` is the symbol `x-`, not the parents of symbol `x`. interpreted as an expression. For example, `"x-"` is the symbol `x-`, not the
Taking shell quoting into account, you may need to use something like parents of symbol `x`. Taking shell quoting into account, you may need to use
`jj log -r '"x-"'`. something like `jj log -r '"x-"'`.
[string-literals]: templates.md#string-literals
### Priority ### Priority

View file

@ -194,11 +194,22 @@ defined.
#### String literals #### String literals
String literals must be surrounded by double quotes (`"`). The following escape String literals must be surrounded by single or double quotes (`'` or `"`).
sequences starting with a backslash have their usual meaning: `\"`, `\\`, `\n`, A double-quoted string literal supports the following escape sequences:
`\r`, `\t`, `\0`. Other escape sequences are not supported. Any UTF-8 characters
are allowed inside a string literal, with two exceptions: unescaped `"`-s and * `\"`: double quote
uses of `\` that don't form a valid escape sequence. * `\\`: backslash
* `\t`: horizontal tab
* `\r`: carriage return
* `\n`: new line
* `\0`: null
Other escape sequences are not supported. Any UTF-8 characters are allowed
inside a string literal, with two exceptions: unescaped `"`-s and uses of `\`
that don't form a valid escape sequence.
A single-quoted string literal has no escape syntax. `'` can't be expressed
inside a single-quoted string literal.
### Template type ### Template type

View file

@ -40,6 +40,9 @@ string_content_char = @{ !("\"" | "\\") ~ ANY }
string_content = @{ string_content_char+ } string_content = @{ string_content_char+ }
string_literal = ${ "\"" ~ (string_content | string_escape)* ~ "\"" } string_literal = ${ "\"" ~ (string_content | string_escape)* ~ "\"" }
raw_string_content = @{ (!"'" ~ ANY)* }
raw_string_literal = ${ "'" ~ raw_string_content ~ "'" }
pattern_kind_op = { ":" } pattern_kind_op = { ":" }
negate_op = { "~" } negate_op = { "~" }
@ -57,7 +60,11 @@ function_arguments = {
} }
// TODO: change rhs to string_literal to require quoting? #2101 // TODO: change rhs to string_literal to require quoting? #2101
string_pattern = { strict_identifier ~ pattern_kind_op ~ (identifier | string_literal) } string_pattern = {
strict_identifier
~ pattern_kind_op
~ (identifier | string_literal | raw_string_literal)
}
bare_string_pattern = { strict_identifier ~ pattern_kind_op ~ bare_string } bare_string_pattern = { strict_identifier ~ pattern_kind_op ~ bare_string }
primary = { primary = {
@ -66,6 +73,7 @@ primary = {
| string_pattern | string_pattern
| identifier | identifier
| string_literal | string_literal
| raw_string_literal
} }
expression = { expression = {

View file

@ -48,6 +48,8 @@ impl Rule {
Rule::string_content_char => None, Rule::string_content_char => None,
Rule::string_content => None, Rule::string_content => None,
Rule::string_literal => None, Rule::string_literal => None,
Rule::raw_string_content => None,
Rule::raw_string_literal => None,
Rule::pattern_kind_op => Some(":"), Rule::pattern_kind_op => Some(":"),
Rule::negate_op => Some("~"), Rule::negate_op => Some("~"),
Rule::union_op => Some("|"), Rule::union_op => Some("|"),
@ -233,6 +235,11 @@ fn parse_as_string_literal(pair: Pair<Rule>) -> String {
match pair.as_rule() { match pair.as_rule() {
Rule::identifier => pair.as_str().to_owned(), Rule::identifier => pair.as_str().to_owned(),
Rule::string_literal => STRING_LITERAL_PARSER.parse(pair.into_inner()), Rule::string_literal => STRING_LITERAL_PARSER.parse(pair.into_inner()),
Rule::raw_string_literal => {
let (content,) = pair.into_inner().collect_tuple().unwrap();
assert_eq!(content.as_rule(), Rule::raw_string_content);
content.as_str().to_owned()
}
r => panic!("unexpected string literal rule: {r:?}"), r => panic!("unexpected string literal rule: {r:?}"),
} }
} }
@ -256,7 +263,9 @@ fn parse_primary_node(pair: Pair<Rule>) -> FilesetParseResult<ExpressionNode> {
ExpressionKind::StringPattern { kind, value } ExpressionKind::StringPattern { kind, value }
} }
Rule::identifier => ExpressionKind::Identifier(first.as_str()), Rule::identifier => ExpressionKind::Identifier(first.as_str()),
Rule::string_literal => ExpressionKind::String(parse_as_string_literal(first)), Rule::string_literal | Rule::raw_string_literal => {
ExpressionKind::String(parse_as_string_literal(first))
}
r => panic!("unexpected primary rule: {r:?}"), r => panic!("unexpected primary rule: {r:?}"),
}; };
Ok(ExpressionNode::new(expr, span)) Ok(ExpressionNode::new(expr, span))
@ -468,6 +477,24 @@ mod tests {
parse_into_kind(r#" "\y" "#), parse_into_kind(r#" "\y" "#),
Err(FilesetParseErrorKind::SyntaxError) Err(FilesetParseErrorKind::SyntaxError)
); );
// Single-quoted raw string
assert_eq!(
parse_into_kind(r#" '' "#),
Ok(ExpressionKind::String("".to_owned())),
);
assert_eq!(
parse_into_kind(r#" 'a\n' "#),
Ok(ExpressionKind::String(r"a\n".to_owned())),
);
assert_eq!(
parse_into_kind(r#" '\' "#),
Ok(ExpressionKind::String(r"\".to_owned())),
);
assert_eq!(
parse_into_kind(r#" '"' "#),
Ok(ExpressionKind::String(r#"""#.to_owned())),
);
} }
#[test] #[test]
@ -493,6 +520,13 @@ mod tests {
value: "".to_owned() value: "".to_owned()
}) })
); );
assert_eq!(
parse_into_kind(r#" foo:'\' "#),
Ok(ExpressionKind::StringPattern {
kind: "foo",
value: r"\".to_owned()
})
);
assert_eq!( assert_eq!(
parse_into_kind(r#" foo: "#), parse_into_kind(r#" foo: "#),
Err(FilesetParseErrorKind::SyntaxError) Err(FilesetParseErrorKind::SyntaxError)

View file

@ -21,6 +21,7 @@ identifier = @{
symbol = { symbol = {
identifier identifier
| string_literal | string_literal
| raw_string_literal
} }
string_escape = @{ "\\" ~ ("t" | "r" | "n" | "0" | "\"" | "\\") } string_escape = @{ "\\" ~ ("t" | "r" | "n" | "0" | "\"" | "\\") }
@ -28,6 +29,9 @@ string_content_char = @{ !("\"" | "\\") ~ ANY }
string_content = @{ string_content_char+ } string_content = @{ string_content_char+ }
string_literal = ${ "\"" ~ (string_content | string_escape)* ~ "\"" } string_literal = ${ "\"" ~ (string_content | string_escape)* ~ "\"" }
raw_string_content = @{ (!"'" ~ ANY)* }
raw_string_literal = ${ "'" ~ raw_string_content ~ "'" }
at_op = { "@" } at_op = { "@" }
pattern_kind_op = { ":" } pattern_kind_op = { ":" }

View file

@ -108,6 +108,8 @@ impl Rule {
Rule::string_content_char => None, Rule::string_content_char => None,
Rule::string_content => None, Rule::string_content => None,
Rule::string_literal => None, Rule::string_literal => None,
Rule::raw_string_content => None,
Rule::raw_string_literal => None,
Rule::at_op => Some("@"), Rule::at_op => Some("@"),
Rule::pattern_kind_op => Some(":"), Rule::pattern_kind_op => Some(":"),
Rule::parents_op => Some("-"), Rule::parents_op => Some("-"),
@ -1114,6 +1116,11 @@ fn parse_symbol_rule_as_literal(mut pairs: Pairs<Rule>) -> String {
match first.as_rule() { match first.as_rule() {
Rule::identifier => first.as_str().to_owned(), Rule::identifier => first.as_str().to_owned(),
Rule::string_literal => STRING_LITERAL_PARSER.parse(first.into_inner()), Rule::string_literal => STRING_LITERAL_PARSER.parse(first.into_inner()),
Rule::raw_string_literal => {
let (content,) = first.into_inner().collect_tuple().unwrap();
assert_eq!(content.as_rule(), Rule::raw_string_content);
content.as_str().to_owned()
}
_ => { _ => {
panic!("unexpected symbol parse rule: {:?}", first.as_str()); panic!("unexpected symbol parse rule: {:?}", first.as_str());
} }
@ -2839,6 +2846,13 @@ mod tests {
"foo bar".to_string() "foo bar".to_string()
)) ))
); );
assert_eq!(
parse(r#"'foo bar'@'bar baz'"#),
Ok(RevsetExpression::remote_symbol(
"foo bar".to_string(),
"bar baz".to_string()
))
);
// Quoted "@" is not interpreted as a working copy or remote symbol // Quoted "@" is not interpreted as a working copy or remote symbol
assert_eq!( assert_eq!(
parse(r#""@""#), parse(r#""@""#),
@ -2895,6 +2909,7 @@ mod tests {
assert_eq!(parse("(foo)"), Ok(foo_symbol.clone())); assert_eq!(parse("(foo)"), Ok(foo_symbol.clone()));
// Parse a quoted symbol // Parse a quoted symbol
assert_eq!(parse("\"foo\""), Ok(foo_symbol.clone())); assert_eq!(parse("\"foo\""), Ok(foo_symbol.clone()));
assert_eq!(parse("'foo'"), Ok(foo_symbol.clone()));
// Parse the "parents" operator // Parse the "parents" operator
assert_eq!(parse("foo-"), Ok(foo_symbol.parents())); assert_eq!(parse("foo-"), Ok(foo_symbol.parents()));
// Parse the "children" operator // Parse the "children" operator
@ -3070,12 +3085,13 @@ mod tests {
#[test] #[test]
fn test_parse_string_literal() { fn test_parse_string_literal() {
let branches_expr =
|s: &str| RevsetExpression::branches(StringPattern::Substring(s.to_owned()));
// "\<char>" escapes // "\<char>" escapes
assert_eq!( assert_eq!(
parse(r#"branches("\t\r\n\"\\\0")"#), parse(r#"branches("\t\r\n\"\\\0")"#),
Ok(RevsetExpression::branches(StringPattern::Substring( Ok(branches_expr("\t\r\n\"\\\0"))
"\t\r\n\"\\\0".to_owned()
)))
); );
// Invalid "\<char>" escape // Invalid "\<char>" escape
@ -3083,6 +3099,12 @@ mod tests {
parse(r#"branches("\y")"#), parse(r#"branches("\y")"#),
Err(RevsetParseErrorKind::SyntaxError) Err(RevsetParseErrorKind::SyntaxError)
); );
// Single-quoted raw string
assert_eq!(parse(r#"branches('')"#), Ok(branches_expr("")));
assert_eq!(parse(r#"branches('a\n')"#), Ok(branches_expr(r"a\n")));
assert_eq!(parse(r#"branches('\')"#), Ok(branches_expr(r"\")));
assert_eq!(parse(r#"branches('"')"#), Ok(branches_expr(r#"""#)));
} }
#[test] #[test]
@ -3117,6 +3139,12 @@ mod tests {
"foo".to_owned() "foo".to_owned()
))) )))
); );
assert_eq!(
parse(r#"branches(exact:'\')"#),
Ok(RevsetExpression::branches(StringPattern::Exact(
r"\".to_owned()
)))
);
assert_eq!( assert_eq!(
parse(r#"branches(bad:"foo")"#), parse(r#"branches(bad:"foo")"#),
Err(RevsetParseErrorKind::InvalidFunctionArguments { Err(RevsetParseErrorKind::InvalidFunctionArguments {
@ -3426,8 +3454,8 @@ mod tests {
// String literal should not be substituted with alias. // String literal should not be substituted with alias.
assert_eq!( assert_eq!(
parse_with_aliases(r#"A|"A""#, [("A", "a")]).unwrap(), parse_with_aliases(r#"A|"A"|'A'"#, [("A", "a")]).unwrap(),
parse("a|A").unwrap() parse("a|A|A").unwrap()
); );
// Alias can be substituted to string literal. // Alias can be substituted to string literal.