From 99353f98fe219d07be0c0b9862392d04d1863c18 Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Tue, 17 Nov 2026 12:37:04 -0700 Subject: [PATCH 1/2] Core, CLI and TUI: response search, JSONPath filtering and body highlighting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JSONPath (RFC 9535) filters JSON responses: a query selects values by name, index, slice, wildcard, descendants and filters (comparisons, &&, ||, !, and the functions length, count, match, search and value). It passes the 715 cases of the JSONPath Compliance Test Suite, an opt-in test (TERMREST_JSONPATH_CTS). match and search take I-Regexp (RFC 9485), turned into .NET's linear-time engine so that . and classes match a code point (an emoji whole; \p{Lu} matches 𝒜). Numbers compare exactly (1 == 1.0; 9007199254740993 is not 9007199254740992), strings by code point. In the UI, the Body tab's Filter shows a JSONPath row: the body shows the values the query selects as a JSON array, in each response until the row is closed. A large body is filtered in the background, NDJSON as an array of its lines, and Copy copies the values. termrest send --filter prints them (on one line with --raw, to a file with -o); a query that isn't JSONPath is a usage error, before anything is sent. Find (Ctrl+F from anywhere; text fields no longer take Ctrl+F as Emacs's cursor right) looks in the text of the tab shown, highlights every match and selects them in turn (F3 or Enter; Shift+F3 or Shift+Enter backwards). JSON, XML and HTML bodies are colored: a request's raw body in the language chosen for it, a response's as its Content-Type says, read-only and wrapped text too. When words wrap, a line is colored whole and its colors split over its rows. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/TermRest.Cli/SendCommand.cs | 76 +- src/TermRest.Core/Http/BodyFilter.cs | 140 +++ src/TermRest.Core/Http/BodyFormatter.cs | 8 +- src/TermRest.Core/Json/IRegexp.cs | 629 +++++++++++++ src/TermRest.Core/Json/JsonPath.cs | 43 + src/TermRest.Core/Json/JsonPathEvaluation.cs | 838 ++++++++++++++++++ src/TermRest.Core/Json/JsonPathParser.cs | 669 ++++++++++++++ src/TermRest.Tui/MainWindow.cs | 17 + src/TermRest.Tui/Syntax/JsonLexer.cs | 93 ++ src/TermRest.Tui/Syntax/MarkupLexer.cs | 281 ++++++ src/TermRest.Tui/Syntax/SyntaxLexer.cs | 8 +- src/TermRest.Tui/TuiApp.cs | 8 + src/TermRest.Tui/Views/BodyEditor.cs | 10 +- src/TermRest.Tui/Views/RequestEditor.cs | 3 + src/TermRest.Tui/Views/ResponseView.cs | 434 ++++++++- src/TermRest.Tui/Views/TextArea.cs | 452 +++++++++- tests/TermRest.Cli.Tests/CommandLineTests.cs | 35 + tests/TermRest.Core.Tests/JsonPathTests.cs | 212 +++++ tests/TermRest.Tui.Tests/MainWindowTests.cs | 59 +- tests/TermRest.Tui.Tests/ResponseViewTests.cs | 99 +++ tests/TermRest.Tui.Tests/SyntaxTests.cs | 50 +- tests/TermRest.Tui.Tests/TextAreaTests.cs | 126 +++ 22 files changed, 4209 insertions(+), 81 deletions(-) create mode 100644 src/TermRest.Core/Http/BodyFilter.cs create mode 100644 src/TermRest.Core/Json/IRegexp.cs create mode 100644 src/TermRest.Core/Json/JsonPath.cs create mode 100644 src/TermRest.Core/Json/JsonPathEvaluation.cs create mode 100644 src/TermRest.Core/Json/JsonPathParser.cs create mode 100644 src/TermRest.Tui/Syntax/JsonLexer.cs create mode 100644 src/TermRest.Tui/Syntax/MarkupLexer.cs create mode 100644 tests/TermRest.Core.Tests/JsonPathTests.cs diff --git a/src/TermRest.Cli/SendCommand.cs b/src/TermRest.Cli/SendCommand.cs index 2e3e7da..28aa390 100644 --- a/src/TermRest.Cli/SendCommand.cs +++ b/src/TermRest.Cli/SendCommand.cs @@ -1,5 +1,7 @@ using System.CommandLine; +using System.Text; using TermRest.Core.Http; +using TermRest.Core.Json; using TermRest.Core.Postman; namespace TermRest.Cli; @@ -14,8 +16,9 @@ public static Command Create(Option insecure) var request = new Argument("request") { Description = "Request path such as \"Users/Get user\", or a unique request name" }; var include = new Option("--include", "-i") { Description = "Also print the response status line and headers to stdout" }; var verbose = new Option("--verbose", "-v") { Description = "Print the request, timing and TLS details to stderr" }; - var output = new Option("--output", "-o") { Description = "Write the raw response body to a file" }; - var raw = new Option("--raw") { Description = "Print the body as received (no JSON/XML pretty printing)" }; + var output = new Option("--output", "-o") { Description = "Write the raw response body (with --filter, the values selected) to a file" }; + var raw = new Option("--raw") { Description = "Print the body as received (no JSON/XML pretty printing); with --filter, the values on one line" }; + var filter = new Option("--filter") { Description = "Print only the values a JSONPath query (RFC 9535) selects in a JSON body, as an array: --filter '$.items[?@.price < 10].id'" }; var fail = new Option("--fail", "-f") { Description = "Exit with code 22 when the HTTP status is 400 or higher" }; var curl = new Option("--curl") { Description = "Print the request as a cURL command instead of sending it (scripts do not run)" }; var noHistory = new Option("--no-history") { Description = "Do not record this request in the workspace history" }; @@ -27,12 +30,28 @@ public static Command Create(Option insecure) command.Options.Add(verbose); command.Options.Add(output); command.Options.Add(raw); + command.Options.Add(filter); command.Options.Add(fail); command.Options.Add(curl); command.Options.Add(noHistory); command.SetAction(async (parseResult, cancellationToken) => { + // A query that is not valid JSONPath is reported before anything is sent. + JsonPath? query = null; + if (parseResult.GetValue(filter) is { } text) + { + try + { + query = JsonPath.Parse(text.TrimEnd()); + } + catch (JsonPathException ex) + { + Output.Error($"--filter: {ex.Message}"); + return 2; + } + } + if (options.Open(parseResult, parseResult.GetValue(collection)!, insecure) is not { } opened) { return 2; @@ -110,7 +129,7 @@ public static Command Create(Option insecure) printed = prepared.Warnings.Count; }, cancellationToken); var recorded = options.SaveRecording(parseResult, runner, recorder, cancellationToken.IsCancellationRequested); - var code = await ReportAsync(parseResult, exchange, verbose, include, output, raw, fail, cancellationToken); + var code = await ReportAsync(parseResult, exchange, query, verbose, include, output, raw, fail, cancellationToken); // Those raised while it was sent: a redirect not followed, a header left out, a body cut short … PrintWarnings(exchange.Request, printed); @@ -165,8 +184,8 @@ private static void PrintWarnings(PreparedRequest prepared, int from = 0) } private static async Task ReportAsync( - ParseResult parseResult, HttpExchange exchange, Option verbose, Option include, Option output, Option raw, Option fail, - CancellationToken cancellationToken) + ParseResult parseResult, HttpExchange exchange, JsonPath? query, Option verbose, Option include, Option output, Option raw, + Option fail, CancellationToken cancellationToken) { if (parseResult.GetValue(verbose)) { @@ -191,7 +210,14 @@ private static async Task ReportAsync( Console.Out.WriteLine(); } - if (parseResult.GetValue(output) is { } file) + if (query is not null) + { + if (await WriteFilteredAsync(query, response, parseResult.GetValue(raw), parseResult.GetValue(output), cancellationToken) is { } failed) + { + return failed; + } + } + else if (parseResult.GetValue(output) is { } file) { try { @@ -230,6 +256,44 @@ private static async Task ReportAsync( return response.BodyTruncated ? 63 : 0; } + /// The values selects in the body, printed or saved; the exit code when they cannot be. + private static async Task WriteFilteredAsync(JsonPath query, ResponseSnapshot response, bool compact, string? file, CancellationToken cancellationToken) + { + FilteredBody filtered; + try + { + filtered = BodyFilter.Apply(query, response.Body, response.ContentType, indented: !compact, cancellationToken: cancellationToken); + } + catch (JsonPathException ex) + { + Output.Error($"--filter: {ex.Message}"); + return 1; + } + catch (OperationCanceledException) + { + return 130; + } + + if (file is null) + { + Console.Out.WriteLine(filtered.Text); + return null; + } + + try + { + await File.WriteAllTextAsync(file, filtered.Text + "\n", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), cancellationToken); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + Output.Error($"The values could not be saved to {file}: {ex.Message}"); + return 1; + } + + Output.Info($"Saved {filtered.Count} value{(filtered.Count == 1 ? "" : "s")} to {file}"); + return null; + } + private static void PrintVerbose(HttpExchange exchange) { var request = exchange.Request; diff --git a/src/TermRest.Core/Http/BodyFilter.cs b/src/TermRest.Core/Http/BodyFilter.cs new file mode 100644 index 0000000..c5bd6a4 --- /dev/null +++ b/src/TermRest.Core/Http/BodyFilter.cs @@ -0,0 +1,140 @@ +using System.Buffers; +using System.Text; +using System.Text.Json; +using TermRest.Core.Json; + +namespace TermRest.Core.Http; + +/// The values a JSONPath query selects in a body, written as a JSON array. +/// The array: all the values, or the first when they would not fit the length asked. +/// How many values the query selects. +/// How many of them the array holds. +public sealed record FilteredBody(string Text, int Count, int Shown); + +/// Applies a JSONPath query to a response body. +public static class BodyFilter +{ + private static readonly JsonDocumentOptions DocumentOptions = new() { MaxDepth = 256 }; + + private static readonly JsonWriterOptions Indented = new() + { + Indented = true, + IndentCharacter = ' ', + IndentSize = 2, + NewLine = "\n", + Encoder = MinimalJsonEncoder.Instance, + MaxDepth = 1000, + }; + + private static readonly JsonWriterOptions Compact = new() { Encoder = MinimalJsonEncoder.Instance, MaxDepth = 1000 }; + + /// + /// The values selects in (decoded as it is shown: see + /// ; NDJSON and JSON Lines as an array of their lines), as a JSON array, two-space + /// indented or on one line. Values that would take it beyond of UTF-8 are left out. A + /// says why a body cannot be filtered: it is empty, binary or not JSON. + /// + public static FilteredBody Apply(JsonPath query, byte[] body, string? contentType, bool indented = true, long maxBytes = long.MaxValue, + CancellationToken cancellationToken = default) + { + if (body.Length == 0) + { + throw new JsonPathException("The body is empty."); + } + + if (!BodyFormatter.LooksLikeText(body, contentType)) + { + throw new JsonPathException("The body is binary, not JSON."); + } + + var text = BodyFormatter.Decode(body, contentType); + try + { + using var document = Parse(text, contentType); + var nodes = query.Select(document.RootElement, cancellationToken); + return Write(nodes, indented, maxBytes, cancellationToken); + } + catch (InvalidOperationException ex) when (ex is not ObjectDisposedException) + { + // System.Text.Json reads "\ud83d" (half of an emoji, cut by JavaScript), then fails on first access to it. + throw new JsonPathException("The body has a string holding half of a character (an unpaired surrogate such as \\ud83d)."); + } + } + + private static JsonDocument Parse(string text, string? contentType) + { + if (BodyFormatter.SubtypeHasWord(contentType, "ndjson", "jsonl", "jsonlines") && Lines(text) is { } lines) + { + return lines; + } + + try + { + return JsonDocument.Parse(text, DocumentOptions); + } + catch (JsonException ex) + { + throw new JsonPathException(ex.LineNumber is { } line + ? $"The body is not JSON: line {line + 1}, byte {ex.BytePositionInLine + 1}." + : "The body is not JSON."); + } + } + + /// JSON Lines: one array of the values on its lines; null when that is not what the body holds. + private static JsonDocument? Lines(string text) + { + var builder = new StringBuilder(text.Length + 16).Append('['); + var first = true; + foreach (var line in text.AsSpan().EnumerateLines()) + { + if (!line.IsWhiteSpace()) + { + if (!first) + { + builder.Append(','); + } + + builder.Append(line); + first = false; + } + + builder.Append('\n'); + } + + try + { + return JsonDocument.Parse(builder.Append(']').ToString(), DocumentOptions); + } + catch (JsonException) + { + return null; // one value written over several lines, say: read as a whole + } + } + + private static FilteredBody Write(IReadOnlyList nodes, bool indented, long maxBytes, CancellationToken cancellationToken) + { + var buffer = new ArrayBufferWriter(); + var shown = 0; + using (var writer = new Utf8JsonWriter(buffer, indented ? Indented : Compact)) + { + writer.WriteStartArray(); + foreach (var node in nodes) + { + if (shown > 0 && writer.BytesCommitted + writer.BytesPending > maxBytes) + { + break; + } + + node.WriteTo(writer); + if ((++shown & 255) == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + } + } + + writer.WriteEndArray(); + } + + return new FilteredBody(Encoding.UTF8.GetString(buffer.WrittenSpan), nodes.Count, shown); + } +} diff --git a/src/TermRest.Core/Http/BodyFormatter.cs b/src/TermRest.Core/Http/BodyFormatter.cs index 023c804..63fd18a 100644 --- a/src/TermRest.Core/Http/BodyFormatter.cs +++ b/src/TermRest.Core/Http/BodyFormatter.cs @@ -27,9 +27,13 @@ public static class BodyFormatter public static bool IsHtml(string? contentType) => SubtypeHasWord(contentType, "html", "xhtml"); - /// A short language label for the body (json, xml, html, text, binary). + /// A short language label for the body (json, xml, html, javascript, text, binary). public static string Language(byte[] body, string? contentType) => - IsJson(contentType) ? "json" : IsHtml(contentType) ? "html" : IsXml(contentType) ? "xml" : LooksLikeText(body, contentType) ? "text" : "binary"; + IsJson(contentType) ? "json" + : IsHtml(contentType) ? "html" + : IsXml(contentType) ? "xml" + : SubtypeHasWord(contentType, "javascript", "ecmascript") ? "javascript" + : LooksLikeText(body, contentType) ? "text" : "binary"; /// Whether a body is shown as text: its Content-Type declares text, or no NUL byte is near its start. public static bool LooksLikeText(byte[] body, string? contentType) => IsTextType(contentType) || !HasNulNearStart(body); diff --git a/src/TermRest.Core/Json/IRegexp.cs b/src/TermRest.Core/Json/IRegexp.cs new file mode 100644 index 0000000..523ac3c --- /dev/null +++ b/src/TermRest.Core/Json/IRegexp.cs @@ -0,0 +1,629 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; + +namespace TermRest.Core.Json; + +/// +/// Turns I-Regexp (RFC 9485), the regular expressions of JSONPath's match and search, into .NET ones that match code +/// points as I-Regexp does, not UTF-16 code units: "." and [^a] match an emoji whole, \p{L} matches 𝒜. +/// +internal static class IRegexp +{ + /// How long a regular expression may take on one string. + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(2); + + private static readonly ConcurrentDictionary<(string Category, bool Negated), List<(int Low, int High)>> SupplementaryCategories = new(); + + private const string Surrogates = @"\uD800-\uDFFF"; + + /// "." of I-Regexp: any code point but a line feed or a carriage return. + private const string Dot = @"(?:[^\n\r\uD800-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF])"; + + /// + /// A regular expression that matches what matches: the whole string (match) or a part of it + /// (search). Null when the pattern is not an I-Regexp, which then matches nothing. + /// + public static Regex? Create(string pattern, bool whole) + { + if (Translate(pattern) is not { } translated) + { + return null; + } + + var expression = whole ? $@"\A(?:{translated})\z" : translated; + try + { + // Matches in a time proportional to the string's length: a pattern taken from a response cannot hang a filter. + return new Regex(expression, RegexOptions.CultureInvariant | RegexOptions.NonBacktracking, Timeout); + } + catch (NotSupportedException) + { + try + { + return new Regex(expression, RegexOptions.CultureInvariant, Timeout); // too large for that engine: a{1000}{1000} + } + catch (ArgumentException) + { + return null; + } + } + catch (ArgumentException) + { + return null; // a count .NET cannot take: a{99999999999} + } + } + + public static bool IsMatch(Regex regex, string text) + { + try + { + return regex.IsMatch(text); + } + catch (RegexMatchTimeoutException) + { + throw new JsonPathException($"A regular expression takes more than {Timeout.TotalSeconds.ToString(CultureInfo.InvariantCulture)} seconds on a string of {text.Length.ToString(CultureInfo.InvariantCulture)} characters."); + } + } + + /// The .NET pattern for an I-Regexp; null when the text is not one. + internal static string? Translate(string pattern) => new Translator(pattern).Run(); + + private sealed class Translator(string pattern) + { + private const int MaxDepth = 64; + + private readonly StringBuilder _out = new(); + private int _pos; + private int _depth; + + public string? Run() + { + try + { + Regexp(); + return _pos == pattern.Length ? _out.ToString() : null; // a ) that closes nothing + } + catch (FormatException) + { + return null; + } + } + + // i-regexp = branch *( "|" branch ); branch = *piece; piece = atom [ quantifier ] + private void Regexp() + { + while (true) + { + while (_pos < pattern.Length && pattern[_pos] is not ('|' or ')')) + { + Atom(); + Quantifier(); + } + + if (!Take('|')) + { + return; + } + + _out.Append('|'); + } + } + + private void Atom() + { + switch (pattern[_pos]) + { + case '(': + _pos++; + if (++_depth > MaxDepth) + { + throw new FormatException(); + } + + _out.Append("(?:"); + Regexp(); + if (!Take(')')) + { + throw new FormatException(); + } + + _out.Append(')'); + _depth--; + break; + case '.': + _pos++; + _out.Append(Dot); + break; + case '[': + _pos++; + var negated = Take('^'); + var set = new CodePointSet(); + ClassItems(set); + Append(set, negated); + break; + case '\\' when Peek(1) is 'p' or 'P': + var category = new CodePointSet(); + Category(category); + Append(category, negated: false); + break; + case '\\': + AppendLiteral(SingleCharEscape()); + break; + + // Anchors, as ECMAScript (and the JSONPath compliance tests) take them. + case '^': + _pos++; + _out.Append(@"(?:\A)"); + break; + case '$': + _pos++; + _out.Append(@"(?:\z)"); + break; + case '*' or '+' or '?' or '{' or '}' or ']': + throw new FormatException(); + default: + AppendLiteral(CodePoint()); + break; + } + } + + // quantifier = "*" / "+" / "?" / "{" n [ "," [ m ] ] "}" + private void Quantifier() + { + if (_pos >= pattern.Length) + { + return; + } + + switch (pattern[_pos]) + { + case '*' or '+' or '?': + _out.Append(pattern[_pos++]); + break; + case '{': + var start = _pos++; + var min = Count() ?? throw new FormatException(); + var max = min; + if (Take(',')) + { + max = Count() ?? long.MaxValue; + } + + if (!Take('}') || max < min) + { + throw new FormatException(); + } + + _out.Append(pattern, start, _pos - start); + break; + } + } + + private long? Count() + { + var start = _pos; + long value = 0; + while (_pos < pattern.Length && char.IsAsciiDigit(pattern[_pos])) + { + value = Math.Min(value * 10 + (pattern[_pos++] - '0'), int.MaxValue); + } + + return _pos == start ? null : value; + } + + // charClassExpr = "[" [ "^" ] ( "-" / CCE1 ) *CCE1 [ "-" ] "]"; CCE1 = ( CCchar [ "-" CCchar ] ) / charClassEsc + private void ClassItems(CodePointSet set) + { + var first = true; + while (true) + { + if (_pos >= pattern.Length) + { + throw new FormatException(); + } + + var c = pattern[_pos]; + if (c == ']' && !first) + { + _pos++; + return; + } + + if (c == '-') + { + if (!first && Peek(1) != ']') + { + throw new FormatException(); // a - only comes first or last + } + + _pos++; + set.Ranges.Add(('-', '-')); + } + else if (c == '\\' && Peek(1) is 'p' or 'P') + { + Category(set); + } + else + { + var low = ClassChar(); + var high = low; + if (Peek(0) == '-' && Peek(1) is not (']' or -1)) + { + _pos++; + if (Peek(0) == '\\' && Peek(1) is 'p' or 'P') + { + throw new FormatException(); + } + + high = ClassChar(); + if (high < low) + { + throw new FormatException(); + } + } + + set.Ranges.Add((low, high)); + } + + first = false; + } + } + + // CCchar = ( %x00-2C / %x2E-5A / %x5E-D7FF / %xE000-10FFFF ) / SingleCharEsc + private int ClassChar() => pattern[_pos] switch + { + '\\' => SingleCharEscape(), + '-' or '[' or ']' => throw new FormatException(), + _ => CodePoint(), + }; + + // SingleCharEsc = "\" ( %x28-2B / "-" / "." / "?" / %x5B-5E / "n" / "r" / "t" / %x7B-7D ) + private int SingleCharEscape() + { + var c = Peek(1); + _pos += 2; + return c switch + { + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + '(' or ')' or '*' or '+' or '-' or '.' or '?' or '[' or '\\' or ']' or '^' or '{' or '|' or '}' => c, + _ => throw new FormatException(), + }; + } + + // catEsc = "\p{" charProp "}"; complEsc = "\P{" charProp "}" + private void Category(CodePointSet set) + { + var negated = pattern[_pos + 1] == 'P'; + _pos += 2; + if (!Take('{')) + { + throw new FormatException(); + } + + var end = pattern.IndexOf('}', _pos); + if (end < 0 || CategoryMembers(pattern[_pos..end]) is null) + { + throw new FormatException(); + } + + set.Categories.Add((pattern[_pos..end], negated)); + _pos = end + 1; + } + + private int CodePoint() + { + var c = pattern[_pos]; + if (char.IsHighSurrogate(c) && _pos + 1 < pattern.Length && char.IsLowSurrogate(pattern[_pos + 1])) + { + _pos += 2; + return char.ConvertToUtf32(c, pattern[_pos - 1]); + } + + if (char.IsSurrogate(c)) + { + throw new FormatException(); + } + + _pos++; + return c; + } + + private void AppendLiteral(int codePoint) + { + if (codePoint > 0xFFFF) + { + // A pair, grouped so that a quantifier repeats the character. + var text = char.ConvertFromUtf32(codePoint); + _out.Append("(?:"); + AppendUnit(_out, text[0]); + AppendUnit(_out, text[1]); + _out.Append(')'); + } + else + { + AppendUnit(_out, (char)codePoint); + } + } + + /// + /// A character class: its BMP part as a .NET class without surrogates, and its other code points as the surrogate + /// pairs that write them. + /// + private void Append(CodePointSet set, bool negated) + { + var bmp = new StringBuilder(); + var supplementary = new List<(int Low, int High)>(); + foreach (var (low, high) in set.Ranges) + { + if (low <= 0xFFFF) + { + AppendUnit(bmp, (char)low); + if (high > low) + { + bmp.Append('-'); + AppendUnit(bmp, (char)Math.Min(high, 0xFFFF)); + } + } + + if (high > 0xFFFF) + { + supplementary.Add((Math.Max(low, 0x10000), high)); + } + } + + foreach (var (name, categoryNegated) in set.Categories) + { + bmp.Append(categoryNegated ? @"\P{" : @"\p{").Append(name).Append('}'); + supplementary.AddRange(SupplementaryRanges(name, categoryNegated)); + } + + supplementary = Merge(supplementary); + var alternatives = new List(); + if (negated) + { + alternatives.Add($"[^{bmp}{Surrogates}]"); + alternatives.AddRange(Pairs(Complement(supplementary))); + } + else + { + if (bmp.Length > 0) + { + alternatives.Add($"[{bmp}-[{Surrogates}]]"); + } + + alternatives.AddRange(Pairs(supplementary)); + } + + _out.Append("(?:").AppendJoin('|', alternatives.Count > 0 ? alternatives : [@"[^\u0000-\uFFFF]"]).Append(')'); + } + + private int Peek(int offset) => _pos + offset < pattern.Length ? pattern[_pos + offset] : -1; + + private bool Take(char c) + { + if (Peek(0) != c) + { + return false; + } + + _pos++; + return true; + } + } + + private sealed class CodePointSet + { + public List<(int Low, int High)> Ranges { get; } = []; + + public List<(string Name, bool Negated)> Categories { get; } = []; + } + + private static void AppendUnit(StringBuilder builder, char c) + { + if (char.IsAsciiLetterOrDigit(c)) + { + builder.Append(c); + } + else + { + builder.Append(@"\u").Append(((int)c).ToString("X4", CultureInfo.InvariantCulture)); + } + } + + /// The general categories in an I-Regexp category name (Lu, or L for all letters); null for another name. + private static UnicodeCategory[]? CategoryMembers(string name) => name switch + { + "L" => [UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter], + "Lu" => [UnicodeCategory.UppercaseLetter], + "Ll" => [UnicodeCategory.LowercaseLetter], + "Lt" => [UnicodeCategory.TitlecaseLetter], + "Lm" => [UnicodeCategory.ModifierLetter], + "Lo" => [UnicodeCategory.OtherLetter], + "M" => [UnicodeCategory.NonSpacingMark, UnicodeCategory.SpacingCombiningMark, UnicodeCategory.EnclosingMark], + "Mn" => [UnicodeCategory.NonSpacingMark], + "Mc" => [UnicodeCategory.SpacingCombiningMark], + "Me" => [UnicodeCategory.EnclosingMark], + "N" => [UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber], + "Nd" => [UnicodeCategory.DecimalDigitNumber], + "Nl" => [UnicodeCategory.LetterNumber], + "No" => [UnicodeCategory.OtherNumber], + "P" => + [ + UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, + UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation, + ], + "Pc" => [UnicodeCategory.ConnectorPunctuation], + "Pd" => [UnicodeCategory.DashPunctuation], + "Ps" => [UnicodeCategory.OpenPunctuation], + "Pe" => [UnicodeCategory.ClosePunctuation], + "Pi" => [UnicodeCategory.InitialQuotePunctuation], + "Pf" => [UnicodeCategory.FinalQuotePunctuation], + "Po" => [UnicodeCategory.OtherPunctuation], + "Z" => [UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator], + "Zs" => [UnicodeCategory.SpaceSeparator], + "Zl" => [UnicodeCategory.LineSeparator], + "Zp" => [UnicodeCategory.ParagraphSeparator], + "S" => [UnicodeCategory.MathSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherSymbol], + "Sm" => [UnicodeCategory.MathSymbol], + "Sc" => [UnicodeCategory.CurrencySymbol], + "Sk" => [UnicodeCategory.ModifierSymbol], + "So" => [UnicodeCategory.OtherSymbol], + "C" => [UnicodeCategory.Control, UnicodeCategory.Format, UnicodeCategory.Surrogate, UnicodeCategory.PrivateUse, UnicodeCategory.OtherNotAssigned], + "Cc" => [UnicodeCategory.Control], + "Cf" => [UnicodeCategory.Format], + "Co" => [UnicodeCategory.PrivateUse], + "Cn" => [UnicodeCategory.OtherNotAssigned], + _ => null, + }; + + /// The code points from U+10000 on in a category (or out of it), worked out once per category. + private static List<(int Low, int High)> SupplementaryRanges(string category, bool negated) => + SupplementaryCategories.GetOrAdd((category, negated), static key => + { + var members = new bool[32]; + foreach (var member in CategoryMembers(key.Category)!) + { + members[(int)member] = true; + } + + var ranges = new List<(int Low, int High)>(); + var start = -1; + for (var codePoint = 0x10000; codePoint <= 0x110000; codePoint++) + { + var inSet = codePoint <= 0x10FFFF && members[(int)Rune.GetUnicodeCategory(new Rune(codePoint))] != key.Negated; + if (inSet && start < 0) + { + start = codePoint; + } + else if (!inSet && start >= 0) + { + ranges.Add((start, codePoint - 1)); + start = -1; + } + } + + return ranges; + }); + + private static List<(int Low, int High)> Merge(List<(int Low, int High)> ranges) + { + ranges.Sort(); + var merged = new List<(int Low, int High)>(); + foreach (var range in ranges) + { + if (merged.Count > 0 && range.Low <= merged[^1].High + 1) + { + merged[^1] = (merged[^1].Low, Math.Max(merged[^1].High, range.High)); + } + else + { + merged.Add(range); + } + } + + return merged; + } + + /// The code points from U+10000 to U+10FFFF outside the (merged) ranges. + private static List<(int Low, int High)> Complement(List<(int Low, int High)> ranges) + { + var complement = new List<(int Low, int High)>(); + var next = 0x10000; + foreach (var (low, high) in ranges) + { + if (low > next) + { + complement.Add((next, low - 1)); + } + + next = high + 1; + } + + if (next <= 0x10FFFF) + { + complement.Add((next, 0x10FFFF)); + } + + return complement; + } + + /// + /// The surrogate pairs that write code points of the (merged) ranges, grouped: for each run of high surrogates followed + /// by the same low surrogates, one alternative. + /// + private static List Pairs(List<(int Low, int High)> ranges) + { + var lows = new List<(int Low, int High)>?[0x400]; + foreach (var (low, high) in ranges) + { + for (var h = (low - 0x10000) >> 10; h <= (high - 0x10000) >> 10; h++) + { + var first = Math.Max(low, 0x10000 + (h << 10)); + var last = Math.Min(high, 0x10000 + (h << 10) + 0x3FF); + (lows[h] ??= []).Add((0xDC00 + ((first - 0x10000) & 0x3FF), 0xDC00 + ((last - 0x10000) & 0x3FF))); + } + } + + var alternatives = new List(); + for (var h = 0; h < lows.Length;) + { + if (lows[h] is not { } same) + { + h++; + continue; + } + + var end = h; + while (end + 1 < lows.Length && lows[end + 1] is { } next && next.SequenceEqual(same)) + { + end++; + } + + var builder = new StringBuilder(); + AppendRange(builder, 0xD800 + h, 0xD800 + end); + if (same.Count == 1) + { + AppendRange(builder, same[0].Low, same[0].High); + } + else + { + builder.Append('['); + foreach (var (low, high) in same) + { + AppendUnit(builder, (char)low); + if (high > low) + { + builder.Append('-'); + AppendUnit(builder, (char)high); + } + } + + builder.Append(']'); + } + + alternatives.Add(builder.ToString()); + h = end + 1; + } + + return alternatives; + } + + private static void AppendRange(StringBuilder builder, int low, int high) + { + if (low == high) + { + AppendUnit(builder, (char)low); + return; + } + + builder.Append('['); + AppendUnit(builder, (char)low); + builder.Append('-'); + AppendUnit(builder, (char)high); + builder.Append(']'); + } +} diff --git a/src/TermRest.Core/Json/JsonPath.cs b/src/TermRest.Core/Json/JsonPath.cs new file mode 100644 index 0000000..972b3d0 --- /dev/null +++ b/src/TermRest.Core/Json/JsonPath.cs @@ -0,0 +1,43 @@ +using System.Text.Json; + +namespace TermRest.Core.Json; + +/// +/// A JSONPath query (RFC 9535), such as $.store.book[?@.price < 10].title: selects values of a JSON document. +/// Its functions are the RFC's: length, count, value, and match and search, which take an I-Regexp (RFC 9485). +/// +public sealed class JsonPath +{ + /// The most values one step of a query may select: $..*..* on a large document fails rather than fill the memory. + internal const int MaxNodes = 1 << 22; + + private readonly PathQuery _query; + + private JsonPath(string text, PathQuery query) + { + Text = text; + _query = query; + } + + /// The query as written. + public string Text { get; } + + /// Parses a query; a says where it is not valid JSONPath. + public static JsonPath Parse(string text) => new(text, JsonPathParser.Parse(text)); + + /// + /// The values the query selects in , in document order. A when a + /// step selects too many values, or a regular expression takes too long. + /// + public IReadOnlyList Select(JsonElement root, CancellationToken cancellationToken = default) => + _query.Select(root, new PathEvaluation(root, cancellationToken)); + + public override string ToString() => Text; +} + +/// A query that is not valid JSONPath ( says where), or that could not be applied. +public sealed class JsonPathException(string message, int position = -1) : FormatException(message) +{ + /// Where in the query the problem is (from 0), or -1. + public int Position { get; } = position; +} diff --git a/src/TermRest.Core/Json/JsonPathEvaluation.cs b/src/TermRest.Core/Json/JsonPathEvaluation.cs new file mode 100644 index 0000000..421268b --- /dev/null +++ b/src/TermRest.Core/Json/JsonPathEvaluation.cs @@ -0,0 +1,838 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace TermRest.Core.Json; + +/// A query: from the root ($) or from the current value of a filter (@), then its segments. +internal sealed class PathQuery(bool absolute, Segment[] segments) +{ + /// Whether it selects at most one value: one name or index per segment, and no descendants. + public bool IsSingular { get; } = Array.TrueForAll(segments, s => s is ChildSegment { Selectors: [NameSelector or IndexSelector] }); + + public List Select(JsonElement current, PathEvaluation evaluation) + { + if (absolute && evaluation.Cached(this) is { } cached) + { + return cached; // the same for every value a filter tests + } + + List nodes = [absolute ? evaluation.Root : current]; + foreach (var segment in segments) + { + var next = new List(); + foreach (var node in nodes) + { + segment.Apply(node, next, evaluation); + } + + nodes = next; + if (nodes.Count == 0) + { + break; + } + } + + if (absolute) + { + evaluation.Cache(this, nodes); + } + + return nodes; + } + + /// The value a singular query selects, if any. + public bool TrySelectOne(JsonElement current, PathEvaluation evaluation, out JsonElement value) + { + if (absolute) + { + // Worked out once per filter, not once per value tested: $[-1] reads the whole array before its last element. + var nodes = Select(current, evaluation); + value = nodes.Count > 0 ? nodes[0] : default; + return nodes.Count > 0; + } + + value = current; + foreach (var segment in segments) + { + if (!segment.Selectors[0].TrySelectOne(value, out value)) + { + return false; + } + } + + return true; + } + + public bool SelectsAny(JsonElement current, PathEvaluation evaluation) => + IsSingular ? TrySelectOne(current, evaluation, out _) : Select(current, evaluation).Count > 0; +} + +internal abstract class Segment(Selector[] selectors) +{ + public Selector[] Selectors { get; } = selectors; + + public abstract void Apply(JsonElement node, List output, PathEvaluation evaluation); +} + +/// [selectors], .name or .*: what the selectors select among the children of a value. +internal sealed class ChildSegment(Selector[] selectors) : Segment(selectors) +{ + public override void Apply(JsonElement node, List output, PathEvaluation evaluation) + { + foreach (var selector in Selectors) + { + selector.Select(node, output, evaluation); + } + } +} + +/// ..[selectors], ..name or ..*: the same for a value and each of its descendants, each before its children. +internal sealed class DescendantSegment(Selector[] selectors) : Segment(selectors) +{ + public override void Apply(JsonElement node, List output, PathEvaluation evaluation) + { + RuntimeHelpers.EnsureSufficientExecutionStack(); + foreach (var selector in Selectors) + { + selector.Select(node, output, evaluation); + } + + evaluation.Step(); + if (node.ValueKind == JsonValueKind.Array) + { + foreach (var item in node.EnumerateArray()) + { + Apply(item, output, evaluation); + } + } + else if (node.ValueKind == JsonValueKind.Object) + { + foreach (var property in node.EnumerateObject()) + { + Apply(property.Value, output, evaluation); + } + } + } +} + +internal abstract class Selector +{ + public abstract void Select(JsonElement node, List output, PathEvaluation evaluation); + + /// For the selectors a singular query is made of (a name, an index): the value selected, if any. + public virtual bool TrySelectOne(JsonElement node, out JsonElement value) => throw new NotSupportedException(); +} + +internal sealed class NameSelector(string name) : Selector +{ + public override void Select(JsonElement node, List output, PathEvaluation evaluation) + { + if (TrySelectOne(node, out var value)) + { + evaluation.Add(output, value); + } + } + + public override bool TrySelectOne(JsonElement node, out JsonElement value) + { + value = default; + return node.ValueKind == JsonValueKind.Object && node.TryGetProperty(name, out value); + } +} + +internal sealed class WildcardSelector : Selector +{ + public static readonly WildcardSelector Instance = new(); + + public override void Select(JsonElement node, List output, PathEvaluation evaluation) + { + if (node.ValueKind == JsonValueKind.Array) + { + foreach (var item in node.EnumerateArray()) + { + evaluation.Add(output, item); + } + } + else if (node.ValueKind == JsonValueKind.Object) + { + foreach (var property in node.EnumerateObject()) + { + evaluation.Add(output, property.Value); + } + } + } +} + +internal sealed class IndexSelector(long index) : Selector +{ + public override void Select(JsonElement node, List output, PathEvaluation evaluation) + { + if (TrySelectOne(node, out var value)) + { + evaluation.Add(output, value); + } + } + + public override bool TrySelectOne(JsonElement node, out JsonElement value) + { + if (node.ValueKind == JsonValueKind.Array) + { + var length = node.GetArrayLength(); + var i = index >= 0 ? index : length + index; + if (i >= 0 && i < length) + { + value = node[(int)i]; + return true; + } + } + + value = default; + return false; + } +} + +/// [start:end:step], with the bounds of RFC 9535: negative ones count from the end, and a negative step goes backwards. +internal sealed class SliceSelector(long? start, long? end, long step) : Selector +{ + public override void Select(JsonElement node, List output, PathEvaluation evaluation) + { + if (node.ValueKind != JsonValueKind.Array || step == 0) + { + return; + } + + // The elements are enumerated, not indexed: finding an element of an array of objects by index reads all before it. + long length = node.GetArrayLength(); + if (step > 0) + { + var lower = Math.Clamp(Normalize(start ?? 0, length), 0, length); + var upper = Math.Clamp(Normalize(end ?? length, length), 0, length); + long i = 0; + var next = lower; + foreach (var item in node.EnumerateArray()) + { + if (i >= upper) + { + break; + } + + if (i == next) + { + evaluation.Add(output, item); + next += step; + } + + i++; + } + } + else + { + var upper = Math.Clamp(Normalize(start ?? length - 1, length), -1, length - 1); + var lower = Math.Clamp(Normalize(end ?? -length - 1, length), -1, length - 1); + if (upper <= lower) + { + return; + } + + var items = new JsonElement[upper + 1]; + var count = 0; + foreach (var item in node.EnumerateArray()) + { + if (count > upper) + { + break; + } + + items[count++] = item; + } + + for (var i = upper; i > lower; i += step) + { + evaluation.Add(output, items[i]); + } + } + } + + private static long Normalize(long index, long length) => index >= 0 ? index : length + index; +} + +/// [?test]: the children of a value for which the test is true. +internal sealed class FilterSelector(LogicalExpression condition) : Selector +{ + public override void Select(JsonElement node, List output, PathEvaluation evaluation) + { + if (node.ValueKind == JsonValueKind.Array) + { + foreach (var item in node.EnumerateArray()) + { + evaluation.Step(); + if (condition.Test(item, evaluation)) + { + evaluation.Add(output, item); + } + } + } + else if (node.ValueKind == JsonValueKind.Object) + { + foreach (var property in node.EnumerateObject()) + { + evaluation.Step(); + if (condition.Test(property.Value, evaluation)) + { + evaluation.Add(output, property.Value); + } + } + } + } +} + +internal abstract class LogicalExpression +{ + public abstract bool Test(JsonElement current, PathEvaluation evaluation); +} + +internal sealed class OrExpression(LogicalExpression left, LogicalExpression right) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) => left.Test(current, evaluation) || right.Test(current, evaluation); +} + +internal sealed class AndExpression(LogicalExpression left, LogicalExpression right) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) => left.Test(current, evaluation) && right.Test(current, evaluation); +} + +internal sealed class NotExpression(LogicalExpression inner) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) => !inner.Test(current, evaluation); +} + +/// A query as a test: whether it selects anything (a value that is false or null too). +internal sealed class ExistsExpression(PathQuery query) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) => query.SelectsAny(current, evaluation); +} + +internal sealed class FunctionTestExpression(FunctionCall call) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) => call.Test(current, evaluation); +} + +/// The comparison operators, in the order the parser tries them. +internal enum ComparisonOperator +{ + Equal, + NotEqual, + LessOrEqual, + GreaterOrEqual, + Less, + Greater, +} + +internal sealed class ComparisonExpression(ValueExpression left, ComparisonOperator op, ValueExpression right) : LogicalExpression +{ + public override bool Test(JsonElement current, PathEvaluation evaluation) + { + var a = left.Evaluate(current, evaluation); + var b = right.Evaluate(current, evaluation); + return op switch + { + ComparisonOperator.Equal => PathValue.AreEqual(a, b), + ComparisonOperator.NotEqual => !PathValue.AreEqual(a, b), + ComparisonOperator.Less => PathValue.IsLess(a, b), + ComparisonOperator.LessOrEqual => PathValue.IsLess(a, b) || PathValue.AreEqual(a, b), + ComparisonOperator.Greater => PathValue.IsLess(b, a), + _ => PathValue.IsLess(b, a) || PathValue.AreEqual(a, b), + }; + } +} + +internal abstract class ValueExpression +{ + public abstract PathValue Evaluate(JsonElement current, PathEvaluation evaluation); +} + +internal sealed class LiteralExpression(PathValue value) : ValueExpression +{ + public PathValue Value { get; } = value; + + public override PathValue Evaluate(JsonElement current, PathEvaluation evaluation) => Value; +} + +/// A singular query as a value: the value it selects, or nothing. +internal sealed class QueryValueExpression(PathQuery query) : ValueExpression +{ + public override PathValue Evaluate(JsonElement current, PathEvaluation evaluation) => + query.TrySelectOne(current, evaluation, out var value) ? PathValue.Of(value) : default; +} + +internal sealed class FunctionValueExpression(FunctionCall call) : ValueExpression +{ + public override PathValue Evaluate(JsonElement current, PathEvaluation evaluation) => call.Evaluate(current, evaluation); +} + +/// The types of RFC 9535 function parameters and results. +internal enum PathType +{ + Value, + Logical, + Nodes, +} + +internal enum PathFunction +{ + Length, + Count, + Match, + Search, + Value, +} + +internal sealed class FunctionCall +{ + private readonly PathFunction _function; + private readonly object[] _arguments; + private readonly bool _literalPattern; + private readonly Regex? _regex; + + public FunctionCall(string name, PathFunction function, PathType result, object[] arguments) + { + Name = name; + Result = result; + _function = function; + _arguments = arguments; + if (function is PathFunction.Match or PathFunction.Search && arguments[1] is LiteralExpression literal) + { + // Written in the query: translated once, not for each value tested. + _literalPattern = true; + _regex = literal.Value.Kind == JsonValueKind.String ? IRegexp.Create(literal.Value.GetString(), whole: function == PathFunction.Match) : null; + } + } + + public string Name { get; } + + public PathType Result { get; } + + public static (PathFunction Function, PathType[] Parameters, PathType Result)? Find(string name) => name switch + { + "length" => (PathFunction.Length, [PathType.Value], PathType.Value), + "count" => (PathFunction.Count, [PathType.Nodes], PathType.Value), + "match" => (PathFunction.Match, [PathType.Value, PathType.Value], PathType.Logical), + "search" => (PathFunction.Search, [PathType.Value, PathType.Value], PathType.Logical), + "value" => (PathFunction.Value, [PathType.Nodes], PathType.Value), + _ => null, + }; + + /// length, count or value. + public PathValue Evaluate(JsonElement current, PathEvaluation evaluation) + { + switch (_function) + { + case PathFunction.Length: + var value = ((ValueExpression)_arguments[0]).Evaluate(current, evaluation); + return value.Kind switch + { + JsonValueKind.String => PathValue.Of(CodePoints(value.GetString())), + JsonValueKind.Array => PathValue.Of(value.Element.GetArrayLength()), + JsonValueKind.Object => PathValue.Of(value.Element.GetPropertyCount()), + _ => default, + }; + case PathFunction.Count: + return PathValue.Of(((PathQuery)_arguments[0]).Select(current, evaluation).Count); + default: + var nodes = ((PathQuery)_arguments[0]).Select(current, evaluation); + return nodes.Count == 1 ? PathValue.Of(nodes[0]) : default; + } + } + + /// match (the whole string) or search (a part of it). + public bool Test(JsonElement current, PathEvaluation evaluation) + { + var subject = ((ValueExpression)_arguments[0]).Evaluate(current, evaluation); + if (subject.Kind != JsonValueKind.String) + { + return false; + } + + Regex? regex; + if (_literalPattern) + { + regex = _regex; + } + else + { + var pattern = ((ValueExpression)_arguments[1]).Evaluate(current, evaluation); + if (pattern.Kind != JsonValueKind.String) + { + return false; + } + + regex = evaluation.Regex(pattern.GetString(), whole: _function == PathFunction.Match); + } + + return regex is not null && IRegexp.IsMatch(regex, subject.GetString()); + } + + /// The length of a string in characters (code points): an emoji is one. + private static int CodePoints(string text) + { + var count = text.Length; + for (var i = 1; i < text.Length; i++) + { + if (char.IsLowSurrogate(text[i]) && char.IsHighSurrogate(text[i - 1])) + { + count--; + } + } + + return count; + } +} + +/// One application of a query: the document, what is worth keeping while it runs, and its cancellation. +internal sealed class PathEvaluation(JsonElement root, CancellationToken cancellationToken) +{ + private const int MaxCachedRegexes = 100; + + private int _steps; + private Dictionary>? _absolute; + private Dictionary<(string Pattern, bool Whole), Regex?>? _regexes; + + public JsonElement Root { get; } = root; + + public void Step() + { + if ((++_steps & 1023) == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + } + } + + public void Add(List nodes, JsonElement node) + { + if (nodes.Count >= JsonPath.MaxNodes) + { + throw new JsonPathException($"The query selects more than {JsonPath.MaxNodes.ToString("N0", CultureInfo.InvariantCulture)} values in one step."); + } + + nodes.Add(node); + Step(); + } + + public List? Cached(PathQuery query) => _absolute?.GetValueOrDefault(query); + + public void Cache(PathQuery query, List nodes) => (_absolute ??= [])[query] = nodes; + + /// A pattern taken from the document: translated once per distinct pattern. + public Regex? Regex(string pattern, bool whole) + { + _regexes ??= []; + if (!_regexes.TryGetValue((pattern, whole), out var regex)) + { + regex = IRegexp.Create(pattern, whole); + if (_regexes.Count < MaxCachedRegexes) + { + _regexes[(pattern, whole)] = regex; + } + } + + return regex; + } +} + +/// A value in a filter: a value of the document, a literal, a number a function computed, or nothing. +internal readonly struct PathValue +{ + private readonly JsonElement _element; + private readonly string? _text; + private readonly long _integer; + private readonly Source _source; + + private PathValue(Source source, JsonElement element, string? text, long integer) + { + _source = source; + _element = element; + _text = text; + _integer = integer; + } + + private enum Source : byte + { + Nothing, + Element, + Integer, + Text, + } + + /// The kind of value; for nothing (a query that selects no value). + public JsonValueKind Kind => _source switch + { + Source.Element => _element.ValueKind, + Source.Integer => JsonValueKind.Number, + Source.Text => JsonValueKind.String, + _ => JsonValueKind.Undefined, + }; + + public JsonElement Element => _element; + + public static PathValue Of(JsonElement element) => new(Source.Element, element, null, 0); + + public static PathValue Of(long integer) => new(Source.Integer, default, null, integer); + + public static PathValue Of(string text) => new(Source.Text, default, text, 0); + + public string GetString() => _text ?? _element.GetString()!; + + /// ==: nothing equals only nothing; numbers by value (1 == 1.0); arrays and objects by their contents. + public static bool AreEqual(in PathValue a, in PathValue b) + { + var kind = a.Kind; + if (kind != b.Kind) + { + return false; + } + + return kind switch + { + JsonValueKind.Number => CompareNumbers(a, b) == 0, + JsonValueKind.String => a._text is not null ? (b._text is not null ? a._text == b._text : b._element.ValueEquals(a._text)) + : b._text is not null ? a._element.ValueEquals(b._text) : StringsEqual(a._element, b._element), + JsonValueKind.Array or JsonValueKind.Object => DeepEquals(a._element, b._element), + _ => true, // true, false, null; and nothing + }; + } + + /// <: numbers by value, strings by code point; false for anything else. + public static bool IsLess(in PathValue a, in PathValue b) + { + var kind = a.Kind; + if (kind != b.Kind) + { + return false; + } + + return kind switch + { + JsonValueKind.Number => CompareNumbers(a, b) < 0, + JsonValueKind.String => CompareCodePoints(a.GetString(), b.GetString()) < 0, + _ => false, + }; + } + + /// + /// Compares strings by code point, as RFC 9535 requires: UTF-16 order puts U+E000 to U+FFFF after the surrogate pairs + /// that write U+10000 and above. + /// + internal static int CompareCodePoints(string a, string b) + { + var length = Math.Min(a.Length, b.Length); + for (var i = 0; i < length; i++) + { + if (a[i] != b[i]) + { + return Order(a[i]) - Order(b[i]); + } + } + + return a.Length - b.Length; + + static int Order(char c) => c < 0xD800 ? c : c >= 0xE000 ? c - 0x800 : c + 0x2000; + } + + private static int CompareNumbers(in PathValue a, in PathValue b) + { + if (a._source == Source.Integer && b._source == Source.Integer) + { + return a._integer.CompareTo(b._integer); + } + + Span x = stackalloc byte[20]; + Span y = stackalloc byte[20]; + return JsonNumbers.Compare(a.RawNumber(x), b.RawNumber(y)); + } + + private ReadOnlySpan RawNumber(Span buffer) + { + if (_source != Source.Integer) + { + return JsonMarshal.GetRawUtf8Value(_element); + } + + _integer.TryFormat(buffer, out var written, default, CultureInfo.InvariantCulture); + return buffer[..written]; + } + + private static bool StringsEqual(JsonElement a, JsonElement b) + { + // Equal strings written without escapes are the same bytes. + var x = JsonMarshal.GetRawUtf8Value(a); + var y = JsonMarshal.GetRawUtf8Value(b); + return x.Contains((byte)'\\') || y.Contains((byte)'\\') ? a.GetString() == b.GetString() : x.SequenceEqual(y); + } + + private static bool DeepEquals(JsonElement a, JsonElement b) + { + RuntimeHelpers.EnsureSufficientExecutionStack(); + if (a.ValueKind != b.ValueKind) + { + return false; + } + + switch (a.ValueKind) + { + case JsonValueKind.Number: + return JsonNumbers.Compare(JsonMarshal.GetRawUtf8Value(a), JsonMarshal.GetRawUtf8Value(b)) == 0; + case JsonValueKind.String: + return StringsEqual(a, b); + case JsonValueKind.Array: + if (a.GetArrayLength() != b.GetArrayLength()) + { + return false; + } + + var left = a.EnumerateArray(); + var right = b.EnumerateArray(); + while (left.MoveNext() && right.MoveNext()) + { + if (!DeepEquals(left.Current, right.Current)) + { + return false; + } + } + + return true; + case JsonValueKind.Object: + if (a.GetPropertyCount() != b.GetPropertyCount()) + { + return false; + } + + foreach (var property in a.EnumerateObject()) + { + if (!b.TryGetProperty(property.Name, out var other) || !DeepEquals(property.Value, other)) + { + return false; + } + } + + return true; + default: + return true; + } + } +} + +/// Exact comparison of JSON numbers as written: 1, 1.0 and 1e0 are equal; 9007199254740993 is not 9007199254740992. +internal static class JsonNumbers +{ + /// Exponents beyond this (in absolute value) are taken as this: no JSON number is that far from 1 in practice. + private const long MaxExponent = 1_000_000_000_000_000; + + public static int Compare(ReadOnlySpan x, ReadOnlySpan y) + { + var a = new Parts(x); + var b = new Parts(y); + if (a.Sign != b.Sign) + { + return a.Sign.CompareTo(b.Sign); + } + + if (a.Sign == 0) + { + return 0; + } + + var magnitude = a.Exponent != b.Exponent ? a.Exponent.CompareTo(b.Exponent) : CompareDigits(a, b); + return a.Sign > 0 ? magnitude : -magnitude; + } + + private static int CompareDigits(in Parts a, in Parts b) + { + var count = Math.Min(a.Count, b.Count); + for (var i = 0; i < count; i++) + { + var difference = a.Digit(i) - b.Digit(i); + if (difference != 0) + { + return difference; + } + } + + return a.Count.CompareTo(b.Count); + } + + /// A number as 0.d1d2…dn × 10^Exponent, its digits without leading or trailing zeros. + private readonly ref struct Parts + { + private readonly ReadOnlySpan _integer; + private readonly ReadOnlySpan _fraction; + private readonly int _first; + + public Parts(ReadOnlySpan text) + { + var negative = text.Length > 0 && text[0] == '-'; + if (negative) + { + text = text[1..]; + } + + var e = text.IndexOfAny((byte)'e', (byte)'E'); + var mantissa = e < 0 ? text : text[..e]; + var dot = mantissa.IndexOf((byte)'.'); + _integer = dot < 0 ? mantissa : mantissa[..dot]; + _fraction = dot < 0 ? default : mantissa[(dot + 1)..]; + + var total = _integer.Length + _fraction.Length; + var first = 0; + while (first < total && At(_integer, _fraction, first) == '0') + { + first++; + } + + _first = first; + if (first == total) + { + return; // zero, either sign + } + + var last = total - 1; + while (At(_integer, _fraction, last) == '0') + { + last--; + } + + Count = last - first + 1; + Sign = negative ? -1 : 1; + Exponent = _integer.Length - first + (e < 0 ? 0 : ParseExponent(text[(e + 1)..])); + } + + public int Sign { get; } + + public int Count { get; } + + public long Exponent { get; } + + public int Digit(int i) => At(_integer, _fraction, _first + i); + + private static int At(ReadOnlySpan integer, ReadOnlySpan fraction, int i) => i < integer.Length ? integer[i] : fraction[i - integer.Length]; + + private static long ParseExponent(ReadOnlySpan text) + { + var negative = text[0] == '-'; + if (text[0] is (byte)'-' or (byte)'+') + { + text = text[1..]; + } + + long value = 0; + foreach (var digit in text) + { + value = Math.Min(value * 10 + (digit - '0'), MaxExponent); + } + + return negative ? -value : value; + } + } +} diff --git a/src/TermRest.Core/Json/JsonPathParser.cs b/src/TermRest.Core/Json/JsonPathParser.cs new file mode 100644 index 0000000..3989783 --- /dev/null +++ b/src/TermRest.Core/Json/JsonPathParser.cs @@ -0,0 +1,669 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace TermRest.Core.Json; + +/// Parses JSONPath (RFC 9535), checking that function calls are well-typed as the RFC requires. +internal sealed class JsonPathParser +{ + /// How deep filters, parentheses and function calls may nest: deeper ones would only run out of stack. + private const int MaxNesting = 64; + + /// The largest index, 2^53 - 1: I-JSON numbers are exact up to it. + private const long MaxIndex = 9_007_199_254_740_991; + + private static readonly string[] ComparisonOperators = ["==", "!=", "<=", ">=", "<", ">"]; + + private readonly string _text; + private int _pos; + private int _nesting; + + private JsonPathParser(string text) => _text = text; + + private enum OperandKind + { + Literal, + Query, + Function, + Logical, + } + + public static PathQuery Parse(string text) + { + var parser = new JsonPathParser(text); + if (!parser.Peek('$')) + { + throw parser.Error(text.Length == 0 ? "The query is empty: a query starts with $" : "A query starts with $ (the whole document)"); + } + + parser._pos++; + var query = parser.Segments(absolute: true); + if (parser._pos < text.Length) + { + throw parser.Unexpected("a segment such as .name, [0] or ..name"); + } + + return query; + } + + // ----- segments and selectors --------------------------------------------------------- + + private PathQuery Segments(bool absolute) + { + var segments = new List(); + while (true) + { + var start = _pos; + SkipBlanks(); + if (Peek('.') && Peek('.', 1)) + { + _pos += 2; + segments.Add(new DescendantSegment(Peek('[') ? Bracketed() : [DotSelector(descendant: true)])); + } + else if (Take('.')) + { + segments.Add(new ChildSegment([DotSelector(descendant: false)])); + } + else if (Peek('[')) + { + segments.Add(new ChildSegment(Bracketed())); + } + else + { + _pos = start; // blanks after a query belong to what follows it + return new PathQuery(absolute, [.. segments]); + } + } + } + + private Selector DotSelector(bool descendant) + { + if (Take('*')) + { + return WildcardSelector.Instance; + } + + var start = _pos; + if (!TakeNameChar(first: true)) + { + throw Unexpected(descendant ? "a name, * or [ after .." : "a name or * after ."); + } + + while (TakeNameChar(first: false)) + { + } + + return new NameSelector(_text[start.._pos]); + } + + /// A character of a name after a dot: a letter, _, a digit (not first) or any non-ASCII character. + private bool TakeNameChar(bool first) + { + if (_pos >= _text.Length) + { + return false; + } + + var c = _text[_pos]; + if (char.IsAsciiLetter(c) || c == '_' || (!first && char.IsAsciiDigit(c)) || (c >= 0x80 && !char.IsSurrogate(c))) + { + _pos++; + return true; + } + + if (char.IsHighSurrogate(c) && _pos + 1 < _text.Length && char.IsLowSurrogate(_text[_pos + 1])) + { + _pos += 2; + return true; + } + + return false; + } + + private Selector[] Bracketed() + { + _pos++; + var selectors = new List(); + while (true) + { + SkipBlanks(); + selectors.Add(Selector()); + SkipBlanks(); + if (Take(']')) + { + return [.. selectors]; + } + + if (!Take(',')) + { + throw Unexpected("',' or ']'"); + } + } + } + + private Selector Selector() + { + if (Take('*')) + { + return WildcardSelector.Instance; + } + + if (Peek('\'') || Peek('"')) + { + return new NameSelector(StringLiteral()); + } + + if (Take('?')) + { + Enter(); + SkipBlanks(); + var condition = Test(Or()); + Leave(); + return new FilterSelector(condition); + } + + var start = Integer(); + if (start is not null) + { + var end = _pos; + SkipBlanks(); + if (!Peek(':')) + { + _pos = end; + return new IndexSelector(start.Value); + } + } + else if (!Peek(':')) + { + throw Unexpected("a selector: 'name', *, an index, a slice (start:end:step) or a filter (?…)"); + } + + _pos++; + SkipBlanks(); + var stop = Integer(); + SkipBlanks(); + long step = 1; + if (Take(':')) + { + var beforeStep = _pos; + SkipBlanks(); + if (Integer() is { } value) + { + step = value; + } + else + { + _pos = beforeStep; + } + } + + return new SliceSelector(start, stop, step); + } + + /// An index or a slice bound: 0, or digits that do not start with 0, perhaps after a -. Null when none starts here. + private long? Integer() + { + var start = _pos; + var negative = Take('-'); + var digits = _pos; + while (_pos < _text.Length && char.IsAsciiDigit(_text[_pos])) + { + _pos++; + } + + if (_pos == digits) + { + if (negative) + { + throw Error("Expected a digit after -", digits); + } + + return null; + } + + var span = _text.AsSpan(digits, _pos - digits); + if (span[0] == '0' && (span.Length > 1 || negative)) + { + throw Error("An index does not start with 0, and is not -0", start); + } + + var value = span.Length > 16 ? long.MaxValue : long.Parse(span, NumberStyles.None, CultureInfo.InvariantCulture); + if (value > MaxIndex) + { + throw Error("The index is out of range: at most 9007199254740991, either way", start); + } + + return negative ? -value : value; + } + + private string StringLiteral() + { + var quote = _text[_pos]; + var start = _pos++; + var builder = new StringBuilder(); + while (true) + { + if (_pos >= _text.Length) + { + throw Error("The string has no closing quote", start); + } + + var c = _text[_pos]; + if (c == quote) + { + _pos++; + return builder.ToString(); + } + + if (c == '\\') + { + Escape(builder, quote, start); + } + else if (c < 0x20) + { + throw Error($"A string cannot hold {Describe(_pos)}: write it as an escape (\\n, \\t, \\u0001 …)"); + } + else if (char.IsHighSurrogate(c) && _pos + 1 < _text.Length && char.IsLowSurrogate(_text[_pos + 1])) + { + builder.Append(c).Append(_text[_pos + 1]); + _pos += 2; + } + else if (char.IsSurrogate(c)) + { + throw Error("A string cannot hold half of a character (a lone surrogate)"); + } + else + { + builder.Append(c); + _pos++; + } + } + } + + private void Escape(StringBuilder builder, char quote, int stringStart) + { + var at = _pos++; + if (_pos >= _text.Length) + { + throw Error("The string has no closing quote", stringStart); + } + + var c = _text[_pos++]; + switch (c) + { + case 'b': builder.Append('\b'); break; + case 'f': builder.Append('\f'); break; + case 'n': builder.Append('\n'); break; + case 'r': builder.Append('\r'); break; + case 't': builder.Append('\t'); break; + case '/': builder.Append('/'); break; + case '\\': builder.Append('\\'); break; + case 'u': + var unit = Hex4(at); + if (char.IsHighSurrogate(unit)) + { + if (!(Peek('\\') && Peek('u', 1))) + { + throw Error("\\u" + ((int)unit).ToString("X4", CultureInfo.InvariantCulture) + " is half of a character: the other half (\\uDC00 to \\uDFFF) must follow it", at); + } + + var lowAt = _pos; + _pos += 2; + var low = Hex4(lowAt); + if (!char.IsLowSurrogate(low)) + { + throw Error("\\u" + ((int)unit).ToString("X4", CultureInfo.InvariantCulture) + " is half of a character: the other half (\\uDC00 to \\uDFFF) must follow it", at); + } + + builder.Append(unit).Append(low); + } + else if (char.IsLowSurrogate(unit)) + { + throw Error("\\u" + ((int)unit).ToString("X4", CultureInfo.InvariantCulture) + " is the second half of a character, without the first", at); + } + else + { + builder.Append(unit); + } + + break; + default: + if (c != quote) + { + throw Error($"\\{c} is not an escape: write \\{quote}, \\\\, \\/, \\b, \\f, \\n, \\r, \\t or \\uXXXX", at); + } + + builder.Append(c); + break; + } + } + + /// The four hexadecimal digits of a \u escape (the position is after the u). + private char Hex4(int escapeStart) + { + if (_pos + 4 > _text.Length || !int.TryParse(_text.AsSpan(_pos, 4), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var value)) + { + throw Error("\\u takes four hexadecimal digits", escapeStart); + } + + _pos += 4; + return (char)value; + } + + // ----- filter expressions ------------------------------------------------------------- + + private Operand Or() + { + var left = And(); + while (TakeOperator("||")) + { + var right = And(); + left = new Operand(OperandKind.Logical, new OrExpression(Test(left), Test(right)), left.Position); + } + + return left; + } + + private Operand And() + { + var left = Basic(); + while (TakeOperator("&&")) + { + var right = Basic(); + left = new Operand(OperandKind.Logical, new AndExpression(Test(left), Test(right)), left.Position); + } + + return left; + } + + private Operand Basic() + { + var start = _pos; + if (Take('!')) + { + SkipBlanks(); + var negated = Peek('(') ? Parenthesized() : Comparable(); + return new Operand(OperandKind.Logical, new NotExpression(Test(negated)), start); + } + + if (Peek('(')) + { + return Parenthesized(); + } + + var left = Comparable(); + var end = _pos; + SkipBlanks(); + if (ComparisonOperator() is { } op) + { + SkipBlanks(); + var right = Comparable(); + return new Operand(OperandKind.Logical, new ComparisonExpression(Value(left), op, Value(right)), start); + } + + if (Peek('=') && !Peek('=', 1)) + { + throw Error("Compare with == (a single = is not an operator)"); + } + + _pos = end; + return left; + } + + private Operand Parenthesized() + { + var start = _pos++; + Enter(); + SkipBlanks(); + var inner = Or(); + SkipBlanks(); + if (!Take(')')) + { + throw Unexpected("')'"); + } + + Leave(); + return new Operand(OperandKind.Logical, Test(inner), start); + } + + private ComparisonOperator? ComparisonOperator() + { + for (var i = 0; i < ComparisonOperators.Length; i++) + { + if (_text.AsSpan(_pos).StartsWith(ComparisonOperators[i], StringComparison.Ordinal)) + { + _pos += ComparisonOperators[i].Length; + return (ComparisonOperator)i; + } + } + + return null; + } + + /// A literal, a query or a function call. + private Operand Comparable() + { + var start = _pos; + var c = _pos < _text.Length ? _text[_pos] : '\0'; + switch (c) + { + case '@' or '$': + _pos++; + return new Operand(OperandKind.Query, Segments(absolute: c == '$'), start); + case '\'' or '"': + return new Operand(OperandKind.Literal, new LiteralExpression(PathValue.Of(StringLiteral())), start); + case '-' or (>= '0' and <= '9'): + return new Operand(OperandKind.Literal, NumberLiteral(), start); + case >= 'a' and <= 'z': + while (_pos < _text.Length && (char.IsAsciiLetterLower(_text[_pos]) || char.IsAsciiDigit(_text[_pos]) || _text[_pos] == '_')) + { + _pos++; + } + + var name = _text[start.._pos]; + if (Peek('(')) + { + return new Operand(OperandKind.Function, Function(name, start), start); + } + + return name is "true" or "false" or "null" + ? new Operand(OperandKind.Literal, new LiteralExpression(PathValue.Of(JsonElement.Parse(name))), start) + : throw Error($"Unknown name {name}: call a function as {name}(…), and quote a string", start); + default: + throw Unexpected("a value, a query (@… or $…) or a function"); + } + } + + /// A number as JSON writes it: -0, 1, 1.5, 1e-3; not 01, 1. or .5. + private LiteralExpression NumberLiteral() + { + var start = _pos; + Take('-'); + if (!Take('0')) + { + if (!(_pos < _text.Length && _text[_pos] is >= '1' and <= '9')) + { + throw Error("Expected a digit"); + } + + SkipDigits(); + } + + if (Take('.')) + { + RequireDigits("Expected a digit after the decimal point"); + } + + if (Take('e') || Take('E')) + { + _ = Take('+') || Take('-'); + RequireDigits("Expected a digit in the exponent"); + } + + return new LiteralExpression(PathValue.Of(JsonElement.Parse(_text[start.._pos]))); + } + + private FunctionCall Function(string name, int start) + { + var signature = FunctionCall.Find(name) + ?? throw Error($"Unknown function {name}(): the functions are length, count, match, search and value", start); + _pos++; + Enter(); + SkipBlanks(); + var operands = new List(); + if (!Peek(')')) + { + while (true) + { + operands.Add(Or()); + SkipBlanks(); + if (!Take(',')) + { + break; + } + + SkipBlanks(); + } + } + + if (!Take(')')) + { + throw Unexpected("',' or ')'"); + } + + Leave(); + var parameters = signature.Parameters; + if (operands.Count != parameters.Length) + { + throw Error($"{name}() takes {parameters.Length} argument{(parameters.Length == 1 ? "" : "s")}, not {operands.Count}", start); + } + + var arguments = new object[operands.Count]; + for (var i = 0; i < operands.Count; i++) + { + arguments[i] = parameters[i] switch + { + PathType.Value => Value(operands[i]), + PathType.Nodes => operands[i].Kind == OperandKind.Query + ? operands[i].Node + : throw Error($"{name}() takes a query, such as @.items or $..id", operands[i].Position), + _ => Test(operands[i]), + }; + } + + return new FunctionCall(name, signature.Function, signature.Result, arguments); + } + + /// An operand used as a value: a literal, a query that selects at most one value, or length, count or value. + private ValueExpression Value(Operand operand) => operand.Kind switch + { + OperandKind.Literal => (LiteralExpression)operand.Node, + OperandKind.Query when ((PathQuery)operand.Node).IsSingular => new QueryValueExpression((PathQuery)operand.Node), + OperandKind.Query => throw Error( + "This query can select more than one value, where one is expected: use names and indexes only (@.a[0]), or count() or value()", + operand.Position), + OperandKind.Function when ((FunctionCall)operand.Node).Result == PathType.Value => new FunctionValueExpression((FunctionCall)operand.Node), + OperandKind.Function => throw Error($"{((FunctionCall)operand.Node).Name}() is true or false, not a value: use it as a test", operand.Position), + _ => throw Error("A test (==, &&, ! …) is not a value: it cannot be compared", operand.Position), + }; + + /// An operand used as a test: a query (whether it selects anything), a comparison, or match or search. + private LogicalExpression Test(Operand operand) => operand.Kind switch + { + OperandKind.Logical => (LogicalExpression)operand.Node, + OperandKind.Query => new ExistsExpression((PathQuery)operand.Node), + OperandKind.Function when ((FunctionCall)operand.Node).Result != PathType.Value => new FunctionTestExpression((FunctionCall)operand.Node), + OperandKind.Function => throw Error($"{((FunctionCall)operand.Node).Name}() is a value, not a test: compare it, e.g. {((FunctionCall)operand.Node).Name}(…) > 0", operand.Position), + _ => throw Error("A value is not a test: compare it, e.g. @.name == 'x'", operand.Position), + }; + + // ----- characters --------------------------------------------------------------------- + + private bool Peek(char c, int offset = 0) => _pos + offset < _text.Length && _text[_pos + offset] == c; + + private bool Take(char c) + { + if (!Peek(c)) + { + return false; + } + + _pos++; + return true; + } + + private bool TakeOperator(string op) + { + var start = _pos; + SkipBlanks(); + if (_text.AsSpan(_pos).StartsWith(op, StringComparison.Ordinal)) + { + _pos += op.Length; + SkipBlanks(); + return true; + } + + _pos = start; + return false; + } + + private void SkipBlanks() + { + while (_pos < _text.Length && _text[_pos] is ' ' or '\t' or '\n' or '\r') + { + _pos++; + } + } + + private void SkipDigits() + { + while (_pos < _text.Length && char.IsAsciiDigit(_text[_pos])) + { + _pos++; + } + } + + private void RequireDigits(string message) + { + if (!(_pos < _text.Length && char.IsAsciiDigit(_text[_pos]))) + { + throw Error(message); + } + + SkipDigits(); + } + + private void Enter() + { + if (++_nesting > MaxNesting) + { + throw Error($"The query nests filters, parentheses and functions more than {MaxNesting} deep"); + } + } + + private void Leave() => _nesting--; + + private JsonPathException Unexpected(string expected) => + _pos >= _text.Length ? Error($"The query ends where {expected} is expected") : Error($"Unexpected {Describe(_pos)}: expected {expected}"); + + private JsonPathException Error(string message, int? at = null) + { + var position = at ?? _pos; + return new JsonPathException($"{message} (character {position + 1}).", position); + } + + private string Describe(int at) => _text[at] switch + { + ' ' => "space", + '\t' => "tab", + '\n' or '\r' => "line break", + var c when char.IsControl(c) => $"control character U+{(int)c:X4}", + var c when char.IsHighSurrogate(c) && at + 1 < _text.Length && char.IsLowSurrogate(_text[at + 1]) => $"'{_text.Substring(at, 2)}'", + var c when char.IsSurrogate(c) => $"half of a character (U+{(int)c:X4})", + var c => $"'{c}'", + }; + + /// A part of a filter expression, whose use (a value, a query or a test) is checked where it is used. + private readonly record struct Operand(OperandKind Kind, object Node, int Position); +} diff --git a/src/TermRest.Tui/MainWindow.cs b/src/TermRest.Tui/MainWindow.cs index b484f7e..1c90221 100644 --- a/src/TermRest.Tui/MainWindow.cs +++ b/src/TermRest.Tui/MainWindow.cs @@ -305,6 +305,8 @@ internal async Task SendAndShowAsync(CancellationToken cancellationToken = defau new MenuItem("_Import from cURL…", "", ShowCurlImport), new MenuItem("_History", Key.F9, ToggleHistory), new MenuItem("Focus _URL bar", Key.L.WithCtrl, () => _editor.FocusUrl()), + new MenuItem("Find in res_ponse", Key.F.WithCtrl, () => _response.OpenFind()), + new MenuItem("Filter response with _JSONPath", "", () => _response.ToggleFilter()), new Line(), new MenuItem("Collection or folder scrip_ts…", "", () => EditScripts(TargetFolder())), ]), @@ -1958,6 +1960,8 @@ private static readonly (string Keys, string Action)[] Shortcuts = ("F10", "Menu"), ("Shift+F10", "Context menu"), ("Ctrl+L", "Focus the URL bar"), + ("Ctrl+F", "Find in the response"), + ("F3, Shift+F3", "Next / previous match"), ("Ctrl+Q", "Quit"), ]; @@ -2172,6 +2176,19 @@ protected override bool OnKeyDown(Key key) return true; } + // Text fields and editors leave Ctrl+F (see TuiApp.ConfigureKeyBindings) and F3 to the window. + if (key == Key.F.WithCtrl) + { + _response.OpenFind(); + return true; + } + + if (key == Key.F3 || key == Key.F3.WithShift) + { + _response.FindNext(backwards: key.IsShift); + return true; + } + if (key == Key.F12) { ToggleRecording(); diff --git a/src/TermRest.Tui/Syntax/JsonLexer.cs b/src/TermRest.Tui/Syntax/JsonLexer.cs new file mode 100644 index 0000000..e922860 --- /dev/null +++ b/src/TermRest.Tui/Syntax/JsonLexer.cs @@ -0,0 +1,93 @@ +using System.Collections.Frozen; + +namespace TermRest.Tui.Syntax; + +/// +/// JSON (and JSON with comments, as request bodies may have): keys as variables, other strings, numbers, true, false and +/// null. A string followed by a colon on its line is a key. +/// +internal sealed class JsonLexer : SyntaxLexer +{ + public static readonly JsonLexer Instance = new(); + + private static readonly FrozenSet.AlternateLookup> Constants = Words("true false null"); + + public override LexState Lex(ReadOnlySpan line, Span kinds, LexState state) + { + var i = state.Mode == LexMode.Comment ? BlockComment(line, kinds, 0, "*/", ref state) : 0; + while (i < line.Length) + { + var c = line[i]; + var next = At(line, i + 1); + if (c == '/' && next == '/') + { + kinds[i..].Fill(SyntaxKind.Comment); + break; + } + + if (c == '/' && next == '*') + { + kinds[i] = kinds[i + 1] = SyntaxKind.Comment; + i = BlockComment(line, kinds, i + 2, "*/", ref state); + continue; + } + + if (c == '"') + { + // A string ends on its line (JSON writes a line break in one as \n). + var end = StringEnd(line, i + 1); + var after = end; + while (after < line.Length && line[after] is ' ' or '\t') + { + after++; + } + + kinds[i..end].Fill(At(line, after) == ':' ? SyntaxKind.Variable : SyntaxKind.String); + i = end; + continue; + } + + if ((c == '-' && char.IsAsciiDigit(next) && !(i > 0 && IsWordPart(line[i - 1]))) || IsNumberStart(line, i)) + { + var end = NumberEnd(line, c == '-' ? i + 1 : i); + kinds[i..end].Fill(SyntaxKind.Number); + i = end; + continue; + } + + if (IsWordStart(c)) + { + var end = WordEnd(line, i); + if (Constants.Contains(line[i..end])) + { + kinds[i..end].Fill(SyntaxKind.Keyword); + } + + i = end; + continue; + } + + i++; + } + + return state; + } + + /// The index after the closing quote of the string whose text starts at , or the line's end. + private static int StringEnd(ReadOnlySpan line, int i) + { + for (; i < line.Length; i++) + { + if (line[i] == '\\') + { + i++; + } + else if (line[i] == '"') + { + return i + 1; + } + } + + return line.Length; + } +} diff --git a/src/TermRest.Tui/Syntax/MarkupLexer.cs b/src/TermRest.Tui/Syntax/MarkupLexer.cs new file mode 100644 index 0000000..edcb204 --- /dev/null +++ b/src/TermRest.Tui/Syntax/MarkupLexer.cs @@ -0,0 +1,281 @@ +namespace TermRest.Tui.Syntax; + +/// +/// XML and HTML: tag names as keywords, attribute names as variables, their values as strings, comments, entities +/// (&amp;) as numbers, and the declarations (<?xml …?>, <!DOCTYPE …>, CDATA sections) as types. In HTML, +/// the content of script and style elements is left plain. +/// +/// +/// What a line leaves open, in : a tag (Code, Depth 1), an attribute value in one (String, its +/// quote, Depth 1), the content of a script or style element (Code, Depth 2), a comment (Comment, Quote '-') or a CDATA +/// section (Comment, Quote ']'). In a tag and its values, Quotes says which raw text element it starts: 1 script, 2 style. +/// +internal sealed class MarkupLexer : SyntaxLexer +{ + public static readonly MarkupLexer Xml = new(html: false); + + public static readonly MarkupLexer Html = new(html: true); + + private const byte InTag = 1; + private const byte InRawText = 2; + + private static readonly string[] RawTextElements = ["", "script", "style"]; + + private static readonly string[] RawTextEnds = ["", " _html = html; + + public override LexState Lex(ReadOnlySpan line, Span kinds, LexState state) + { + var i = 0; + switch (state) + { + case { Mode: LexMode.Comment, Quote: '-' }: + i = Until(line, kinds, 0, "-->", SyntaxKind.Comment, SyntaxKind.Comment, ref state); + break; + case { Mode: LexMode.Comment }: + i = Until(line, kinds, 0, "]]>", SyntaxKind.String, SyntaxKind.Type, ref state); + break; + case { Mode: LexMode.String }: + i = AttributeValue(line, kinds, 0, ref state); + break; + case { Depth: InRawText }: + i = RawText(line, 0, ref state); + break; + } + + while (i < line.Length) + { + if (state.Mode != LexMode.Code) + { + break; // a comment, CDATA section or value goes on past the line + } + + if (state.Depth == InTag) + { + i = TagBody(line, kinds, i, ref state); + continue; + } + + if (state.Depth == InRawText) + { + i = RawText(line, i, ref state); + continue; + } + + var c = line[i]; + if (c == '<') + { + i = TagStart(line, kinds, i, ref state); + continue; + } + + if (c == '&' && EntityEnd(line, i) is var entityEnd and > 0) + { + kinds[i..entityEnd].Fill(SyntaxKind.Number); + i = entityEnd; + continue; + } + + i++; + } + + return state; + } + + /// What starts with a < at : a tag, a comment, a declaration, or text (a < alone). + private int TagStart(ReadOnlySpan line, Span kinds, int i, ref LexState state) + { + var rest = line[i..]; + if (rest.StartsWith("", SyntaxKind.Comment, SyntaxKind.Comment, ref state); + } + + if (rest.StartsWith("", SyntaxKind.String, SyntaxKind.Type, ref state); + } + + var next = At(line, i + 1); + if (next is '!' or '?') + { + // , : the rest is read as attributes. + var end = NameEnd(line, i + 2); + kinds[i..end].Fill(SyntaxKind.Type); + state = new LexState(LexMode.Code, Depth: InTag); + return end; + } + + var closing = next == '/'; + var nameStart = closing ? i + 2 : i + 1; + if (!IsNameStart(At(line, nameStart))) + { + return i + 1; // a < in text + } + + var nameEnd = NameEnd(line, nameStart); + kinds[nameStart..nameEnd].Fill(SyntaxKind.Keyword); + byte raw = 0; + for (var element = 1; _html && !closing && element < RawTextElements.Length; element++) + { + if (line[nameStart..nameEnd].Equals(RawTextElements[element], StringComparison.OrdinalIgnoreCase)) + { + raw = (byte)element; + } + } + + state = new LexState(LexMode.Code, Quotes: raw, Depth: InTag); + return nameEnd; + } + + /// The attributes of a tag from , up to its end (or the line's). + private static int TagBody(ReadOnlySpan line, Span kinds, int i, ref LexState state) + { + var value = false; // after =: an unquoted value (HTML) + while (i < line.Length) + { + var c = line[i]; + var next = At(line, i + 1); + if (c == '>' || (c is '/' or '?' && next == '>')) + { + // The end of the tag; after a script or style start tag, the element's content. + var raw = c == '>' ? state.Quotes : (byte)0; + state = raw > 0 ? new LexState(LexMode.Code, Quotes: raw, Depth: InRawText) : LexState.Code; + return c == '>' ? i + 1 : i + 2; + } + + if (c == '<') + { + state = LexState.Code; // a tag left open: what follows is another one + return i; + } + + if (c is '"' or '\'') + { + kinds[i] = SyntaxKind.String; + state = state with { Mode = LexMode.String, Quote = c }; + return AttributeValue(line, kinds, i + 1, ref state); + } + + if (char.IsWhiteSpace(c) || c == '=') + { + value = c == '=' || (value && char.IsWhiteSpace(c)); + i++; + continue; + } + + var end = i + 1; + while (end < line.Length && !(char.IsWhiteSpace(line[end]) || line[end] is '"' or '\'' or '=' or '<' or '>' || (line[end] is '/' or '?' && At(line, end + 1) == '>'))) + { + end++; + } + + kinds[i..end].Fill(value ? SyntaxKind.String : SyntaxKind.Variable); + value = false; + i = end; + } + + return i; + } + + /// A quoted attribute value from to its closing quote (it may go on over lines). + private static int AttributeValue(ReadOnlySpan line, Span kinds, int i, ref LexState state) + { + var close = line[i..].IndexOf(state.Quote); + var end = close < 0 ? line.Length : i + close + 1; + kinds[i..end].Fill(SyntaxKind.String); + if (close >= 0) + { + state = state with { Mode = LexMode.Code, Quote = '\0' }; + } + + return end; + } + + /// The content of a script or style element from , up to its end tag (or the line's end). + private static int RawText(ReadOnlySpan line, int i, ref LexState state) + { + var found = line[i..].IndexOf(RawTextEnds[state.Quotes], StringComparison.OrdinalIgnoreCase); + if (found < 0) + { + return line.Length; + } + + state = LexState.Code; + return i + found; + } + + /// + /// Colors from up to , which gets + /// ; returns the index after it, or the line's end ( unchanged). + /// + private static int Until(ReadOnlySpan line, Span kinds, int i, string close, SyntaxKind kind, SyntaxKind closeKind, ref LexState state) + { + var found = line[i..].IndexOf(close.AsSpan()); + if (found < 0) + { + kinds[i..].Fill(kind); + return line.Length; + } + + kinds[i..(i + found)].Fill(kind); + kinds[(i + found)..(i + found + close.Length)].Fill(closeKind); + state = LexState.Code; + return i + found + close.Length; + } + + /// The end of an entity at (&amp; &#38; &#x26;), or -1. + private static int EntityEnd(ReadOnlySpan line, int i) + { + var j = i + 1; + if (At(line, j) == '#') + { + j++; + var hex = At(line, j) is 'x' or 'X'; + if (hex) + { + j++; + } + + var digits = j; + while (j < line.Length && (hex ? char.IsAsciiHexDigit(line[j]) : char.IsAsciiDigit(line[j]))) + { + j++; + } + + return j > digits && At(line, j) == ';' ? j + 1 : -1; + } + + if (!char.IsAsciiLetter(At(line, j))) + { + return -1; + } + + while (j < line.Length && char.IsAsciiLetterOrDigit(line[j])) + { + j++; + } + + return At(line, j) == ';' ? j + 1 : -1; + } + + private static bool IsNameStart(char c) => char.IsLetter(c) || c is '_' or ':'; + + /// The end of the tag or declaration name at : letters, digits and _ : . - + private static int NameEnd(ReadOnlySpan line, int i) + { + while (i < line.Length && (char.IsLetterOrDigit(line[i]) || line[i] is '_' or ':' or '.' or '-')) + { + i++; + } + + return i; + } +} diff --git a/src/TermRest.Tui/Syntax/SyntaxLexer.cs b/src/TermRest.Tui/Syntax/SyntaxLexer.cs index 478114a..0f006c2 100644 --- a/src/TermRest.Tui/Syntax/SyntaxLexer.cs +++ b/src/TermRest.Tui/Syntax/SyntaxLexer.cs @@ -76,13 +76,19 @@ internal abstract class SyntaxLexer [ThreadStatic] private static int _nesting; - /// The lexer of a script language (), or null for plain text. + /// + /// The lexer of a language: a script language (), or a body's (json, xml, html, javascript); + /// null for plain text. + /// public static SyntaxLexer? For(string? language) => language switch { ScriptLanguage.Python => PythonLexer.Instance, ScriptLanguage.JavaScript => JavaScriptLexer.Instance, ScriptLanguage.CSharp => CSharpLexer.Instance, ScriptLanguage.PowerShell => PowerShellLexer.Instance, + "json" => JsonLexer.Instance, + "xml" => MarkupLexer.Xml, + "html" => MarkupLexer.Html, _ => null, }; diff --git a/src/TermRest.Tui/TuiApp.cs b/src/TermRest.Tui/TuiApp.cs index 547e6da..b15a2df 100644 --- a/src/TermRest.Tui/TuiApp.cs +++ b/src/TermRest.Tui/TuiApp.cs @@ -1,6 +1,7 @@ using System.Text; using Terminal.Gui.App; using Terminal.Gui.Input; +using Terminal.Gui.Views; using TermRest.Core.History; using TermRest.Core.Workspace; using TermRest.Tui.Theming; @@ -141,6 +142,13 @@ internal static void ConfigureKeyBindings() { Application.RemoveDefaultKeyBinding(Command.Refresh); } + + // Ctrl+F finds in the response: not the cursor moving right (Emacs), which is all Command.Right adds to the arrow key + // in Terminal.Gui 2.5's text fields and editors. + TextField.DefaultKeyBindings?.Remove(Command.Right); +#pragma warning disable CS0618 // TextView: the editor TextArea derives from + TextView.DefaultKeyBindings?.Remove(Command.Right); +#pragma warning restore CS0618 } /// Creates the main window without running it (used by tests). diff --git a/src/TermRest.Tui/Views/BodyEditor.cs b/src/TermRest.Tui/Views/BodyEditor.cs index 48d7e25..e9f3877 100644 --- a/src/TermRest.Tui/Views/BodyEditor.cs +++ b/src/TermRest.Tui/Views/BodyEditor.cs @@ -80,6 +80,7 @@ public BodyEditor() _language = new OptionSelector { X = 0, Y = 1, Orientation = Orientation.Horizontal, Labels = LanguageLabels, Value = 0 }; _language.ValueChanged += (_, e) => { + ColorRaw(); if (!_loading && e.NewValue is int index) { _body.RawLanguage = Languages[index]; @@ -90,6 +91,7 @@ public BodyEditor() _beautify.Accepted += (_, _) => Beautify(); _raw = new TextArea { X = 0, Y = 2, Width = Dim.Fill(), Height = Dim.Fill() }; + ColorRaw(); _raw.UserEdited += (_, text) => { _body.Raw = text; @@ -160,7 +162,7 @@ public BodyEditor() _body.GraphQLQuery = text; RaiseChanged(); }; - _graphQLVariables = new TextArea { X = Pos.Right(_graphQLQuery) + 1, Y = 1, Width = Dim.Fill(), Height = Dim.Fill() }; + _graphQLVariables = new TextArea { X = Pos.Right(_graphQLQuery) + 1, Y = 1, Width = Dim.Fill(), Height = Dim.Fill(), SyntaxLanguage = "json" }; _graphQLVariables.UserEdited += (_, text) => { _body.GraphQLVariables = text; @@ -199,6 +201,12 @@ public bool Recording /// What the file panel says about the chosen file (for tests). internal string FileStatus => _fileStatus.Text; + /// The language the raw body is colored in (for tests). + internal string? RawSyntax => _raw.SyntaxLanguage; + + /// Colors the raw body in the language chosen for it (none for Text). + private void ColorRaw() => _raw.SyntaxLanguage = _language.Value is int index && Languages[index] != "text" ? Languages[index] : null; + public void Load(RequestBody body) { _loading = true; diff --git a/src/TermRest.Tui/Views/RequestEditor.cs b/src/TermRest.Tui/Views/RequestEditor.cs index d20e6cb..f8c7958 100644 --- a/src/TermRest.Tui/Views/RequestEditor.cs +++ b/src/TermRest.Tui/Views/RequestEditor.cs @@ -212,6 +212,9 @@ public Func? FilesFolder /// What the Body tab says about the body file (for tests). internal string BodyFileStatus => _body.FileStatus; + /// The language the raw body is colored in (for tests). + internal string? RawBodySyntax => _body.RawSyntax; + /// The Scripts tab (for tests). internal ScriptsEditor ScriptsTab => _scripts; diff --git a/src/TermRest.Tui/Views/ResponseView.cs b/src/TermRest.Tui/Views/ResponseView.cs index ef18d11..8fe7977 100644 --- a/src/TermRest.Tui/Views/ResponseView.cs +++ b/src/TermRest.Tui/Views/ResponseView.cs @@ -5,12 +5,16 @@ using Terminal.Gui.ViewBase; using Terminal.Gui.Views; using TermRest.Core.Http; +using TermRest.Core.Json; using TermRest.Tui.Dialogs; using TermRest.Tui.Theming; namespace TermRest.Tui.Views; -/// Response pane: status line plus Body / Headers / Timeline / TLS tabs. +/// +/// Response pane: status line plus Body / Headers / Timeline / TLS / Scripts tabs. The body is colored as its type says, +/// can be filtered with JSONPath, and Find (Ctrl+F) looks for text in the tab shown. +/// internal sealed class ResponseView : View { /// @@ -22,6 +26,9 @@ internal sealed class ResponseView : View /// Bodies of this many bytes or more are formatted (decoded, pretty printed) in the background. private const int BackgroundSize = 1_048_576; + /// A filter's values are written up to this many bytes (of UTF-8): the body tab shows their start, Copy all of them. + internal const long MaxFilteredBytes = 16 * 1024 * 1024; + /// The Timeline tab shows this many characters of a request's body at most. private const int TimelineBodyLength = 4000; @@ -43,10 +50,21 @@ internal sealed class ResponseView : View private readonly TextArea _timeline; private readonly TextArea _tls; private readonly TextArea _scripts; + private readonly View _filterRow; + private readonly TextField _filterField; + private readonly Label _filterStatus; + private readonly View _findBar; + private readonly TextField _findField; + private readonly CheckBox _matchCase; + private readonly Label _findCount; private HttpExchange? _exchange; private bool _fromHistory; // the exchange shown came from the history: its body as the history keeps it private bool _prettyOn = true; private int _bodyVersion; // a body formatted in the background is shown only if no other body replaced it meanwhile + private CancellationTokenSource? _rendering; // the body formatted or filtered in the background, stopped when replaced + private JsonPath? _filter; // the query the body is filtered with, kept for the responses that follow + private bool _filterInvalid; // the query typed is not valid JSONPath: the filter row says why + private TextArea? _findTarget; // the text of the tab that Find looks in private bool _disposed; public ResponseView() @@ -77,8 +95,20 @@ public ResponseView() copy.Accepted += (_, _) => CopyBody(); var save = new Button { Text = "Save as…", X = Pos.Right(copy) + 2, Y = 0, NoDecorations = true, ShadowStyle = null }; save.Accepted += (_, _) => SaveBody(); + var filter = new Button { Text = "Filter", X = Pos.Right(save) + 2, Y = 0, NoDecorations = true, ShadowStyle = null }; + filter.Accepted += (_, _) => ToggleFilter(); _body = new TextArea { X = 0, Y = 1, Width = Dim.Fill(), Height = Dim.Fill(), ReadOnly = true }; - _bodyTab.Add(_pretty, _wrap, copy, save, _body); + + // JSONPath: the body shows the values the query selects, as a JSON array. + _filterRow = new View { X = 0, Y = 1, Width = Dim.Fill(), Height = 1, CanFocus = true, Visible = false }; + var filterLabel = new Label { Text = "JSONPath:", X = 0, Y = 0 }; + _filterField = new TextField { X = Pos.Right(filterLabel) + 1, Y = 0, Width = Dim.Percent(45) }; + _filterField.TextChanged += (_, _) => FilterChanged(); + _filterStatus = new Label { HotKeySpecifier = Ui.NoHotKey, X = Pos.Right(_filterField) + 1, Y = 0, Width = Dim.Fill(3), Text = "" }; + var closeFilter = new Button { Text = "✕", X = Pos.AnchorEnd(2), Y = 0, NoDecorations = true, ShadowStyle = null }; + closeFilter.Accepted += (_, _) => CloseFilter(); + _filterRow.Add(filterLabel, _filterField, _filterStatus, closeFilter); + _bodyTab.Add(_pretty, _wrap, copy, save, filter, _filterRow, _body); var headersTab = new View { Title = "Headers", Width = Dim.Fill(), Height = Dim.Fill(), CanFocus = true }; _headers = new TableView { Width = Dim.Fill(), Height = Dim.Fill(), FullRowSelect = true }; @@ -107,7 +137,51 @@ public ResponseView() scriptsTab.Add(_scripts); _tabs.AddTabs(_bodyTab, headersTab, timelineTab, tlsTab, scriptsTab); - Add(_status, _tabs); + + // Find (Ctrl+F): in the text of the tab shown. + _findBar = new View { X = 0, Y = Pos.AnchorEnd(1), Width = Dim.Fill(), Height = 1, CanFocus = true, Visible = false }; + var findLabel = new Label { Text = "Find:", X = 0, Y = 0 }; + _findField = new TextField { X = Pos.Right(findLabel) + 1, Y = 0, Width = Dim.Fill(38) }; + _findField.TextChanged += (_, _) => FindChanged(); + var previous = new Button { Text = "▲", X = Pos.Right(_findField) + 1, Y = 0, NoDecorations = true, ShadowStyle = null }; + previous.Accepted += (_, _) => FindNext(backwards: true); + var next = new Button { Text = "▼", X = Pos.Right(previous) + 1, Y = 0, NoDecorations = true, ShadowStyle = null }; + next.Accepted += (_, _) => FindNext(); + _matchCase = new CheckBox { Text = "Match case", X = Pos.Right(next) + 2, Y = 0 }; + _matchCase.ValueChanged += (_, _) => FindChanged(); + _findCount = new Label { HotKeySpecifier = Ui.NoHotKey, X = Pos.Right(_matchCase) + 2, Y = 0, Width = Dim.Fill(3), Text = "" }; + var closeFind = new Button { Text = "✕", X = Pos.AnchorEnd(2), Y = 0, NoDecorations = true, ShadowStyle = null }; + closeFind.Accepted += (_, _) => CloseFind(); + _findBar.Add(findLabel, _findField, previous, next, _matchCase, _findCount, closeFind); + + // Enter and Shift+Enter go to the next and previous match (Esc closes the bar: see OnKeyDown). + _findField.KeyDown += (_, key) => + { + if (key == Key.Enter || key == Key.Enter.WithShift) + { + FindNext(backwards: key.IsShift); + key.Handled = true; + } + }; + _tabs.ValueChanged += (_, _) => + { + if (_findBar.Visible) + { + FindIn(SearchedArea()); + } + }; + foreach (var area in new[] { _body, _timeline, _tls, _scripts }) + { + area.MatchesChanged += (sender, _) => + { + if (sender == _findTarget) + { + ShowFindCount(); + } + }; + } + + Add(_status, _tabs, _findBar); SetHeaders([]); _scripts.SetText(NoScripts); } @@ -139,6 +213,15 @@ public ResponseView() /// The TLS tab's text (for tests). internal string TlsText => _tls.GetText(); + /// The language the Body tab colors its text in (for tests). + internal string? BodySyntax => _body.SyntaxLanguage; + + /// What the filter row says: how many values the query selects, or why it can't (for tests). + internal string FilterStatus => _filterStatus.Text; + + /// What the find bar says: which match is selected, of how many (for tests). + internal string FindStatus => _findCount.Text; + public void Clear() { _exchange = null; @@ -146,6 +229,7 @@ public void Clear() _status.Text = "No response yet. Press F5 (or Enter in the URL bar) to send."; _status.SchemeName = null; ShowBody(""); + SetFilterStatus("", error: false); _timeline.SetText(""); _tls.SetText(""); _scripts.SetText(NoScripts); @@ -184,6 +268,7 @@ public void ShowExchange(HttpExchange exchange, bool fromHistory = false) // When a script stopped the request, its traceback is what the user needs to see. ShowBody(exchange.Cancelled ? "" : scripts?.Error is not null ? ShownScripts($"{exchange.ErrorMessage}\n\n{scripts.Describe()}") : exchange.ErrorMessage ?? ""); + SetFilterStatus(_filter is null ? "" : "No response to filter.", error: false); SetHeaders([]); } else @@ -218,12 +303,15 @@ public void ShowExchange(HttpExchange exchange, bool fromHistory = false) } /// - /// Shows the response body, pretty or not, formatted from the response each time (as Copy is): the editor's text has - /// its own line breaks (a lone CR shows as one) and only the start of a long body, and keeping the whole text as well - /// would take memory. A large body is formatted in the background, and shown if nothing replaced it meanwhile. + /// Shows the response body, pretty or not (or the values the filter selects in it), formatted from the response each time + /// (as Copy is): the editor's text has its own line breaks (a lone CR shows as one) and only the start of a long body, + /// and keeping the whole text as well would take memory. A large body is formatted in the background, and shown if + /// nothing replaced it meanwhile. /// private void RenderBody() { + _rendering?.Cancel(); + _rendering = null; if (_exchange?.Response is not { } response) { return; @@ -233,23 +321,38 @@ private void RenderBody() if (BodyNotKept) { ShowBody("(response body not kept in the history)"); + SetFilterStatus(_filter is null ? "" : "✗ The history kept no copy of this response body.", error: true); return; } - var pretty = _prettyOn; + var (pretty, filter) = (_prettyOn, _filter); if (App is not { } app || response.Body.Length < BackgroundSize) { - ShowBody(Shown(response, pretty)); + Show(Render(response, pretty, filter, CancellationToken.None)); return; } - var version = ShowBody("Formatting…"); - _ = Task.Run(() => Shown(response, pretty)).ContinueWith( + var rendering = _rendering = new CancellationTokenSource(); + var version = ShowBody(filter is null ? "Formatting…" : "Filtering…"); + _ = Task.Run(() => Render(response, pretty, filter, rendering.Token), rendering.Token).ContinueWith( task => app.AddTimeout(TimeSpan.Zero, () => { + if (_rendering == rendering) + { + _rendering = null; + } + + rendering.Dispose(); if (version == _bodyVersion && !_disposed) { - _body.SetText(task.IsCompletedSuccessfully ? task.Result : $"✗ {task.Exception?.GetBaseException().Message}"); + if (task.IsCompletedSuccessfully) + { + Show(task.Result); + } + else if (!task.IsCanceled) + { + ShowBody($"✗ {task.Exception?.GetBaseException().Message}"); + } } return false; @@ -257,17 +360,88 @@ private void RenderBody() TaskScheduler.Default); } + /// What the body tab shows of a response, the language it is colored in, and what the filter row says. + internal readonly record struct RenderedBody(string Text, string? Language, string FilterStatus = "", bool FilterFailed = false); + + /// + /// The body as the body tab shows it (see ), or, with a filter, the values it selects (as much of them + /// as allows). A body the filter can't apply to is shown as it is, and the filter row says why. + /// + internal static RenderedBody Render(ResponseSnapshot response, bool pretty, JsonPath? filter, CancellationToken cancellationToken) + { + if (filter is not null) + { + try + { + var filtered = BodyFilter.Apply(filter, response.Body, response.ContentType, pretty, MaxFilteredBytes, cancellationToken); + var text = filtered.Text.Length <= MaxShownLength + ? filtered.Text + : string.Concat(Start(filtered.Text), $"\n\n… showing the first {HttpExchange.FormatSize(MaxShownLength)} of {HttpExchange.FormatSize(filtered.Text.Length)}: Copy gives them all"); + return new RenderedBody(text, "json", Describe(filtered)); + } + catch (JsonPathException ex) + { + var shown = Shown(response, pretty); + var cut = response.BodyTruncated ? " The body was cut at the maximum response size (Tools > Settings)." : ""; + return new RenderedBody(shown, SyntaxOf(response, shown), $"✗ {ex.Message}{cut}", FilterFailed: true); + } + } + + var body = Shown(response, pretty); + return new RenderedBody(body, SyntaxOf(response, body)); + } + + /// How many values a filter selected, and how many of them it wrote. + private static string Describe(FilteredBody filtered) + { + var count = filtered.Count.ToString("N0", CultureInfo.InvariantCulture); + return filtered.Count == 0 ? "No values" + : filtered.Shown < filtered.Count ? $"{count} values: the first {filtered.Shown.ToString("N0", CultureInfo.InvariantCulture)}, {HttpExchange.FormatSize(MaxFilteredBytes)}, are shown" + : filtered.Count == 1 ? "1 value" + : $"{count} values"; + } + + /// + /// The language the body tab colors a response body in: the one its Content-Type names, or JSON, HTML or other markup + /// (as XML) that a body of another type (text/plain, say) or none holds. Null for other text and for a hex dump. + /// + internal static string? SyntaxOf(ResponseSnapshot response, string shown) + { + var language = BodyFormatter.Language(response.Body, response.ContentType); + if (language != "text") + { + return language == "binary" ? null : language; + } + + // Pretty printing drops an XML declaration: the text shown starts with the root element then. + var start = shown.AsSpan().TrimStart(); + return start.StartsWith('{') || start.StartsWith('[') ? "json" + : start.StartsWith(" 0) + { + SetFilterStatus(rendered.FilterStatus, rendered.FilterFailed); + } + } + /// The response comes from the history, which has no copy of its body, though the body was not empty. private bool BodyNotKept => _fromHistory && _exchange?.Response?.Body.Length == 0 && _exchange.HistoryEntry?.Size > 0; - /// Shows in the body tab, in place of a body still being formatted. - private int ShowBody(string text) + /// Shows in the body tab, colored in , in place of a body still being formatted. + private int ShowBody(string text, string? language = null) { + _body.SyntaxLanguage = language; _body.SetText(text); return ++_bodyVersion; } - /// Copies the whole body, as formatted (a large one is formatted in the background). + /// Copies the whole body, as formatted, or the values the filter selects (a large body is done in the background). private void CopyBody() { if (_exchange?.Response is not { } response) @@ -281,15 +455,15 @@ private void CopyBody() return; } - var pretty = _prettyOn; + var (pretty, filter) = (_prettyOn, _filter); if (App is not { } app || response.Body.Length < BackgroundSize) { - Copied(Whole(response, pretty)); + Copied(Whole(response, pretty, filter)); return; } - Notify("Copying the response body…"); - _ = Task.Run(() => Whole(response, pretty)).ContinueWith( + Notify(filter is null ? "Copying the response body…" : "Copying the values the filter selects…"); + _ = Task.Run(() => Whole(response, pretty, filter)).ContinueWith( task => app.AddTimeout(TimeSpan.Zero, () => { if (task.IsCompletedSuccessfully) @@ -306,19 +480,36 @@ private void CopyBody() TaskScheduler.Default); } - private void Copied(string text) + private void Copied((string Text, bool Filtered) copied) { if (!_disposed) { - Notify(Ui.CopyToClipboard(App, text) ? "Response body copied to the clipboard." : "Clipboard is not available in this terminal."); + Notify(!Ui.CopyToClipboard(App, copied.Text) ? "Clipboard is not available in this terminal." + : copied.Filtered ? "The values the filter selects copied to the clipboard." + : "Response body copied to the clipboard."); } } - /// The whole body as formatted, with a note when the size limit cut it. - private static string Whole(ResponseSnapshot response, bool pretty) + /// + /// What Copy copies: the values the filter selects (up to ), or the whole body as formatted, + /// with a note when the size limit cut it. + /// + private static (string Text, bool Filtered) Whole(ResponseSnapshot response, bool pretty, JsonPath? filter) { + if (filter is not null) + { + try + { + return (BodyFilter.Apply(filter, response.Body, response.ContentType, pretty, MaxFilteredBytes).Text, true); + } + catch (JsonPathException) + { + // Not JSON: the body tab shows the body, which is copied. + } + } + var text = BodyFormatter.Format(response.Body, response.ContentType, pretty); - return response.BodyTruncated ? text + "\n\n… (truncated)" : text; + return (response.BodyTruncated ? text + "\n\n… (truncated)" : text, false); } /// @@ -457,9 +648,206 @@ private void SaveBody() private void Notify(string message) => Notice?.Invoke(this, message); + // ----- filter --------------------------------------------------------------------------- + + /// The Filter button: shows the JSONPath row (or closes it, which clears the filter). + internal void ToggleFilter() + { + if (_filterRow.Visible) + { + CloseFilter(); + return; + } + + _filterRow.Visible = true; + _body.Y = 2; + _tabs.Select(_bodyTab, focusPage: false); + _filterField.SetFocus(); + FilterChanged(); + } + + private void CloseFilter() + { + _filterRow.Visible = false; + _body.Y = 1; + _filterField.Text = ""; // the filter goes with it + FilterChanged(); + _body.SetFocus(); + } + + /// The query in the filter row, as typed; the body shows what it selects in this response and the ones after it. + internal void SetFilter(string query) + { + if (!_filterRow.Visible) + { + ToggleFilter(); + } + + _filterField.Text = query; + } + + /// + /// The query was edited: the body shows what it selects. While it is not valid JSONPath (being typed), the row says why + /// and the body shows what the last valid one selected. + /// + private void FilterChanged() + { + var text = _filterField.Text.TrimEnd(); + _filterInvalid = false; + if (text.Length == 0) + { + SetFilterStatus("Type a JSONPath query, such as $.items[*].id", error: false); + if (_filter is not null) + { + _filter = null; + RenderBody(); + } + + return; + } + + try + { + _filter = JsonPath.Parse(text); + } + catch (JsonPathException ex) + { + SetFilterStatus($"✗ {ex.Message}", error: true); + _filterInvalid = true; + return; + } + + if (_exchange?.Response is null) + { + SetFilterStatus("No response to filter yet.", error: false); + return; + } + + RenderBody(); + } + + private void SetFilterStatus(string text, bool error) + { + if (_filterInvalid) + { + return; // the row says why the query typed is not valid + } + + _filterStatus.Text = text; + _filterStatus.SchemeName = error ? "Error" : null; + } + + // ----- find ----------------------------------------------------------------------------- + + /// Ctrl+F: shows the find bar, its text selected to type over, looking in the text of the tab shown. + internal void OpenFind() + { + if (!_findBar.Visible) + { + _findBar.Visible = true; + _tabs.Height = Dim.Fill(1); + FindIn(SearchedArea()); + } + + _findField.SetFocus(); + _findField.SelectAll(); + } + + /// + /// F3 or Enter in the find bar: selects the next match (Shift: the previous one), going round. Opens the find bar when it + /// is closed or has no text. + /// + internal void FindNext(bool backwards = false) + { + if (!_findBar.Visible || _findField.Text.Length == 0) + { + OpenFind(); + return; + } + + _findTarget?.SelectNextMatch(backwards); + ShowFindCount(); + } + + /// The text the find bar looks for (for tests). + internal void Find(string text, bool matchCase = false) + { + OpenFind(); + _matchCase.Value = matchCase ? CheckState.Checked : CheckState.UnChecked; + _findField.Text = text; + } + + private void CloseFind() + { + var area = _findTarget; + FindIn(null); + _findBar.Visible = false; + _tabs.Height = Dim.Fill(); + if (area is not null) + { + area.SetFocus(); + } + else + { + _tabs.FocusSelectedPage(); + } + } + + private void FindChanged() + { + _findTarget?.Find(_findField.Text, _matchCase.Value == CheckState.Checked); + ShowFindCount(); + } + + /// Looks for the find bar's text in (the text of the tab shown), and no longer in another. + private void FindIn(TextArea? area) + { + if (_findTarget is { } previous && previous != area) + { + previous.Find(null, matchCase: false); + } + + _findTarget = area; + area?.Find(_findField.Text, _matchCase.Value == CheckState.Checked); + ShowFindCount(); + } + + /// The text of the tab shown; none for Headers, a table. + private TextArea? SearchedArea() => _tabs.Value?.SubViews.OfType