diff --git a/.gitattributes b/.gitattributes index 1ff0c42..1366fc5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -61,3 +61,14 @@ #*.PDF diff=astextplain #*.rtf diff=astextplain #*.RTF diff=astextplain + +############################################################################### +# The target filter parser is generated (Source/TargetFilter/regenerate.sh). +# The grammar and the scripts are read as checked out, so every machine reads +# the same text; the generated folder is kept byte for byte as the generator +# writes it (CRLF), and its rule comes last so that no rule above converts it. +############################################################################### +*.gram text eol=lf +*.sh text eol=lf +Source/TargetFilter/dotgram.pin text eol=lf +Source/TargetFilter/Generated/** -text diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 3b12186..935cc0c 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -5,6 +5,7 @@ on: branches: [ "master" ] pull_request: branches: [ "master" ] + workflow_dispatch: jobs: build: @@ -119,18 +120,38 @@ jobs: public static void OnBeforeCall(InterceptInfo info) { Calls++; } } + // Applied to a type with a TargetFilter, so that a filter is selected by the packed generator on the oldest toolchain. + // Filters are parsed by the hand-written parser for now; this covers the generated one once filters are parsed by it. + [Aspect(OnBeforeCall = nameof(OnBeforeCall))] + [AttributeUsage(AttributeTargets.Class)] + sealed class FilteredAttribute : Attribute + { + public static int Calls; + public string? TargetFilter { get; set; } + public static void OnBeforeCall(InterceptInfo info) { Calls++; } + } + static class Service { [Count] public static int Twice(int x) { return x * 2; } } + [Filtered(TargetFilter = "contains: Selected")] + static class FilteredService + { + public static int Selected(int x) { return x + 1; } + public static int Other(int x) { return x + 2; } + } + static class Program { static int Main() { var result = Service.Twice(21); - Console.WriteLine($"result={result} calls={CountAttribute.Calls}"); - return result == 42 && CountAttribute.Calls == 1 ? 0 : 1; + var filtered = FilteredService.Selected(1) + FilteredService.Other(1); + Console.WriteLine($"result={result} calls={CountAttribute.Calls} filtered={filtered} filteredCalls={FilteredAttribute.Calls}"); + // Only the call the filter selects is intercepted. + return result == 42 && CountAttribute.Calls == 1 && filtered == 5 && FilteredAttribute.Calls == 1 ? 0 : 1; } } EOF @@ -139,3 +160,60 @@ jobs: cmp "$RUNNER_TEMP/feed/AspectGenerator.$ASPECT_GENERATOR_VERSION.nupkg" "$dir/packages/aspectgenerator/${ASPECT_GENERATOR_VERSION,,}/aspectgenerator.${ASPECT_GENERATOR_VERSION,,}.nupkg" (cd "$dir" && dotnet build --configuration Release --no-restore && dotnet run --configuration Release --no-build) done + + # The target filter parser is generated ahead of the build (Source/TargetFilter/regenerate.sh, at the DotGram commit and + # SDK in Source/TargetFilter/dotgram.pin) and committed. This job regenerates it exactly as a developer does and fails + # when the committed folder differs: a grammar edited without regenerating, a stale or hand-edited file, a leftover file. + # Windows checks as well that the checkout's line-ending conversion leaves the generated folder byte for byte as written. + filter-parser: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + + runs-on: ${{ matrix.os }} + + steps: + - uses: actions/checkout@v4 + - name: Read the pin + id: pin + shell: bash + run: | + set -euo pipefail + sdk="$(sed -n 's/^sdk=//p' Source/TargetFilter/dotgram.pin | tr -d '\r')" + [ -n "$sdk" ] || { echo "Source/TargetFilter/dotgram.pin has no sdk=" >&2; exit 1; } + echo "sdk=$sdk" >> "$GITHUB_OUTPUT" + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: ${{ steps.pin.outputs.sdk }} + - name: Select the pinned SDK + shell: bash + # The runner image may have a newer SDK installed; the script refuses anything but the pinned one. + run: dotnet new globaljson --sdk-version "${{ steps.pin.outputs.sdk }}" --roll-forward disable --force + - name: Regenerate the parser + shell: bash + run: Source/TargetFilter/regenerate.sh + - name: The committed parser is current + shell: bash + run: | + status="$(git status --porcelain --untracked-files=all -- Source/TargetFilter)" + if [ -n "$status" ]; then + echo "Source/TargetFilter differs after regeneration; run Source/TargetFilter/regenerate.sh and commit the result:" >&2 + echo "$status" >&2 + git --no-pager diff --stat -- Source/TargetFilter >&2 + exit 1 + fi + - name: The local DotGram mode refuses to pack + if: runner.os == 'Linux' + shell: bash + # -p:DotGramLocal=true builds an unpinned parser, so a package must never come out of it. The scratch checkout the + # script just made is the DotGram checkout. + run: | + set -euo pipefail + commit="$(sed -n 's/^commit=//p' Source/TargetFilter/dotgram.pin | tr -d '\r')" + root="${TMPDIR:-/tmp}/aspectgenerator-dotgram-${commit:0:12}/dotgram" + if dotnet pack Source/AspectGenerator.csproj --configuration Release -p:DotGramLocal=true -p:DotGramRoot="$root" -nodeReuse:false; then + echo "Packing succeeded with DotGramLocal=true; it must fail." >&2 + exit 1 + fi diff --git a/AGENTS.md b/AGENTS.md index 259ac48..887604b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,3 +9,14 @@ Current notes: - Preserve CRLF line endings for touched repository files. - Do not add new NuGet packages, template engines, formatters, source-generation helper libraries, or build tools unless the maintainer explicitly asks for that dependency. - Do not replace internal code generation with Scriban, Handlebars.Net, CSharpier, or other external templating/formatting tools as an automatic refactoring step. + +## Target filter parser + +The parser of the target filter language is written in DotGram (`Source/TargetFilter/TargetFilter.gram`) and generated ahead of the build. The generated C# in `Source/TargetFilter/Generated` is committed and compiled like any other source: the build and the package have no DotGram dependency, and nothing is generated at build time. + +What is proven today: the generated parser compiles against Roslyn 4.12 on `netstandard2.0` inside the generator assembly, and the unit tests (`TargetFilterParserSmokeTests`) exercise it. Production target filters are still parsed by the hand-written parser, so the `minimum-sdk` consumer's `TargetFilter` does not run the generated parser yet; that check covers it once filters are parsed by it. + +- After any change to `TargetFilter.gram` (or to a type it builds), run `Source/TargetFilter/regenerate.sh` and commit the changed files with it. Never edit `Generated` by hand; the next run overwrites it. The script works in Git Bash on Windows too. +- `Source/TargetFilter/dotgram.pin` names the DotGram commit and the exact .NET SDK the generation uses. The script builds `DotGram.Cli` at that commit into a scratch folder (`DOTGRAM_SCRATCH`, `DOTGRAM_REPO` to fetch from a local clone) and refuses to run under another SDK: select the pinned one first, for instance with an untracked `global.json` (the refusal message prints it). Move the pin only to a green commit of the DotGram repository, in a commit of its own with the regenerated folder. +- The `filter-parser` CI job runs the same script and fails when `git status` shows any difference in `Source/TargetFilter`. The script itself fails when `Generated` holds a file the manifest (`.dotgram.json`) does not list, which the generator would leave in place. `.gitattributes` keeps `*.gram` and scripts at LF and the generated folder byte for byte (`-text`, last rule). +- `-p:DotGramLocal=true -p:DotGramRoot=` builds the parser from the grammar with that checkout as the generator and leaves the committed folder out (default `DotGramRoot` is `..\dotgram`, next to this repository). It is for trying a DotGram change; the committed folder is what ships. In this mode automatic packaging is off and an explicit `dotnet pack` fails, so a package never carries an unpinned parser. diff --git a/Directory.Build.props b/Directory.Build.props index b9c8473..393ee41 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -5,6 +5,12 @@ latest + + + false + $(MSBuildThisFileDirectory)..\dotgram + + diff --git a/Source/AspectGenerator.csproj b/Source/AspectGenerator.csproj index 959d232..53d1354 100644 --- a/Source/AspectGenerator.csproj +++ b/Source/AspectGenerator.csproj @@ -25,6 +25,35 @@ true + + + + + + + false + + + + + + + + + + + + + + diff --git a/Source/TargetFilter/Generated/.dotgram.json b/Source/TargetFilter/Generated/.dotgram.json new file mode 100644 index 0000000..df8e73e --- /dev/null +++ b/Source/TargetFilter/Generated/.dotgram.json @@ -0,0 +1,10 @@ +{ + "format": 1, + "tool": "0.3.0", + "generator": "0.3.0", + "files": [ + { "name": "AspectGenerator.TargetFilterParser.g.cs" }, + { "name": "DotGram.Attributes.g.cs" }, + { "name": "Microsoft.CodeAnalysis.EmbeddedAttribute.cs" } + ] +} diff --git a/Source/TargetFilter/Generated/AspectGenerator.TargetFilterParser.g.cs b/Source/TargetFilter/Generated/AspectGenerator.TargetFilterParser.g.cs new file mode 100644 index 0000000..32f8317 --- /dev/null +++ b/Source/TargetFilter/Generated/AspectGenerator.TargetFilterParser.g.cs @@ -0,0 +1,1615 @@ +// +#nullable enable + +namespace AspectGenerator +{ + using System; + + partial class TargetFilterParser + { + /// Parses the whole input as Line. + /// + /// The input is not Line. TryParseLine answers instead. + /// + public static TargetFilterLine ParseLine(string input) + { + var match = TryParseLine(input); + + if (match.IsSuccess) + return match.Value; + + var error = match.Error!; + + throw new global::System.FormatException( + (error.EndsWith(".", global::System.StringComparison.Ordinal) ? error.Substring(0, error.Length - 1) : error) + + " at " + match.Position.ToString(global::System.Globalization.CultureInfo.InvariantCulture) + "."); + } + + /// Parses the whole input as Line, answering rather than throwing. + public static Match TryParseLine(string input) + { + var text = global::System.MemoryExtensions.AsSpan(input); + var failure = new Failure { Quiet = true }; + + var end = RecWhole_DotGram_Line(text, 0, ref failure, out var recognized); + + if (end < 0) + { + failure = new Failure { Unasked = true, Doors = failure.Position }; + end = RecWhole_DotGram_Line(text, 0, ref failure, out recognized); + } + + if (end < 0) + { + var starved = failure.OutOfInput == failure.Position + 1 || failure.Position >= text.Length; + + var otherwise = starved + ? "Expected more input." + : "Input does not match 'Line'."; + + return Match.Failed(starved ? Outcome.Starved : Outcome.NoMatch, otherwise, failure.Position, failure.Expected, Handed_DotGram(failure.ExpectedMore)); + } + + return Match.Success(recognized, 0, end); + } + + /// Parses the whole input as Line, answering only whether it is one. + /// + /// Nothing is said about a refusal: TryParseLine returning a match says where and why. + /// + public static bool TryParseLine(string input, out TargetFilterLine value) + { + var text = global::System.MemoryExtensions.AsSpan(input); + var failure = new Failure { Quiet = true }; + + var end = RecWhole_DotGram_Line(text, 0, ref failure, out var recognized); + + if (end < 0) + { + value = default!; + return false; + } + + value = recognized; + + return true; + } + + /// Reads a Line beginning at . + /// + /// The input is not required to end there: what comes back says where the + /// reading began and how far it got, so a caller may go on from it. A position + /// is an offset into the text. + /// + public static Match TryParseLine(string input, int at) + { + if (at < 0 || at > input.Length) + { + return Match.Failed(Outcome.NoMatch, "Position " + at.ToString() + " is outside the input.", at, null, null); + } + + var text = global::System.MemoryExtensions.AsSpan(input); + var failure = new Failure { Quiet = true }; + + var end = Rec_DotGram_Line(text, at, ref failure, out var recognized); + + if (end < 0) + { + failure = new Failure { Unasked = true, Doors = failure.Position }; + end = Rec_DotGram_Line(text, at, ref failure, out recognized); + } + + if (end < 0) + { + if (failure.Position < at) + failure.Position = at; + + var starved = failure.OutOfInput == failure.Position + 1 || failure.Position >= text.Length; + + var otherwise = starved + ? "Expected more input." + : "Input does not match 'Line'."; + + return Match.Failed(starved ? Outcome.Starved : Outcome.NoMatch, otherwise, failure.Position, failure.Expected, Handed_DotGram(failure.ExpectedMore)); + } + + return Match.Success(recognized, at, end - at); + } + + /// Reads a Line at , answering only whether one is there. + /// + /// Nothing is said about a refusal: TryParseLine returning a match says where and why. + /// On a reading, moves to the end of what was read; on a + /// refusal it stays where it was. + /// + public static bool TryParseLine(string input, ref int at, out TargetFilterLine value) + { + if (at < 0 || at > input.Length) + throw new global::System.ArgumentOutOfRangeException(nameof(at)); + + var text = global::System.MemoryExtensions.AsSpan(input); + var failure = new Failure { Quiet = true }; + + var end = Rec_DotGram_Line(text, at, ref failure, out var recognized); + + if (end < 0) + { + value = default!; + return false; + } + + value = recognized; + at = end; + + return true; + } + + /// Reads a Line inside a window of the input. + /// + /// The reading begins at and sees no character from + /// at + length on; it is not required to reach that far, and what comes back + /// says how far it got. Positions are offsets into the whole input. + /// + public static Match TryParseLine(string input, int at, int length) + { + if (at < 0 || length < 0 || at > input.Length - length) + { + return Match.Failed(Outcome.NoMatch, "The window " + at.ToString() + ".." + (at + length).ToString() + " is outside the input.", at, null, null); + } + + var text = global::System.MemoryExtensions.AsSpan(input, 0, at + length); + var failure = new Failure { Quiet = true }; + + var end = Rec_DotGram_Line(text, at, ref failure, out var recognized); + + if (end < 0) + { + failure = new Failure { Unasked = true, Doors = failure.Position }; + end = Rec_DotGram_Line(text, at, ref failure, out recognized); + } + + if (end < 0) + { + if (failure.Position < at) + failure.Position = at; + + var starved = failure.OutOfInput == failure.Position + 1 || failure.Position >= text.Length; + + var otherwise = starved + ? "Expected more input." + : "Input does not match 'Line'."; + + return Match.Failed(starved ? Outcome.Starved : Outcome.NoMatch, otherwise, failure.Position, failure.Expected, Handed_DotGram(failure.ExpectedMore)); + } + + return Match.Success(recognized, at, end - at); + } + + /// Reads a Line at , answering only whether one is there. + /// + /// Nothing is said about a refusal: TryParseLine returning a match says where and why. + /// On a reading, moves to the end of what was read; on a + /// refusal it stays where it was. + /// + public static bool TryParseLine(string input, ref int at, int length, out TargetFilterLine value) + { + if (at < 0 || length < 0 || at > input.Length - length) + throw new global::System.ArgumentOutOfRangeException(nameof(at)); + + var text = global::System.MemoryExtensions.AsSpan(input, 0, at + length); + var failure = new Failure { Quiet = true }; + + var end = Rec_DotGram_Line(text, at, ref failure, out var recognized); + + if (end < 0) + { + value = default!; + return false; + } + + value = recognized; + at = end; + + return true; + } + + static string New_DotGram_Operator(string t) => +#line 8 "../TargetFilter.gram" + (t); +#line default + + static string New_DotGram_MatcherPrefix(string t) => +#line 10 "../TargetFilter.gram" + (t); +#line default + + static string New_DotGram_Rest(string t) => +#line 12 "../TargetFilter.gram" + (t); +#line default + + static TargetFilterLine New_DotGram_Line(string? op, string? matcher, string rest) => +#line 15 "../TargetFilter.gram" + (new TargetFilterLine(op, matcher, rest)); +#line default + + private ref struct Reader_DotGram + { + readonly global::System.ReadOnlySpan text; + internal Failure failure; + readonly Ways_DotGram ways; + internal string last0; + internal TargetFilterLine last1; + internal int unbuilt; + internal Failure replayed; + internal int replayedMore; + + internal Reader_DotGram(global::System.ReadOnlySpan text, Ways_DotGram ways) + { + this.text = text; + this.failure = default; + this.ways = ways; + this.last0 = default!; + this.last1 = default!; + this.unbuilt = default!; + this.replayed = default!; + this.replayedMore = default!; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + int Stood_DotGram(int u, int s) + { + if (u == 2) + { + replayed = failure; + replayedMore = failure.ExpectedMore == null ? 0 : failure.ExpectedMore.Count; + unbuilt = 0; + ways.Cursor = s; + + return 3; + } + + Replayed_DotGram(); + + return 0; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + void Replayed_DotGram() + { + var more = failure.ExpectedMore; + + failure = replayed; + + if (more != null && more.Count > replayedMore) + more.RemoveRange(replayedMore, more.Count - replayedMore); + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + int Retried_DotGram(int u) + { + if (u == 1) + { + unbuilt = 1; + + return 2; + } + + return u == 0 && unbuilt == 0 ? 1 : u; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + void Undeferred_DotGram(int u) + { + if (u == 2) + unbuilt = 0; + else if (u == 3) + Replayed_DotGram(); + } + + public int Read_Line(int pos) + { + var s = ways.Cursor; + var u = 0; + + while (true) + { + var q = ReadBody_Line(pos); + + if (q >= 0) + { + if (u > 1) + { + u = Stood_DotGram(u, s); + + if (u > 0) + continue; + } + + return q; + } + + if (ways.Cursor > s && ways.Retry(s)) + { + u = Retried_DotGram(u); + + continue; + } + + Undeferred_DotGram(u); + + return -1; + } + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int ReadBody_Line(int pos) + { + var p = pos; + var c = '\0'; + string? r0 = default; + string? r1 = default; + string r2 = default!; + var t0 = 0; + while (true) + { + if (t0 >= 1) + break; + + var o1 = (uint)p < (uint)text.Length; + + if (o1) + { + c = text[p]; + o1 = c <= 255 && RecognizeClass0_DotGram[c] != 0; + } + + if (!o1 && (failure.Quiet || p < failure.Doors)) + { + break; + } + + var w0 = -1; + var d0 = 0; + + if (ways.Cursor < ways.Count) + { + w0 = ways.Cursor; + d0 = ways.Items[w0 * 2]; + ways.Cursor++; + } + else + { + w0 = ways.Open(1); + } + + if (d0 == 1) + break; + + var q0 = -1; + + q0 = ReadPart0_Line(p, ref r0); + + if (q0 < 0) + { + } + + if (q0 < 0) + { + r0 = default; + + ways.Next(w0, 1); + + break; + } + + p = q0; + t0++; + } + var t1 = 0; + while (true) + { + if (t1 >= 1) + break; + + var o4 = (uint)p < (uint)text.Length; + + if (o4) + { + c = text[p]; + o4 = c <= 255 && RecognizeClass1_DotGram[c] != 0; + } + + if (!o4 && (failure.Quiet || p < failure.Doors)) + { + break; + } + + var w3 = -1; + var d3 = 0; + + if (ways.Cursor < ways.Count) + { + w3 = ways.Cursor; + d3 = ways.Items[w3 * 2]; + ways.Cursor++; + } + else + { + w3 = ways.Open(1); + } + + if (d3 == 1) + break; + + var q1 = -1; + + q1 = ReadPart1_Line(p, ref r1); + + if (q1 < 0) + { + } + + if (q1 < 0) + { + r1 = default; + + ways.Next(w3, 1); + + break; + } + + p = q1; + t1++; + } + var q2 = Read_Rest(p); + if (q2 < 0) return -1; + p = q2; + r2 = last0; + var q3 = Read_eof(p); + if (q3 < 0) return -1; + p = q3; + if (unbuilt == 0) last1 = New_DotGram_Line(r0, r1, r2!); + return p; + } + + public int ReadPart0_Line(int pos, ref string? r0) + { + var p = pos; + var q0 = Read_Operator(p); + if (q0 < 0) return -1; + p = q0; + r0 = last0; + return p; + } + + public int ReadPart1_Line(int pos, ref string? r1) + { + var p = pos; + var q0 = Read_MatcherPrefix(p); + if (q0 < 0) return -1; + p = q0; + r1 = last0; + return p; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Read_Operator(int pos) + { + var p = pos; + var c = '\0'; + var a0 = -1; + var b0 = -1; + a0 = p; + if ((uint)p >= (uint)text.Length) + { + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(0)); + return -1; + } + c = text[p]; + if (!(c <= 255 && RecognizeClass0_DotGram[c] != 0)) + { + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(0)); + return -1; + } + p++; + b0 = p; + if (unbuilt == 0) last0 = New_DotGram_Operator((a0 < 0 ? string.Empty : text.Slice(a0, b0 - a0).ToString())!); + return p; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Read_MatcherPrefix(int pos) + { + var p = pos; + var c = '\0'; + var a0 = -1; + var b0 = -1; + a0 = p; + if ((uint)p >= (uint)text.Length) + { + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(4)); + return -1; + } + c = text[p]; + switch (c) + { + case 'c': + { + if ((uint)(p + 9) > (uint)text.Length) + { + p = RecognizeRanOut_DotGram(text, p, "contains:", false, !failure.Quiet, true, ref failure); + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(2)); + return -1; + } + if (!global::System.MemoryExtensions.SequenceEqual(text.Slice(p, 9), global::System.MemoryExtensions.AsSpan("contains:"))) + { + if (!failure.Quiet) + p = RecognizeAgreeing_DotGram(text, p, "contains:", false); + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(2)); + return -1; + } + p += 9; + break; + } + case 'p': + { + if ((uint)(p + 8) > (uint)text.Length) + { + p = RecognizeRanOut_DotGram(text, p, "pattern:", false, !failure.Quiet, true, ref failure); + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(1)); + return -1; + } + if (!global::System.MemoryExtensions.SequenceEqual(text.Slice(p, 8), global::System.MemoryExtensions.AsSpan("pattern:"))) + { + if (!failure.Quiet) + p = RecognizeAgreeing_DotGram(text, p, "pattern:", false); + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(1)); + return -1; + } + p += 8; + break; + } + case 'r': + { + if ((uint)(p + 6) > (uint)text.Length) + { + p = RecognizeRanOut_DotGram(text, p, "regex:", false, !failure.Quiet, true, ref failure); + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(3)); + return -1; + } + if (!global::System.MemoryExtensions.SequenceEqual(text.Slice(p, 6), global::System.MemoryExtensions.AsSpan("regex:"))) + { + if (!failure.Quiet) + p = RecognizeAgreeing_DotGram(text, p, "regex:", false); + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(3)); + return -1; + } + p += 6; + break; + } + default: + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(4)); + return -1; + } + b0 = p; + if (unbuilt == 0) last0 = New_DotGram_MatcherPrefix((a0 < 0 ? string.Empty : text.Slice(a0, b0 - a0).ToString())!); + return p; + } + + public int Read_Rest(int pos) + { + var p = pos; + var c = '\0'; + var a0 = -1; + var b0 = -1; + a0 = p; + while (true) + { + if ((uint)p >= (uint)text.Length) + break; + + c = text[p]; + + if (!(!(c == '\n' || c == '\r'))) + break; + + p++; + } + + b0 = p; + if (unbuilt == 0) last0 = New_DotGram_Rest((a0 < 0 ? string.Empty : text.Slice(a0, b0 - a0).ToString())!); + return p; + } + + public int Read_eof(int pos) + { + var p = pos; + failure.Looking++; + var q0 = ReadPart0_eof(p); + failure.Looking--; + + + if (q0 >= 0) + { + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(6)); + return -1; + } + return p; + } + + public int ReadPart0_eof(int pos) + { + var p = pos; + var c = '\0'; + if ((uint)p >= (uint)text.Length) + { + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(7)); + return -1; + } + c = text[p]; + p++; + return p; + } + + public int RecWholeRead_Line(int pos) + { + var s = ways.Cursor; + var u = 0; + + while (true) + { + var q = RecWholeReadBody_Line(pos); + + if (q >= 0) + { + if (u > 1) + { + u = Stood_DotGram(u, s); + + if (u > 0) + continue; + } + + return q; + } + + if (ways.Cursor > s && ways.Retry(s)) + { + u = Retried_DotGram(u); + + continue; + } + + Undeferred_DotGram(u); + + return -1; + } + } + + public int RecWholeReadBody_Line(int pos) + { + var p = pos; + var q0 = Read_Line(p); + if (q0 < 0) return -1; + p = q0; + if (p != text.Length) + { + Refused_DotGram(ref failure, p, ExpectedSet_DotGram(6)); + return -1; + } + return p; + } + + public int RecRead_Line(int pos) + { + var s = ways.Cursor; + var u = 0; + + while (true) + { + var q = RecReadBody_Line(pos); + + if (q >= 0) + { + if (u > 1) + { + u = Stood_DotGram(u, s); + + if (u > 0) + continue; + } + + return q; + } + + if (ways.Cursor > s && ways.Retry(s)) + { + u = Retried_DotGram(u); + + continue; + } + + Undeferred_DotGram(u); + + return -1; + } + } + + public int RecReadBody_Line(int pos) + { + var p = pos; + var q0 = Read_Line(p); + if (q0 < 0) return -1; + p = q0; + return p; + } + + } + + static int RecWhole_DotGram_Line(global::System.ReadOnlySpan text, int pos, ref Failure failure, out TargetFilterLine value) + { + var ways = Ways_DotGram.Rent(); + + try + { + var reader = new Reader_DotGram(text, ways); + + reader.failure = failure; + if (failure.Unasked) reader.unbuilt = 1; + + var end = reader.RecWholeRead_Line(pos); + + failure = reader.failure; + + if (end < 0) + { + value = default!; + + return end; + } + + value = reader.last1; + + return end; + } + finally + { + Ways_DotGram.Return(ways); + } + } + + static int Rec_DotGram_Line(global::System.ReadOnlySpan text, int pos, ref Failure failure, out TargetFilterLine value) + { + var ways = Ways_DotGram.Rent(); + + try + { + var reader = new Reader_DotGram(text, ways); + + reader.failure = failure; + if (failure.Unasked) reader.unbuilt = 1; + + var end = reader.RecRead_Line(pos); + + failure = reader.failure; + + if (end < 0) + { + value = default!; + + return end; + } + + value = reader.last1; + + return end; + } + finally + { + Ways_DotGram.Return(ways); + } + } + + + + static int RecognizeAgreeing_DotGram(global::System.ReadOnlySpan text, int p, string value, bool fold) + { + var i = 0; + + while (i < value.Length - 1 && (uint)(p + i) < (uint)text.Length && (text[p + i] == value[i] || fold && (uint)((value[i] | 0x20) - 'a') <= 'z' - 'a' && (text[p + i] | 0x20) == (value[i] | 0x20))) + i++; + + return p + i; + } + + static int RecognizeRanOut_DotGram(global::System.ReadOnlySpan text, int p, string value, bool fold, bool moves, bool marks, ref Failure failure) + { + var reach = RecognizeAgreeing_DotGram(text, p, value, fold); + + if ((uint)reach >= (uint)text.Length) + { + if (marks && p + 1 > failure.OutOfInput) failure.OutOfInput = p + 1; + } + + return moves ? reach : p; + } + + static readonly byte[] RecognizeClass0_DotGram = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; + + static readonly byte[] RecognizeClass1_DotGram = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; + + /// What kind of answer a publication gave (docs/syntax.md §7.5). + public enum Outcome + { + /// The input matched, and Value holds what it built. + Success, + + /// The input was there and did not fit. + NoMatch, + + /// The input ran out where more was needed. + Starved, + } + + /// What a publication answers with: the value, or why there is none. + public readonly struct Match + { + private readonly string[]? _expected; + + private readonly string[][]? _tied; + + private readonly string? _otherwise; + + private Match( + Outcome outcome, T value, long position, int length, + string[]? expected, string[][]? tied, + string? otherwise) + { + Outcome = outcome; + Value = value; + Position = position; + Length = length; + _expected = expected; + _tied = tied; + _otherwise = otherwise; + } + + /// Whether there is a value. + public bool IsSuccess { get { return Outcome == Outcome.Success; } } + + /// + /// Which kind of answer this is: the value, input that did not fit, or input + /// that ran out (docs/syntax.md §7.5). + /// + public Outcome Outcome { get; } + + /// What was recognized. Meaningless unless IsSuccess. + public T Value { get; } + + /// + /// Why nothing was recognized, or null. + /// + /// + /// Built where it is asked for rather than where the match failed, and built + /// again on each ask. A caller that only wants to know whether the input + /// matched pays for none of it, which is most callers and every one in a loop + /// over input that is expected to fail sometimes. + /// + public string? Error + { + get + { + if (IsSuccess) + return null; + + var expected = _expected; + + if (_tied != null) + { + var total = expected == null ? 0 : expected.Length; + + foreach (var each in _tied) + total += each.Length; + + var merged = new string[total]; + var at = 0; + + if (expected != null) + { + expected.CopyTo(merged, 0); + at = expected.Length; + } + + foreach (var each in _tied) + { + each.CopyTo(merged, at); + at += each.Length; + } + + expected = merged; + } + + if (expected == null || expected.Length == 0) + return _otherwise; + + // A rule that says what its own refusal says (docs/syntax.md §4's `on + // fail`) writes it as one item, marked with a character no grammar can + // write. Where one stands here it is the whole answer: the author took + // the wording, and what else could have stood here is not it. + for (var i = 0; i < expected.Length; i++) + if (expected[i].Length > 0 && expected[i][0] == '\u0000') + return expected[i].Substring(1); + + // A list cut at the cap ends with a mark no grammar can write (Truncated_DotGram); + // it is not a thing wanted, and the message says there were more. + var cut = false; + + for (var i = 0; i < expected.Length; i++) + if (expected[i] == "\u0001") + { + cut = true; + break; + } + + if (cut) + { + var named = new string[expected.Length]; + var count = 0; + + for (var i = 0; i < expected.Length; i++) + if (expected[i] != "\u0001") + named[count++] = expected[i]; + + expected = new string[count]; + global::System.Array.Copy(named, expected, count); + } + + // Two sites may ask for the same thing — a literal written in two rules, + // or the `<` that opens a type argument list in more than one — and a + // reader is owed one mention of it rather than one per site. Copied + // rather than compacted where it stands: without a tie this array is the + // one the generator declared `static readonly`, and rewriting that would + // change what every later failure says. + if (expected.Length > 1) + { + var unique = new string[expected.Length]; + var kept = 0; + + for (var i = 0; i < expected.Length; i++) + { + var seen = false; + + for (var j = 0; j < kept; j++) + if (string.Equals( + unique[j], expected[i], global::System.StringComparison.Ordinal)) + { + seen = true; + break; + } + + if (!seen) + unique[kept++] = expected[i]; + } + + if (kept < expected.Length) + { + expected = new string[kept]; + global::System.Array.Copy(unique, expected, kept); + } + } + + if (expected.Length == 0) + return "Expected many alternatives, among others."; + + var among = cut ? ", among others." : "."; + + if (expected.Length == 1) + return "Expected " + expected[0] + among; + + return "Expected " + + string.Join(", ", expected, 0, expected.Length - 1) + + " or " + expected[expected.Length - 1] + among; + } + } + + /// + /// Where the match began, or how far the input could be followed before it + /// failed. An offset into the whole input, so a long: an input may be a + /// file larger than an int can index (docs/syntax.md §6.3). + /// + public long Position { get; } + + /// + /// How much was matched, in input items, and zero when nothing was. An extent + /// into a buffer rather than an offset into the input, so an int. + /// + public int Length { get; } + + internal static Match Success(T value, long position, int length) + { + return new Match(Outcome.Success, value, position, length, null, null, null); + } + + internal static Match Failed( + Outcome outcome, string otherwise, long position, string[]? expected, + string[][]? tied) + { + return new Match(outcome, default!, position, 0, expected, tied, otherwise); + } + + internal Match Refusal(long position, string otherwise) + { + return Match.Failed(Outcome, _otherwise ?? otherwise, position, _expected, _tied); + } + } + + struct Failure + { + public int Position; + + public int OutOfInput; + + public string[]? Expected; + + public global::System.Collections.Generic.List? ExpectedMore; + + public int Looking; + + public bool Quiet; + + public bool Unasked; + + public int Doors; + } + + [global::System.ThreadStatic] + private static global::System.Collections.Generic.List? _spareTies; + + private static global::System.Collections.Generic.List Ties_DotGram() + { + var ties = _spareTies; + + if (ties == null) + return new global::System.Collections.Generic.List(); + + _spareTies = null; + + return ties; + } + + private const int TieCap_DotGram = 16384; + + private static readonly string[] Truncated_DotGram = new string[] { "\u0001" }; + + private static void Tie_DotGram(ref Failure failure, string[] expected) + { + var more = failure.ExpectedMore; + + if (more == null) + failure.ExpectedMore = more = Ties_DotGram(); + + if (more.Count < TieCap_DotGram) + more.Add(expected); + else if (more.Count == TieCap_DotGram) + more.Add(Truncated_DotGram); + } + + private static string[][]? Handed_DotGram(global::System.Collections.Generic.List? ties) + { + if (ties == null) + return null; + + var tied = ties.Count == 0 ? null : ties.ToArray(); + + ties.Clear(); + _spareTies = ties; + + return tied; + } + + sealed class Ways_DotGram + { + internal int[] Items = new int[32]; + + internal int Count; + + internal int Cursor; + + internal int[] Log = new int[64]; + + internal int LogCount; + + internal int Records; + + internal int Last = -1; + + internal int Built; + + internal int AllBuilt; + + internal int AllBuiltAt; + + + + + #if DOTGRAM_COUNTS + + // Initialised, not merely declared: a grammar whose walk never reaches one of these — no + // marks, or nothing that materialises at all — leaves it unassigned, and CS0649 is an ERROR + // where a consumer treats warnings as errors (DotGram.Compatibility does, on purpose). + internal static long CountWalks = 0; + + internal static long CountListed = 0; + + internal static long CountMarkSteps = 0; + + #endif + internal int[] Refs = new int[48]; + + internal int RefsCount; + + internal int Opened; + int _number; + + [global::System.ThreadStatic] + static Ways_DotGram? _spare; + + [global::System.ThreadStatic] + static Ways_DotGram?[]? _deeper; + + [global::System.ThreadStatic] + static int _deeperCount; + + [global::System.ThreadStatic] + static Ways_DotGram? _large; + + [global::System.ThreadStatic] + static int _largeIdle; + + [global::System.ThreadStatic] + static global::System.WeakReference? _largeLetGo; + + [global::System.ThreadStatic] + static int _spareIdle; + + [global::System.ThreadStatic] + static global::System.WeakReference? _spareLetGo; + + const int LargeIdle = 8; + + const int SpareIdle = 8; + + internal static Ways_DotGram Rent() + { + var spare = _spare; + + if (spare != null) + _spare = null; + else if (_deeperCount > 0) + { + spare = _deeper![--_deeperCount]!; + _deeper![_deeperCount] = null; + } + else if (_large != null) + { + spare = _large; + _large = null; + } + else if (_largeLetGo != null && _largeLetGo.TryGetTarget(out var letGo)) + { + spare = letGo; + _largeLetGo.SetTarget(null!); + } + else if (_spareLetGo != null && _spareLetGo.TryGetTarget(out var letGoSpare)) + { + spare = letGoSpare; + _spareLetGo.SetTarget(null!); + } + else + return new Ways_DotGram(); + spare.Count = 0; + spare.Cursor = 0; + spare.LogCount = 0; + spare.Records = 0; + spare.RefsCount = 0; + spare.Last = -1; + spare.Built = 0; + spare.AllBuilt = 0; + spare.AllBuiltAt = 0; + + return spare; + } + + internal static void Return(Ways_DotGram ways) + { + // Bound retained capacity, including an earlier parse's high-water size. Past it + // the tape is not thrown away — that was a cliff rather than a bound: one entry + // over and the next parse of a document that size grew everything again from + // nothing, which cost twenty times the memory of a document a third smaller. + // It goes to a slot of its own instead, held while the work keeps wanting it + // (Return, LargeIdle) and let go of by the collector afterwards. Handing it to + // ArrayPool.Shared instead was considered and is not the same thing: that + // pool's largest kept array is 2^20 elements, the very number this bound is + // written in, so it would decline exactly these arrays and "pool it" would mean + // "drop it" in more words. + if ((long)ways.Items.Length + ways.Log.Length + ways.Refs.Length > 1048576) + { + if (_large != null && !ReferenceEquals(_large, ways)) + (_largeLetGo ??= new global::System.WeakReference(_large)).SetTarget(_large); + + // The same question the ordinary slot asks below: is the room far larger than the + // use. The bound decides which slot holds the tape, not whether to keep it. + if (!((long)ways.Items.Length + ways.Log.Length + ways.Refs.Length + > 4L * (ways.Count * 2L + ways.LogCount + ways.RefsCount))) + _largeIdle = 0; + else if (++_largeIdle >= LargeIdle) + { + (_largeLetGo ??= new global::System.WeakReference(ways)).SetTarget(ways); + _large = null; + _largeIdle = 0; + + return; + } + + _large = ways; + + return; + } + + // The ordinary slot lets go by the rule the parked one uses, counted where a parse + // ENDS and against what it used. Room and use are the two sums already written above: + // every array here is indexed by the same thing, so the bound's capacities and the + // release's counts are the same quantity twice. Four times and not twice because a + // table grows to at least double: one doubling is the slack a steady workload leaves, + // and two is a workload that has shrunk. + if (!((long)ways.Items.Length + ways.Log.Length + ways.Refs.Length + > 4L * (ways.Count * 2L + ways.LogCount + ways.RefsCount))) + _spareIdle = 0; + else if (++_spareIdle >= SpareIdle) + { + (_spareLetGo ??= new global::System.WeakReference(ways)).SetTarget(ways); + _spareIdle = 0; + + return; + } + + if (_spare == null) + _spare = ways; + else if (_deeperCount < 3) + (_deeper ??= new Ways_DotGram?[3])[_deeperCount++] = ways; + } + + internal int Open(int last) => Open(0, last); + + internal int Open(int at, int last) + { + if (Count * 2 + 2 > Items.Length) + global::System.Array.Resize(ref Items, Items.Length * 2); + + Items[Count * 2] = at; + Items[Count * 2 + 1] = last; + Count++; + Cursor = Count; + + return Count - 1; + } + + internal bool Retry(int segment) + { + for (var way = Cursor - 1; way >= segment; way--) + { + if (Items[way * 2] < Items[way * 2 + 1]) + { + Items[way * 2]++; + Count = way + 1; + Cursor = segment; + + return true; + } + } + + return false; + } + + internal void Next(int way, int value) + { + Items[way * 2] = value; + Count = way + 1; + Cursor = way + 1; + } + + internal void Next(int way, int value, int last) + { + Items[way * 2] = value; + Items[way * 2 + 1] = last; + Count = way + 1; + Cursor = way + 1; + } + + internal void Seal(int segment) + { + for (var way = segment; way < Cursor; way++) + Items[way * 2 + 1] = Items[way * 2]; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + internal void Begin(int arm) + { + if (LogCount + 2 > Log.Length) + global::System.Array.Resize(ref Log, Log.Length * 2 + 2); + + Opened = LogCount; + _number = Records++; + Log[LogCount++] = 0; + Log[LogCount++] = arm; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + internal void Begin(int arm, int start, int end) + { + if (LogCount + 4 > Log.Length) + global::System.Array.Resize(ref Log, Log.Length * 2 + 4); + + Opened = LogCount; + _number = Records++; + Log[LogCount++] = 0; + Log[LogCount++] = arm; + Log[LogCount++] = start; + Log[LogCount++] = end; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + internal void Put(int value) + { + if (LogCount + 1 > Log.Length) + global::System.Array.Resize(ref Log, Log.Length * 2 + 1); + + Log[LogCount++] = value; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + internal void Put(int a, int b) + { + if (LogCount + 2 > Log.Length) + global::System.Array.Resize(ref Log, Log.Length * 2 + 2); + + Log[LogCount++] = a; + Log[LogCount++] = b; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + internal void End(int refs) + { + Log[Opened] = LogCount - Opened; + Last = _number; + RefsCount = refs; + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + internal void EndAt(int refs) + { + Log[Opened] = LogCount - Opened; + Last = Opened; + RefsCount = refs; + } + + internal void Mark(int kind, int site, int at) + { + if (LogCount + 5 > Log.Length) + global::System.Array.Resize(ref Log, Log.Length * 2 + 5); + + Records++; + + Log[LogCount++] = 5; + Log[LogCount++] = kind; + Log[LogCount++] = site; + Log[LogCount++] = at; + Log[LogCount++] = at; + } + + internal void Push(int slot, int a, int b) + { + if (RefsCount + 3 > Refs.Length) + global::System.Array.Resize(ref Refs, Refs.Length * 2 + 3); + + Refs[RefsCount++] = slot; + Refs[RefsCount++] = a; + Refs[RefsCount++] = b; + } + + internal void Collect(int from, long slots, bool pairs) + { + var count = 0; + + for (var at = from; at < RefsCount; at += 3) + if ((slots & (1L << Refs[at])) != 0) + count++; + + Put(count); + + for (var at = from; at < RefsCount; at += 3) + if ((slots & (1L << Refs[at])) != 0) + { + if (pairs) + Put(Refs[at + 1], Refs[at + 2]); + else + Put(Refs[at + 1]); + } + } + } + + static void Refuse_DotGram(ref Failure failure, int at, string[]? expected) + { + if (failure.Looking > 0) + return; + + if (at > failure.Position) + { + failure.Position = at; + failure.Expected = expected; + failure.ExpectedMore?.Clear(); + } + else if (at == failure.Position && expected != null && !ReferenceEquals(expected, failure.Expected)) + { + // The same set said twice is one thing wanted, not two. A rule refused at the + // furthest position by several of its alternatives says the same set from + // each, and a message listing it once is the message; a list holding it + // several times is a list that grew on a parse that went on to succeed. + var more = failure.ExpectedMore; + + if (more != null && more.Count > 0 && ReferenceEquals(more[more.Count - 1], expected)) + return; + + Tie_DotGram(ref failure, expected); + } + } + + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + static void Refused_DotGram(ref Failure failure, int at, string[]? expected) + { + if (!failure.Quiet) + Refuse_DotGram(ref failure, at, expected); + else if (failure.Looking == 0 && at > failure.Position) + failure.Position = at; + } + + static void Refuse_DotGram_Over(ref Failure failure, int at, string[] expected, string[] covered, int stood) + { + if (failure.Looking > 0) + return; + + if (at == failure.Position && !Spoke_DotGram(failure.Expected) && !Spoke_DotGram(failure.ExpectedMore)) + { + if (stood < 0) + { + failure.Expected = expected; + failure.ExpectedMore?.Clear(); + + return; + } + + var more = failure.ExpectedMore; + + if (more != null && more.Count > stood) + more.RemoveRange(stood, more.Count - stood); + } + + if (at == failure.Position) + { + if (ReferenceEquals(failure.Expected, covered)) + failure.Expected = expected; + + failure.ExpectedMore?.Remove(covered); + } + + Refuse_DotGram(ref failure, at, expected); + } + + static bool Spoke_DotGram(string[]? expected) + { + if (expected != null) + foreach (var one in expected) + if (one.Length > 0 && one[0] == '\u0000') + return true; + + return false; + } + + static bool Spoke_DotGram(global::System.Collections.Generic.List? tied) + { + if (tied != null) + foreach (var one in tied) + if (Spoke_DotGram(one)) + return true; + + return false; + } + + sealed class ImmediateValues_DotGram + { + internal static bool IsDefault(T value) => global::System.Collections.Generic.EqualityComparer.Default.Equals(value, default!); + } + + + // The sets a refusal names, by number: built the first time a refusal asks for one, never in the + // type's initializer, and then the same array for as long as the process lives, because refusals + // tell sets apart by reference. + static string[]?[]? ExpectedBuilt_DotGram; + static string[]? ExpectedItems_DotGram; + static int[]? ExpectedStarts_DotGram; + + static string[] ExpectedSet_DotGram(int id) + { + var built = ExpectedBuilt_DotGram; + + if (built != null) + { + var set = built[id]; + + if (set != null) + return set; + } + + return ExpectedDecoded_DotGram(id); + } + + static string[] ExpectedDecoded_DotGram(int id) + { + var data = "ACEGIKMOBABBBCBDBEBFBGBH"u8; + var built = ExpectedBuilt_DotGram ?? global::System.Threading.Interlocked.CompareExchange(ref ExpectedBuilt_DotGram, new string[]?[8], null) ?? ExpectedBuilt_DotGram!; + var items = ExpectedItems_DotGram ?? global::System.Threading.Interlocked.CompareExchange(ref ExpectedItems_DotGram, new string[] + { + "['&' | '-' | '|']", + "\"pattern:\"", + "\"contains:\"", + "\"regex:\"", + "['p' | 'c' | 'r']", + "[^ '\\n' | '\\r']", + "end of input", + "[^ ]", + }, null) ?? ExpectedItems_DotGram!; + var starts = ExpectedStarts_DotGram; + var at = 0; + int value; + + if (starts == null) + { + starts = new int[8]; + + for (var i = 0; i < starts.Length; i++) + { + value = 0; + while (data[at] >= 0x60) + value = value << 5 | data[at++] & 0x1F; + value = (value << 5 | data[at++] & 0x1F) - 1; + starts[i] = value; + } + + for (var i = 0; i < starts.Length; i++) + starts[i] += at; + + starts = global::System.Threading.Interlocked.CompareExchange(ref ExpectedStarts_DotGram, starts, null) ?? starts; + } + + at = starts[id]; + value = 0; + while (data[at] >= 0x60) + value = value << 5 | data[at++] & 0x1F; + value = (value << 5 | data[at++] & 0x1F) - 1; + + var set = new string[value]; + + for (var i = 0; i < set.Length; i++) + { + value = 0; + while (data[at] >= 0x60) + value = value << 5 | data[at++] & 0x1F; + value = (value << 5 | data[at++] & 0x1F) - 1; + set[i] = items[value]; + } + + return global::System.Threading.Interlocked.CompareExchange(ref built[id], set, null) ?? set; + } + } +} diff --git a/Source/TargetFilter/Generated/DotGram.Attributes.g.cs b/Source/TargetFilter/Generated/DotGram.Attributes.g.cs new file mode 100644 index 0000000..7ccb358 --- /dev/null +++ b/Source/TargetFilter/Generated/DotGram.Attributes.g.cs @@ -0,0 +1,489 @@ +// + +namespace DotGram +{ + /// + /// One reading of the grammar a class carries, beside the one [Gram] asks + /// for. + /// + /// + /// The same grammar compiled again under different options — another carrier, + /// another division, locations where the first has none. Each reading needs a + /// scope of its own, so each names a nested class with , and + /// what it does not say it takes from [Gram]. + /// + [global::System.AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = true, Inherited = false)] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + [global::Microsoft.CodeAnalysis.Embedded] + internal class GramOptionsAttribute : global::System.Attribute + { + /// + /// The nested class this compilation goes into, where the host has more + /// than one. One identifier; the host class itself where nothing is said. + /// + /// + /// Two compilations cannot share a scope — a file's support is written + /// once and named for what it is — so the second gets a class, and its + /// parse methods are reached through it: Sql.Immediate.TryParseR. + /// What the host declares is still in reach from inside, a nested class + /// reading the static members around it by their simple names. + /// + public string Suffix { get; set; } + + /// + /// How large the parts of a divided recognizer are aimed to be, in the + /// generator's estimate of basic blocks. Zero takes the measured default. + /// + /// + /// A recognizer too large for one method is written in several, and how + /// large each should be was measured flat anywhere between sixty and two + /// hundred and fifty — flat, but on grammars that are not yours. Set this + /// where yours turns out to want something else. + /// + /// It is a wish rather than a setting: every value generates a parser. + /// Below one asks for the finest division there is, past the size of the + /// recognizer asks for one part, and nothing written here can fail a + /// build. + /// + public int PartSize { get; set; } + + /// + /// Read the input as tokens rather than as characters. + /// + /// + /// The grammar is cut in two: a lexical machine over characters that + /// answers with token kinds, and the same syntactic machine over those + /// (docs/design/lexical-adt-design.md). Nothing about the grammar changes and + /// nothing about the published methods changes — they take a string and + /// answer as they did. + /// + /// Off by default and a request rather than a setting: a grammar that + /// cannot be cut is compiled over characters and told why. What cannot + /// be cut is a grammar with no trivia at all — a URL is characters and + /// there is nothing to gain — one whose terminals are not regular + /// languages, one that publishes `find`, and one whose `trivia` is not + /// written in braces, since the seam is skipped by the scanner those + /// braces ask for. + /// + /// Worth it where the input is long or is refused: measured against the + /// character machine on standard SQL, an accepted condition runs 1.05 to + /// 2.45 times faster and a refused one 1.35 to 3.85, the gain growing + /// with the input because the syntactic machine reads a fifth as many + /// items and keeps a fifth as many ways back. + /// + public bool Lexical { get; set; } + + /// + /// How the reader carries what it has read until the constructions run. + /// + /// + /// GramCarrier.Auto unless set, which is Immediate wherever that + /// carrier can carry the grammar; where the tape would be safer the build says so + /// (GRAM5016, GRAM5012). What each carrier gives up is written on it. A part of the + /// grammar the carrier cannot carry is compiled on the tape. + /// + public GramCarrier Carrier { get; set; } + + /// + /// Says a construction may throw on a reading the parse gives up: carried + /// immediately, what one throws is then thrown only where the tape would have + /// built the value, and a refused parse throws nothing. Costs every construction + /// a little; the tape ignores it. + /// + public bool ConstructionsMayThrow { get; set; } + + /// Add buffered pull-input publications beside existing forms. + public bool BufferedInput { get; set; } + + /// Add buffered byte-input publications; no text decoding is performed. + public bool BufferedBytes { get; set; } + + /// Pass character captures as ReadOnlySpan<char> rather than string. + public bool SpanCaptures { get; set; } + + /// + /// The most input a buffered parse may hold at once, in characters or bytes, where a + /// call does not say. + /// + /// + /// A streaming overload's own maxRetained overrides it for that call. Past the + /// limit the parse throws IOException naming it. The default is no limit. + /// + public int MaxRetained { get; set; } = int.MaxValue; + + /// + /// The initial capacity of a buffered parse's buffer, where a call does not say. + /// + /// A streaming overload's own bufferSize overrides it for that call. + public int BufferSize { get; set; } = 4096; + + /// + /// How many stacks one parse may take beyond the one it began on. + /// + /// + /// A grammar that recurses on input the author did not write can be handed a + /// thousand brackets. Where the stack it is reading on runs low the reading + /// carries on over a stack of its own, and a reading deep enough to run that + /// one low takes another — by default for as long as there is memory to take + /// one with. + /// + /// Set it to say how many is enough. Past that many the parse fails with + /// `InsufficientExecutionStackException`, which is what it always did. Zero, + /// the default, is no limit; one is a single extra stack; a reading that never + /// goes deep takes none whatever this says. + /// + public int Stacks { get; set; } + + /// + /// An interface whose implementors are told where they were written. + /// + /// + /// Nothing written here changes what is read; it changes what a value knows + /// about itself. Name an interface with a settable property called + /// Span, and every rule whose value implements it is handed the range + /// of input it was built from — the rule's own text, without the trivia + /// around it, so that a comment falls between two of them rather than inside + /// one. + /// + /// What that buys is everything a parse cannot answer on its own: which + /// characters a diagnostic is about, which node a comment belongs to, and + /// what a formatter or a rewriter may leave alone. A grammar that says + /// nothing here pays nothing — a recognizer wants no positions, and most + /// grammars are recognizers. + /// + /// The property is written once, by the reader, on a value it has just made + /// and nothing has yet seen. + /// + public global::System.Type LocationType { get; set; } + + /// + /// Whether this reading is the class's own parser called with locations on, rather + /// than a second compilation of the grammar. + /// + /// + /// Written on a [GramOptions] that names a and a + /// : the grammar is compiled once, its constructions are told + /// where they were written only when a call asks, and the nested class named by the + /// suffix holds the same published methods, each of them asking. A call that does + /// not ask pays a test per construction and nothing else. + /// + /// The interface then offers Locate(int at, int length, int gapStart), where + /// the gap start is where the text between the value and the token before it + /// begins: the end of that token, or where the reading began. + /// + public bool PerCall { get; set; } + + /// + /// Whether the grammar travels with the assembly, so that another project can + /// include it. + /// + /// + /// A .gram file is read at compile time and is not part of what ships. + /// This writes the text onto the generated class, where + /// [GramInclude(typeof(X))] in another project finds it — without which + /// including a grammar across a reference cannot work at all. + /// + /// Unset, it follows what the class already says: a publicly visible host is + /// offered outward and carries its grammar, and one that is not cannot be named + /// from outside anyway. Say it either way where that guess is wrong. It costs + /// the size of the grammar — measured at 4.7% of an assembly holding five of + /// them, whose bulk is the parsers they generated. + /// + public bool Portable { get; set; } = true; + + /// + /// Whether this reading is a trace build: its parser reports the rules it enters, + /// what it refuses and why, to a sink set with Tracing(sink). + /// + /// + /// The sink is GramTrace, nested in the class beside the parser together + /// with three ready-made ones: GramWhy, which says why an input was + /// refused and by which rules; GramTraceLog, an indented log of every rule + /// entered; and GramProfile, how often each rule was entered and how long + /// it took. Off, nothing of it is written. The build property + /// DotGramTrace asks the same of every grammar in a project, and a + /// [GramOptions(Suffix = "Traced", Trace = true)] puts a traced reading + /// beside an untouched one (docs/syntax.md, §6.9). + /// + public bool Trace { get; set; } + } + + /// How a generated reader carries what it has read. + [global::Microsoft.CodeAnalysis.Embedded] + internal enum GramCarrier + { + /// + /// The default: Immediate wherever it can carry the grammar, the tape + /// where it cannot. A construction runs as its alternative is read, also for a + /// reading the parse gives up; Tape holds every one back until a parse has + /// accepted. Where that matters the build says so (GRAM5016, GRAM5012). + /// + Auto, + + /// Records on a tape, built into values once the parse is accepted. + Tape, + + /// + /// No deferral: a construction runs the moment its alternative has been read, + /// and one abandoned afterwards has already run. Once per derivation tried + /// rather than once per derivation accepted — invisible to a pure allocation, + /// visible to a counter. Named, it says the author has checked, and silences + /// what a grammar left to choose is told. + /// + Immediate, + } + + /// + /// What a rule or a capture means, as a role rather than a colour: an editor's + /// theme decides how an identifier looks, and this says only that something is + /// one. + /// + [global::Microsoft.CodeAnalysis.Embedded] + internal enum GramClassification + { + Keyword, + Identifier, + Type, + Variable, + Function, + Method, + Property, + Number, + String, + Comment, + Operator, + Punctuation, + Namespace, + Parameter, + Label, + } + + /// + /// The grammar a class is compiled from, and the first reading of it. + /// + /// + /// One per class: this says which grammar, which is a thing a class has + /// one of. How to read it is what it shares with , + /// and a class wanting the same grammar read a second way writes one of those. + /// + [global::System.AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + [global::Microsoft.CodeAnalysis.Embedded] + internal sealed class GramAttribute : GramOptionsAttribute + { + /// The grammar is the .gram file named after the class. + public GramAttribute() { } + + /// + /// A path to a .gram file, or the grammar text itself. A single-line value + /// ending in ".gram" is a path; anything else is grammar text. + /// + public GramAttribute(string source) => Source = source; + + public string Source { get; } + + /// + /// The name another grammar includes this one under, where nothing else was + /// said — the default, and no more: what a grammar is called inside another is + /// the includer's business, and [GramInclude(…, As = "…")] is where it + /// is said. + /// + public string IncludedAs { get; set; } + } + + /// + /// The grammar a generated class was compiled from, written onto the class itself. + /// + /// + /// A .gram file is read at compile time and does not travel: what ships is + /// the assembly. So the text is put here, on the class an including grammar names + /// — [GramInclude(typeof(X))] — and a grammar in a referenced assembly is + /// then found the same way one beside you is. The file wins where both are in + /// reach, so that a diagnostic points at something somebody can edit. + /// + [global::System.AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + [global::Microsoft.CodeAnalysis.Embedded] + internal sealed class GramSourceAttribute : global::System.Attribute + { + public GramSourceAttribute(string text) => Text = text; + + public string Text { get; } + } + + /// + /// Another grammar this one is written on top of. + /// + /// + /// + /// The named class's rules are declared beside this grammar's own, under a + /// namespace called after the class unless says otherwise, so + /// that using Sql92 and Sql92.ValueExpression reach them (§5.1). + /// Write it as many times as there are grammars to build on: a dialect on a + /// standard, a standard on a library of lexemes, both at once. + /// + /// + /// The C# comes with it. Whatever static members the named class holds are + /// brought into scope of the generated code, so a rule this grammar includes goes + /// on calling the helpers its author wrote. Two grammars offering the same name is + /// then an ordinary C# ambiguity and is refused as one; a member you + /// declare under a name a grammar you include calls is not refused and is used + /// instead of theirs, which is the one collision nothing here can see and the + /// reason to read what you include. + /// + /// + /// A grammar may also be inherited, by deriving from the class that holds it. + /// That is the older spelling and it says less: a class has one base and many + /// attributes, and a base class carries meaning of its own that a grammar has no + /// use for. + /// + /// + [global::System.AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = true, Inherited = false)] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + [global::Microsoft.CodeAnalysis.Embedded] + internal sealed class GramIncludeAttribute : global::System.Attribute + { + /// The class whose grammar is included. + public GramIncludeAttribute(global::System.Type grammar) => Grammar = grammar; + + public global::System.Type Grammar { get; } + + /// + /// The name this grammar's rules are reached under, where the class's own + /// name is not what you want to write. + /// + /// + /// The includer's to choose, which is the right way round: what a grammar is + /// called inside yours is your business and not its author's. + /// + public string As { get; set; } + } + + /// Names the language a grammar describes, for tooling to discover. + [global::System.AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + [global::Microsoft.CodeAnalysis.Embedded] + internal sealed class GramLanguageAttribute : global::System.Attribute + { + /// + /// A stable identifier for the language, unique to whoever owns it — a reverse + /// domain name is the usual shape. + /// + public GramLanguageAttribute(string id) => Id = id; + + public string Id { get; } + + /// File extensions this language claims, with the dot. + public string[] Extensions { get; set; } + } + + /// + /// Gives a rule or one of its captures a semantic role. + /// + /// + /// A rule's own classification is the default for every use of it; a capture's + /// overrides that default where the two disagree. `Declaration.type` and + /// `Declaration.name` may both be `Identifier` rules and mean different things. + /// + [global::System.AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = true, Inherited = false)] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + [global::Microsoft.CodeAnalysis.Embedded] + internal sealed class GramClassifyAttribute : global::System.Attribute + { + /// + /// A rule name — Keyword — or a capture of one — Declaration.type. + /// + /// What it means, for an editor to present as it likes. + public GramClassifyAttribute(string target, GramClassification role) + { + Target = target; + Role = role; + } + + public string Target { get; } + public GramClassification Role { get; } + } + + /// Declares a non-executing editor decision for a grammar guard. + [global::System.AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = true, Inherited = false)] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + [global::Microsoft.CodeAnalysis.Embedded] + internal sealed class GramToolingGuardAttribute : global::System.Attribute + { + public GramToolingGuardAttribute(string expression, bool accepted) + { + Expression = expression; + Accepted = accepted; + } + + public string Expression { get; } + public bool Accepted { get; } + } + + /// Maps an external recognizer to an equivalent grammar rule for editors. + [global::System.AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = true, Inherited = false)] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + [global::Microsoft.CodeAnalysis.Embedded] + internal sealed class GramToolingExternalAttribute : global::System.Attribute + { + public GramToolingExternalAttribute(string method, string rule) + { + Method = method; + Rule = rule; + } + + public string Method { get; } + public string Rule { get; } + } + + /// Locates the versioned language descriptor carried by a generated parser. + [global::System.AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + [global::Microsoft.CodeAnalysis.Embedded] + internal sealed class GramLanguageDescriptorAttribute : global::System.Attribute + { + public GramLanguageDescriptorAttribute( + int formatVersion, + string languageId, + string grammarHash, + string sourcePayload, + string entriesPayload) + { + FormatVersion = formatVersion; + LanguageId = languageId; + GrammarHash = grammarHash; + SourcePayload = sourcePayload; + EntriesPayload = entriesPayload; + } + + public GramLanguageDescriptorAttribute( + int formatVersion, + string languageId, + string grammarHash, + string sourcePayload, + string entriesPayload, + string classificationsPayload) + : this(formatVersion, languageId, grammarHash, sourcePayload, entriesPayload) => + ClassificationsPayload = classificationsPayload; + + public GramLanguageDescriptorAttribute( + int formatVersion, + string languageId, + string grammarHash, + string sourcePayload, + string entriesPayload, + string classificationsPayload, + string recognitionContractPayload) + : this(formatVersion, languageId, grammarHash, sourcePayload, entriesPayload, classificationsPayload) => + RecognitionContractPayload = recognitionContractPayload; + + public int FormatVersion { get; } + public string LanguageId { get; } + public string GrammarHash { get; } + public string SourcePayload { get; } + public string EntriesPayload { get; } + public string ClassificationsPayload { get; } + public string RecognitionContractPayload { get; } + } + +} \ No newline at end of file diff --git a/Source/TargetFilter/Generated/Microsoft.CodeAnalysis.EmbeddedAttribute.cs b/Source/TargetFilter/Generated/Microsoft.CodeAnalysis.EmbeddedAttribute.cs new file mode 100644 index 0000000..6ff2684 --- /dev/null +++ b/Source/TargetFilter/Generated/Microsoft.CodeAnalysis.EmbeddedAttribute.cs @@ -0,0 +1,7 @@ +// +namespace Microsoft.CodeAnalysis +{ + internal sealed partial class EmbeddedAttribute : global::System.Attribute + { + } +} \ No newline at end of file diff --git a/Source/TargetFilter/TargetFilter.gram b/Source/TargetFilter/TargetFilter.gram new file mode 100644 index 0000000..e17ca7b --- /dev/null +++ b/Source/TargetFilter/TargetFilter.gram @@ -0,0 +1,17 @@ +// The grammar of one line of a target filter. The generated parser is the internal TargetFilterParser; +// regenerate it with Source/TargetFilter/regenerate.sh after any change to this file. +// +// A line is an optional operator, an optional matcher prefix and the rest of the line. + +@using System; + +Operator : @string = t: ('-' | '&' | '|') => @(t) + +MatcherPrefix : @string = t: ("pattern:" | "contains:" | "regex:") => @(t) + +Rest : @string = t: [^ '\r' | '\n']* => @(t) + +Line : @TargetFilterLine = op: Operator? & matcher: MatcherPrefix? & rest: Rest & eof + => @(new TargetFilterLine(op, matcher, rest)) + +parse Line diff --git a/Source/TargetFilter/TargetFilterLine.cs b/Source/TargetFilter/TargetFilterLine.cs new file mode 100644 index 0000000..8d9c07d --- /dev/null +++ b/Source/TargetFilter/TargetFilterLine.cs @@ -0,0 +1,22 @@ +namespace AspectGenerator +{ + /// One line of a target filter as the grammar reads it. + internal sealed class TargetFilterLine + { + public TargetFilterLine(string? @operator, string? matcherPrefix, string text) + { + Operator = @operator; + MatcherPrefix = matcherPrefix; + Text = text; + } + + /// The leading -, & or |, or . + public string? Operator { get; } + + /// The matcher prefix with its colon (pattern:, contains:, regex:), or . + public string? MatcherPrefix { get; } + + /// The rest of the line. + public string Text { get; } + } +} diff --git a/Source/TargetFilter/TargetFilterParser.cs b/Source/TargetFilter/TargetFilterParser.cs new file mode 100644 index 0000000..2aeab01 --- /dev/null +++ b/Source/TargetFilter/TargetFilterParser.cs @@ -0,0 +1,14 @@ +using DotGram; + +namespace AspectGenerator +{ + /// + /// The parser of a target filter line. Its members are generated from TargetFilter.gram and committed under + /// Generated; the build does not run the generator. Nothing in the generator uses it yet: it is compiled and + /// exercised by the unit tests, and filters are still parsed by the hand-written parser. + /// + [Gram("TargetFilter.gram")] + internal partial class TargetFilterParser + { + } +} diff --git a/Source/TargetFilter/dotgram.pin b/Source/TargetFilter/dotgram.pin new file mode 100644 index 0000000..1e6a94a --- /dev/null +++ b/Source/TargetFilter/dotgram.pin @@ -0,0 +1,9 @@ +# What generates Source/TargetFilter/Generated: read by regenerate.sh, by the filter-parser CI job and by the +# setup-dotnet step of that job. Move the commit only to a commit of the DotGram repository whose CI is green, in a +# commit of its own together with the regenerated folder. +# +# commit the DotGram commit whose DotGram.Cli generates the parser (the tool's version string does not tell commits apart) +# sdk the exact .NET SDK the generation runs with: the generated text includes the compiler's own text of the +# embedded attribute, so another SDK may write different bytes +commit=2adfb25704001eeded51e1cebb9570d77421e3a9 +sdk=10.0.401 diff --git a/Source/TargetFilter/regenerate.sh b/Source/TargetFilter/regenerate.sh new file mode 100755 index 0000000..51e2c5a --- /dev/null +++ b/Source/TargetFilter/regenerate.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +# Regenerates Source/TargetFilter/Generated from TargetFilter.gram with the DotGram commit and the .NET SDK in dotgram.pin. +# +# Source/TargetFilter/regenerate.sh +# +# It builds DotGram.Cli from the pinned commit into a scratch folder and runs project-mode `generate` over +# Source/AspectGenerator.csproj. It refuses to run with any other SDK than the pinned one: select that SDK first (a +# global.json for it, or an environment where it is the default). Running it twice changes nothing. +# +# Environment: +# DOTGRAM_REPO where to fetch DotGram from (default https://github.com/dotgram/dotgram.git; a local clone works) +# DOTGRAM_SCRATCH the scratch folder (default $TMPDIR/aspectgenerator-dotgram-); kept between runs +# +# Works in Git Bash on Windows as well. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +root="$(cd "$here/../.." && pwd)" +pin="$here/dotgram.pin" + +pinned() { + local value + value="$(sed -n "s/^$1=//p" "$pin" | tr -d '\r' | head -n 1)" + [ -n "$value" ] || { echo "regenerate.sh: $pin has no '$1='" >&2; exit 2; } + printf '%s' "$value" +} + +native() { + # A path as the dotnet host reads it: Windows form under Git Bash, unchanged elsewhere. + if command -v cygpath > /dev/null 2>&1; then cygpath -m "$1"; else printf '%s' "$1"; fi +} + +commit="$(pinned commit)" +sdk="$(pinned sdk)" + +cd "$root" + +actual="$(dotnet --version)" +if [ "$actual" != "$sdk" ]; then + echo "regenerate.sh: .NET SDK $actual is selected in $root; the generated files are produced with exactly $sdk (Source/TargetFilter/dotgram.pin)." >&2 + echo " Install $sdk and select it, for example with a global.json:" >&2 + echo " { \"sdk\": { \"version\": \"$sdk\", \"rollForward\": \"disable\" } }" >&2 + exit 1 +fi + +export MSBUILDDISABLENODEREUSE=1 +export DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1 + +repo="${DOTGRAM_REPO:-https://github.com/dotgram/dotgram.git}" +scratch="${DOTGRAM_SCRATCH:-${TMPDIR:-/tmp}/aspectgenerator-dotgram-${commit:0:12}}" +mkdir -p "$scratch" +scratch="$(cd "$scratch" && pwd)" +tree="$scratch/dotgram" + +if [ "$(git -C "$tree" rev-parse HEAD 2> /dev/null || true)" != "$commit" ]; then + rm -rf "$tree" + mkdir -p "$tree" + git -C "$tree" init --quiet + git -C "$tree" fetch --quiet --depth 1 "$repo" "$commit" + git -C "$tree" checkout --quiet --detach FETCH_HEAD + [ "$(git -C "$tree" rev-parse HEAD)" = "$commit" ] || { echo "regenerate.sh: fetched $(git -C "$tree" rev-parse HEAD), not $commit" >&2; exit 1; } +fi + +# The checkout has a global.json of its own that rolls forward to any newer feature band: pin the exact SDK there too. +printf '{ "sdk": { "version": "%s", "rollForward": "disable" } }\n' "$sdk" > "$tree/global.json" +treesdk="$(cd "$tree" && dotnet --version)" +if [ "$treesdk" != "$sdk" ]; then + echo "regenerate.sh: building DotGram.Cli would use .NET SDK $treesdk, not the pinned $sdk." >&2 + exit 1 +fi + +cli="$tree/.build/bin/DotGram.Cli/release/dotnet-dotgram.dll" +stamp="$scratch/cli-$commit-sdk-$sdk.built" +if [ ! -e "$stamp" ] || [ ! -e "$cli" ]; then + rm -f "$stamp" + ( cd "$tree" && dotnet build src/DotGram.Cli/DotGram.Cli.csproj --configuration Release -nodeReuse:false --verbosity quiet ) + [ -e "$cli" ] || { echo "regenerate.sh: DotGram.Cli was not built at $cli" >&2; exit 1; } + : > "$stamp" +fi + +# The tool reads a restored project and never restores. +dotnet restore Source/AspectGenerator.csproj --verbosity quiet + +dotnet "$(native "$cli")" generate Source/AspectGenerator.csproj --output Source/TargetFilter/Generated + +# DotGram deletes only what the manifest lists and keeps every other file: a stray committed file would compile into the +# parser and leave git status clean. The folder must hold exactly the manifest's files and the manifest. +out=Source/TargetFilter/Generated +expected="$( { sed -n 's/.*"name": *"\([^"]*\)".*/\1/p' "$out/.dotgram.json" | tr -d '\r'; echo .dotgram.json; } | LC_ALL=C sort)" +actual="$(cd "$out" && find . -type f | sed 's|^\./||' | LC_ALL=C sort)" +if [ "$expected" != "$actual" ]; then + echo "regenerate.sh: $out does not hold exactly the files of its manifest .dotgram.json." >&2 + echo " only in the folder: $(LC_ALL=C comm -13 <(printf '%s\n' "$expected") <(printf '%s\n' "$actual") | tr '\n' ' ')" >&2 + echo " only in the manifest: $(LC_ALL=C comm -23 <(printf '%s\n' "$expected") <(printf '%s\n' "$actual") | tr '\n' ' ')" >&2 + exit 1 +fi diff --git a/UnitTests/Tests/TargetFilterParserSmokeTests.cs b/UnitTests/Tests/TargetFilterParserSmokeTests.cs new file mode 100644 index 0000000..f787011 --- /dev/null +++ b/UnitTests/Tests/TargetFilterParserSmokeTests.cs @@ -0,0 +1,64 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace AspectGenerator.Tests +{ + /// + /// The generated target filter parser links, loads and reads a handful of lines. The grammar is the only thing it is + /// checked against here; the filter semantics are pinned elsewhere. + /// + [TestClass] + public class TargetFilterParserSmokeTests + { + static void AssertLine(string input, string? @operator, string? matcherPrefix, string text) + { + var match = TargetFilterParser.TryParseLine(input); + + Assert.IsTrue(match.IsSuccess, $"'{input}' was refused: {match.Error}"); + + var line = match.Value; + + Assert.AreEqual(@operator, line.Operator, $"operator of '{input}'"); + Assert.AreEqual(matcherPrefix, line.MatcherPrefix, $"matcher prefix of '{input}'"); + Assert.AreEqual(text, line.Text, $"text of '{input}'"); + } + + [TestMethod] + public void PlainLineIsTheRestTest() + { + AssertLine("Save", null, null, "Save"); + AssertLine("Acme.Core.*", null, null, "Acme.Core.*"); + AssertLine("", null, null, ""); + } + + [TestMethod] + public void OperatorsAreTakenOffTheFrontTest() + { + AssertLine("-Save", "-", null, "Save"); + AssertLine("&Save", "&", null, "Save"); + AssertLine("|Save", "|", null, "Save"); + } + + [TestMethod] + public void MatcherPrefixesAreTakenAfterTheOperatorTest() + { + AssertLine("pattern:Save*", null, "pattern:", "Save*"); + AssertLine("contains:Save", null, "contains:", "Save"); + AssertLine("regex:^Save\\d+$", null, "regex:", "^Save\\d+$"); + AssertLine("-contains:Save", "-", "contains:", "Save"); + AssertLine("®ex:Save", "&", "regex:", "Save"); + } + + [TestMethod] + public void UnknownPrefixStaysInTheRestTest() + { + AssertLine("other:Save", null, null, "other:Save"); + AssertLine("--Save", "-", null, "-Save"); + } + + [TestMethod] + public void LineBreakIsRefusedTest() + { + Assert.IsFalse(TargetFilterParser.TryParseLine("Save\nPing").IsSuccess); + } + } +}