![]() |
VOOZH | about |
dotnet add package MSL.Lexi --version 2.2.2
NuGet\Install-Package MSL.Lexi -Version 2.2.2
<PackageReference Include="MSL.Lexi" Version="2.2.2" />
<PackageVersion Include="MSL.Lexi" Version="2.2.2" />Directory.Packages.props
<PackageReference Include="MSL.Lexi" />Project file
paket add MSL.Lexi --version 2.2.2
#r "nuget: MSL.Lexi, 2.2.2"
#:package MSL.Lexi@2.2.2
#addin nuget:?package=MSL.Lexi&version=2.2.2Install as a Cake Addin
#tool nuget:?package=MSL.Lexi&version=2.2.2Install as a Cake Tool
👁 .NET Tests
👁 .NET Publish
👁 Nuget
👁 Nuget
👁 Nuget
👁 Nuget
A regex based lexer for dotnet. The lexer supports simple L1 recursive descent parsers.
https://www.nuget.org/packages/MSL.Lexi/
dotnet add package MSL.Lexi
There are two sample projects that demonstrate how to use the lexer within a recursive descent parser. One is a simple math parser and the other is a predicate expression parser. Each project includes a parser library, a set of tests for the parser, and a REPL console application that allows you to interact with the parser.
See Math.Parser and Predicate.Parser for working samples.
math:> (1 + 1) / 2 * 3
BinaryOperation
Left Expression
BinaryOperation
Left Expression
Group Expression
BinaryOperation
Left Expression
Number: 1
Op Add
Right Expression
Number: 1
Op Divide
Right Expression
Number: 2
Op Multiply
Right Expression
Number: 3
-------------
result:> 3
math:>
predicate:> from Address where Street startswith "Cypress" and (City = "Tampa" or City = "Miami")
From: Address
LogicalExpression:
|-- L: ComparisonExpression:
|-- L: |-- L: Identifier: Street
|-- L: |-- Operator: StartsWith
|-- L: |-- R: StringLiteral: Cypress
|-- Operator: And
|-- R: ParentheticalExpression:
|-- R: |-- (: LogicalExpression:
|-- R: |-- (: |-- L: ComparisonExpression:
|-- R: |-- (: |-- L: |-- L: Identifier: City
|-- R: |-- (: |-- L: |-- Operator: Equal
|-- R: |-- (: |-- L: |-- R: StringLiteral: Tampa
|-- R: |-- (: |-- Operator: Or
|-- R: |-- (: |-- R: ComparisonExpression:
|-- R: |-- (: |-- R: |-- L: Identifier: City
|-- R: |-- (: |-- R: |-- Operator: Equal
|-- R: |-- (: |-- R: |-- R: StringLiteral: Miami
predicate:>
You specify the vocabulary with the VocabularyBuilder which returns a lexer from the Build method.
Here's a sample from the Math.Parser project:
public static IServiceCollection AddParser(this IServiceCollection services)
{
var builder = VocabularyBuilder
.Create(RegexOptions.CultureInvariant)
.Match("false", TokenIds.FALSE)
.Match("true", TokenIds.TRUE)
.Match(CommonPatterns.IntegerLiteral(), TokenIds.INTEGER_LITERAL)
.Match(CommonPatterns.FloatingPointLiteral(), TokenIds.FLOATING_POINT_LITERAL)
.Match(CommonPatterns.ScientificNotationLiteral(), TokenIds.SCIENTIFIC_NOTATION_LITERAL)
.Match(@"\+", TokenIds.ADD)
.Match("-", TokenIds.SUBTRACT)
.Match(@"\*", TokenIds.MULTIPLY)
.Match("/", TokenIds.DIVIDE)
.Match("%", TokenIds.MODULUS)
.Match(@"\(", TokenIds.OPEN_PARENTHESIS)
.Match(@"\)", TokenIds.CLOSE_PARENTHESIS);
// register the lexer with the service collection
services.TryAddSingleton(serviceProvider => builder.Build());
// lexer is injected into Parser constructor:
// public sealed class Parser(Lexer lexer)
services.TryAddTransient<Parser>();
return services;
}
The Predicate.Parser project works the same way:
public static IServiceCollection AddParser(this IServiceCollection services)
{
var builder = VocabularyBuilder
.Create(RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)
.Match($"{nameof(TokenIds.FROM)}", TokenIds.FROM)
.Match($"{nameof(TokenIds.WHERE)}", TokenIds.WHERE)
.Match($"{nameof(TokenIds.SKIP)}", TokenIds.SKIP)
.Match($"{nameof(TokenIds.TAKE)}", TokenIds.TAKE)
.Match($"{nameof(TokenIds.CONTAINS)}", TokenIds.CONTAINS)
.Match("startswith|sw", TokenIds.STARTS_WITH)
.Match("endswith|ew", TokenIds.ENDS_WITH)
.Match(@"and|&&", TokenIds.LOGICAL_AND)
.Match(@"or|\|\|", TokenIds.LOGICAL_OR)
.Match("null|NULL", TokenIds.NULL_LITERAL)
.Match(CommonPatterns.Identifier(), TokenIds.IDENTIFIER)
.Match("true", TokenIds.TRUE)
.Match("false", TokenIds.FALSE)
.Match(CommonPatterns.IntegerLiteral(), TokenIds.INTEGER_LITERAL)
.Match(CommonPatterns.FloatingPointLiteral(), TokenIds.FLOATING_POINT_LITERAL)
.Match(CommonPatterns.ScientificNotationLiteral(), TokenIds.SCIENTIFIC_NOTATION_LITERAL)
.Match(CommonPatterns.QuotedStringLiteral(), TokenIds.STRING_LITERAL)
.Match(CommonPatterns.CharacterLiteral(), TokenIds.CHAR_LITERAL)
.Match(@"\(", TokenIds.OPEN_PARENTHESIS)
.Match(@"\)", TokenIds.CLOSE_PARENTHESIS)
.Match("=|==", TokenIds.EQUAL)
.Match(">", TokenIds.GREATER_THAN)
.Match(">=", TokenIds.GREATER_THAN_OR_EQUAL)
.Match("<", TokenIds.LESS_THAN)
.Match("<=", TokenIds.LESS_THAN_OR_EQUAL)
.Match("!=", TokenIds.NOT_EQUAL);
// register the lexer with the service collection
services.TryAddSingleton(serviceProvider => builder.Build());
// lexer is injected into Parser constructor:
// public sealed class Parser(Lexer lexer)
services.TryAddTransient<Parser>();
return services;
}
The Math.Parser implements a classic term/factor recusive descent parser. The parser returns an expression tree that can be evaluated to get the result.
We use the lexer to get the next token with calls to one of the Lexer.NextMatch overloads as required.
using Lexi;
using Math.Parser.Exceptions;
using Math.Parser.Expressions;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace Math.Parser;
public sealed class Parser(Lexer lexer)
{
private readonly Lexer lexer = lexer
?? throw new ArgumentNullException(nameof(lexer));
// Parse the source string into an expression tree.
public Expression Parse(string source)
{
ArgumentNullException.ThrowIfNull(source);
return ParseTerm(new Source(source))
.Expression;
}
private readonly ref struct ParseResult(
Expression expression,
MatchResult matchResult)
{
public readonly Expression Expression = expression;
public readonly MatchResult MatchResult = matchResult;
}
private ParseResult ParseTerm(Source script)
{
var left = ParseFactor(script);
var matchResult = left.MatchResult;
matchResult = lexer.NextMatch(matchResult);
while (!matchResult.Source.IsEndOfSource
&& matchResult.Symbol.IsOperator()
&& matchResult.Symbol.IsTerm())
{
var right = ParseFactor(matchResult.Source);
left = new(
new BinaryOperation(
left.Expression,
right.Expression,
matchResult.Symbol.TokenId),
right.MatchResult);
matchResult = lexer.NextMatch(right.MatchResult);
}
return left;
}
private ParseResult ParseFactor(Source script)
{
var left = ParseValue(script);
var matchResult = left.MatchResult;
matchResult = lexer.NextMatch(matchResult);
while (!matchResult.Source.IsEndOfSource
&& matchResult.Symbol.IsOperator()
&& matchResult.Symbol.IsFactor())
{
var right = ParseValue(matchResult.Source);
left = new(
new BinaryOperation(
left.Expression,
right.Expression,
matchResult.Symbol.TokenId),
right.MatchResult);
matchResult = lexer.NextMatch(right.MatchResult);
}
return left;
}
private ParseResult ParseValue(Source source)
{
if (source.IsEndOfSource)
{
throw new UnexpectedEndOfSourceException("Unexpected end of source");
}
var matchResult = lexer.NextMatch(source);
if (matchResult.Symbol.IsNumericLiteral())
{
return new(ParseNumber(in matchResult), matchResult);
}
else if (matchResult.Symbol.IsOpenCircumfixDelimiter())
{
var term = ParseTerm(matchResult.Source);
matchResult = lexer.NextMatch(term.MatchResult);
if (matchResult.Symbol.IsCloseCircumfixDelimiter())
{
return new(new Group(term.Expression), matchResult);
}
if (matchResult.Symbol.IsMatch)
{
throw new UnexpectedTokenException($"unexpected token '{matchResult.Source.ReadSymbol(in matchResult.Symbol)}' at {matchResult.Symbol.Offset}. expected close parenthesis.");
}
throw new UnexpectedEndOfSourceException($"unexpected token '{source.Remaining()}' at {matchResult.Symbol.Offset}. expected close parenthesis.");
}
if (matchResult.Symbol.IsMatch)
{
throw new UnexpectedTokenException($"unexpected token '{matchResult.Source.ReadSymbol(in matchResult.Symbol)}' at {matchResult.Symbol.Offset}. expected number or open parenthesis.");
}
throw new UnexpectedTokenException($"unexpected token '{source.Remaining()}' at {matchResult.Symbol.Offset}. expected number or open parenthesis.");
}
[SuppressMessage("Style", "IDE0072:Add missing cases", Justification = "switch is complete")]
private static Number ParseNumber(ref readonly MatchResult matchResult)
{
var value = matchResult
.Source
.ReadSymbol(in matchResult.Symbol);
// todo: use TryParse and add error msg on false
return matchResult.Symbol.TokenId switch
{
TokenIds.INTEGER_LITERAL => new Number(
NumericTypes.Integer,
Int32.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture)),
TokenIds.FLOATING_POINT_LITERAL => new Number(
NumericTypes.FloatingPoint,
Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture)),
TokenIds.SCIENTIFIC_NOTATION_LITERAL => new Number(
NumericTypes.ScientificNotation,
Double.Parse(value, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture)),
_ => new Number(NumericTypes.NotANumber, 0)
};
}
}
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net6.0 net6.0 is compatible. net6.0-android net6.0-android was computed. net6.0-ios net6.0-ios was computed. net6.0-maccatalyst net6.0-maccatalyst was computed. net6.0-macos net6.0-macos was computed. net6.0-tvos net6.0-tvos was computed. net6.0-windows net6.0-windows was computed. net7.0 net7.0 is compatible. net7.0-android net7.0-android was computed. net7.0-ios net7.0-ios was computed. net7.0-maccatalyst net7.0-maccatalyst was computed. net7.0-macos net7.0-macos was computed. net7.0-tvos net7.0-tvos was computed. net7.0-windows net7.0-windows was computed. net8.0 net8.0 is compatible. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 was computed. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 was computed. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
This package is not used by any NuGet packages.
This package is not used by any popular GitHub repositories.