Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ If the expression is invalid, `Success` is `false`, and `ErrorMessage` describes
Identifiers are resolved in a case-insensitive manner, so `math.min`, `Math.Min`, and `MATH.MIN`
refer to the same method.

`true`, `false`, and `null` are keywords. As in C#, prefix a name with `@` to use it as an identifier,
for example `item.@null` for a member named `null`.

### Evaluating expressions

`Evaluate` parses, compiles, and runs an expression in a single call:
Expand Down
14 changes: 12 additions & 2 deletions src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,21 @@ private static Parser<Expr> CreateParser()
Character.LetterOrDigit,
L('_')).Void();

var identifier =
var identifier_name =
Seq(
identifier_start,
identifier_body.Many()
).Map(m => new Identifier(m.ToString())).As("identifier");
).Map(m => new Identifier(m.ToString()));

//
// As in C#, the '@' prefix makes a verbatim identifier, which can be a keyword, as in 'x.@null'.
// The prefix is not part of the name. The keyword check does not match the prefix, so a verbatim
// identifier passes Not(keyword) wherever an identifier is expected.
//
var identifier =
L('@').Optional()
.Then(identifier_name)
.As("identifier");

var keyword =
Seq(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@ public override T Accept<T>(ExprVisitor<T> visitor) =>

/// <inheritdoc />
public override string ToString() =>
Value.ToString();
Value.ToSourceString();
}
}
2 changes: 1 addition & 1 deletion src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public override T Accept<T>(ExprVisitor<T> visitor) =>
/// </returns>
public override string ToString() => UnaryType switch
{
UnaryType.Convert => $"({Operand} :> {Operator})",
UnaryType.Convert => $"({Operand} :> {Operator.ToSourceString()})",
_ => $"{Operator}({Operand})"
};
}
Expand Down
16 changes: 16 additions & 0 deletions src/Ramstack.ExpressionParser/Expressions/Identifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ public sealed class Identifier(string name)
/// <summary>
/// Gets the name of the identifier or the symbol of the operator.
/// </summary>
/// <remarks>
/// The name of a verbatim identifier, such as <c>@null</c>, does not include the <c>@</c> prefix.
/// </remarks>
public string Name { get; } = name;

/// <summary>
Expand All @@ -22,4 +25,17 @@ public void Deconstruct(out string name) =>
/// <inheritdoc />
public override string ToString() =>
Name;

/// <summary>
/// Returns the name as it is written in an expression.
/// </summary>
/// <returns>
/// The name, prefixed with <c>@</c> if it is a keyword, such as <c>true</c>,
/// so that the parser reads it back as an identifier.
/// </returns>
/// <remarks>
/// The keywords are those of the <c>keyword</c> rule in <see cref="ExpressionParser" />.
/// </remarks>
internal string ToSourceString() =>
Name is "true" or "false" or "null" ? $"@{Name}" : Name;
}
12 changes: 12 additions & 0 deletions tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,18 @@ int.true:>text
double.false:>text
(1:8) Expected identifier

@true
Cannot resolve symbol 'true'.

"abc".@null
Cannot resolve symbol 'null'.

"abc".@
(1:7) Expected identifier

@ true
(1:1) Expected [!+\-~], double-quoted string, quoted-character, 'true', 'false', 'null', identifier, or '('

Math.int:>text
Cannot resolve symbol 'int'.

Expand Down
28 changes: 28 additions & 0 deletions tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,25 @@ public void Subparser_DotWithoutMember_StopsBeforeDot(string source, string expe
Assert.That(source[result.Length..], Is.EqualTo(rest));
}

[TestCase("@true", 1)]
[TestCase("@false + @null", 5)]
[TestCase("Self.@true", 1)]
[TestCase("Self.@null", 3)]
[TestCase("@Value", 4)]
[TestCase("Self.@Value", 4)]
public void Evaluate_VerbatimIdentifier_ResolvesMemberByName(string expression, int expected) =>
Assert.That(ExpressionParser.Evaluate(expression, new KeywordContext()), Is.EqualTo(expected));

[TestCase("@true", "@true")]
[TestCase("x.@null", "x.@null")]
[TestCase("@false(1)[2]", "@false(1)[2]")]
[TestCase("x :> @null", "(x :> @null)")]
[TestCase("@trueValue", "trueValue")]
[TestCase("@x.@y", "x.y")]
[TestCase("1 :> @long", "(1 :> long)")]
public void ToString_VerbatimIdentifier_PrefixesOnlyKeywords(string source, string expected) =>
Assert.That(ExpressionParser.Parser.Parse(source).Value?.ToString(), Is.EqualTo(expected));

[Test]
public void MaxDepthTest()
{
Expand Down Expand Up @@ -1474,4 +1493,13 @@ public class ArrayContext
public int[][] Jagged { get; } = [[1], [1, 2, 3]];
public Array Untyped { get; } = new[] { "a", "b" };
}

public class KeywordContext
{
public int @true { get; } = 1;
public int @false { get; } = 2;
public int @null { get; } = 3;
public int Value { get; } = 4;
public KeywordContext Self => this;
}
}