Add JSON path to CLI and refactored
This commit is contained in:
parent
82a59eebd2
commit
dc7fda1eed
@ -1,4 +1,5 @@
|
||||
using DevDisciples.Json.Parser.Syntax;
|
||||
using DevDisciples.Parsing.Extensions;
|
||||
|
||||
namespace DevDisciples.Json.Parser.Tests;
|
||||
|
||||
@ -110,7 +111,7 @@ public class JsonParserTests
|
||||
var node = JsonParser.Parse(nameof(Can_parse_an_object_with_one_entry), source);
|
||||
|
||||
Assert.That(node is JsonObjectSyntax { Properties.Length: 1 });
|
||||
var @object = (JsonObjectSyntax)node;
|
||||
var @object = node.As<JsonObjectSyntax>();
|
||||
Assert.That(@object.Properties.Any(property => property.Key.Lexeme == "first_name"));
|
||||
Assert.That(@object.Properties.First(property => property.Key.Lexeme == "first_name").Value is JsonStringSyntax { Value: "John" });
|
||||
}
|
||||
@ -124,7 +125,7 @@ public class JsonParserTests
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(node is JsonObjectSyntax { Properties.Length: 2 });
|
||||
var @object = (JsonObjectSyntax)node;
|
||||
var @object = node.As<JsonObjectSyntax>();
|
||||
Assert.That(@object.Properties.Any(property => property.Key.Lexeme == "first_name"));
|
||||
Assert.That(@object.Properties.First(property => property.Key.Lexeme == "first_name").Value is JsonStringSyntax { Value: "John" });
|
||||
Assert.That(@object.Properties.Any(property => property.Key.Lexeme == "last_name"));
|
||||
|
@ -33,7 +33,7 @@ public static partial class JsonParser
|
||||
if (ctx.Match(JsonToken.True) || ctx.Match(JsonToken.False))
|
||||
return BoolExpression(ctx);
|
||||
|
||||
throw Report.Error(ctx.Current, $"Expected a JSON expression, got '{ctx.Current.Lexeme}'");
|
||||
throw Report.SyntaxException(ctx.Current, $"Expected a JSON expression, got '{ctx.Current.Lexeme}'");
|
||||
}
|
||||
|
||||
private static IJsonSyntax ArrayExpression(ParserContext<JsonToken> ctx)
|
||||
|
@ -17,8 +17,8 @@ public class TransformController : ControllerBase
|
||||
return Ok(new { Result = result });
|
||||
}
|
||||
|
||||
[HttpPost("prettify")]
|
||||
public IActionResult Prettify([FromBody] PrettifyRequest request)
|
||||
[HttpPost("beautify")]
|
||||
public IActionResult Beautify([FromBody] BeautifyRequest request)
|
||||
{
|
||||
var context = new JsonFormatter.Context { Beautify = true, IndentSize = request.IndentSize };
|
||||
|
||||
|
@ -23,7 +23,7 @@ public class GlobalExceptionHandler : IExceptionHandler
|
||||
{
|
||||
switch (exception)
|
||||
{
|
||||
case ParsingException:
|
||||
case SyntaxException:
|
||||
_logger.LogError(exception, "An exception occurred: {Message}", exception.Message);
|
||||
|
||||
var problem = new ProblemDetails
|
||||
|
@ -1,6 +1,6 @@
|
||||
namespace DevDisciples.Json.Tools.API.Requests;
|
||||
|
||||
public class PrettifyRequest : TransformRequest
|
||||
public class BeautifyRequest : TransformRequest
|
||||
{
|
||||
public int IndentSize { get; init; } = JsonFormatter.Context.DefaultIndentSize;
|
||||
}
|
@ -1,13 +1,13 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import {HomeComponent} from "./home/home.component";
|
||||
import {PrettifyComponent} from "./prettify/prettify.component";
|
||||
import {BeautifyComponent} from "./beautify/beautify.component";
|
||||
import {UglifyComponent} from "./uglify/uglify.component";
|
||||
import {Json2CsharpComponent} from "./json2csharp/json2-csharp.component";
|
||||
import {JsonPathComponent} from "./json-path/json-path.component";
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: 'home', component: HomeComponent },
|
||||
{ path: 'prettify', component: PrettifyComponent },
|
||||
{ path: 'beautify', component: BeautifyComponent },
|
||||
{ path: 'uglify', component: UglifyComponent },
|
||||
{ path: 'json2csharp', component: Json2CsharpComponent },
|
||||
{ path: 'jsonpath', component: JsonPathComponent },
|
||||
|
@ -1,4 +1,4 @@
|
||||
<h1>JSON Prettify</h1>
|
||||
<h1>JSON Beautify</h1>
|
||||
|
||||
<app-input-output [input]="$input.value"
|
||||
[inputOptions]="inputOptions"
|
@ -1,18 +1,18 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { PrettifyComponent } from './prettify.component';
|
||||
import { BeautifyComponent } from './beautify.component';
|
||||
|
||||
describe('PrettifyComponent', () => {
|
||||
let component: PrettifyComponent;
|
||||
let fixture: ComponentFixture<PrettifyComponent>;
|
||||
describe('BeautifyComponent', () => {
|
||||
let component: BeautifyComponent;
|
||||
let fixture: ComponentFixture<BeautifyComponent>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [PrettifyComponent]
|
||||
imports: [BeautifyComponent]
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(PrettifyComponent);
|
||||
fixture = TestBed.createComponent(BeautifyComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
@ -12,17 +12,17 @@ import {
|
||||
import {BehaviorSubject, debounceTime} from "rxjs";
|
||||
|
||||
@Component({
|
||||
selector: 'app-prettify',
|
||||
selector: 'app-beautify',
|
||||
standalone: true,
|
||||
imports: [
|
||||
EditorComponent,
|
||||
FormsModule,
|
||||
InputOutputComponent
|
||||
],
|
||||
templateUrl: './prettify.component.html',
|
||||
styleUrl: './prettify.component.scss'
|
||||
templateUrl: './beautify.component.html',
|
||||
styleUrl: './beautify.component.scss'
|
||||
})
|
||||
export class PrettifyComponent implements OnInit {
|
||||
export class BeautifyComponent implements OnInit {
|
||||
// input: string = ;
|
||||
$input: BehaviorSubject<string> = new BehaviorSubject<string>(GenerateDefaultJsonObjectString());
|
||||
inputOptions = MonacoJsonConfig;
|
||||
@ -43,7 +43,7 @@ export class PrettifyComponent implements OnInit {
|
||||
|
||||
update(input: string): void {
|
||||
this.service
|
||||
.prettify(input)
|
||||
.beautify(input)
|
||||
.subscribe({
|
||||
next: response => {
|
||||
console.log(response);
|
@ -11,8 +11,8 @@ export class JsonTransformService {
|
||||
constructor(private http: HttpClient) {
|
||||
}
|
||||
|
||||
public prettify(source: string): Observable<HttpResponse<any>> {
|
||||
return this.http.post(`${this.url}/api/transform/prettify`, {Source: source}, {observe: "response"});
|
||||
public beautify(source: string): Observable<HttpResponse<any>> {
|
||||
return this.http.post(`${this.url}/api/transform/beautify`, {Source: source}, {observe: "response"});
|
||||
}
|
||||
|
||||
public uglify(source: string): Observable<HttpResponse<any>> {
|
||||
|
@ -3,7 +3,7 @@
|
||||
<mat-toolbar>Menu</mat-toolbar>
|
||||
<mat-nav-list>
|
||||
<mat-list-item routerLink="/home">Home</mat-list-item>
|
||||
<mat-list-item routerLink="/prettify">Prettify</mat-list-item>
|
||||
<mat-list-item routerLink="/beautify">Beautify</mat-list-item>
|
||||
<mat-list-item routerLink="/uglify">Uglify</mat-list-item>
|
||||
<mat-list-item routerLink="/json2csharp">JSON to C#</mat-list-item>
|
||||
<mat-list-item routerLink="/jsonpath">JSON Path</mat-list-item>
|
||||
|
@ -2,7 +2,7 @@ namespace DevDisciples.Json.Tools.CLI;
|
||||
|
||||
public class CommandOptions
|
||||
{
|
||||
public InputOptions Input { get; set; }
|
||||
public InputSource Input { get; set; }
|
||||
public FileInfo? InputFile { get; set; }
|
||||
public string? InputArgument { get; set; }
|
||||
public OutputOptions Output { get; set; }
|
||||
|
@ -4,13 +4,12 @@ namespace DevDisciples.Json.Tools.CLI.Extensions;
|
||||
|
||||
public static class CommandExtensions
|
||||
{
|
||||
public static void AddIOCommandOptions(this Command command)
|
||||
public static void AddInputOutputCommandOptions(this Command command)
|
||||
{
|
||||
command.AddOption(SharedCommandOptions.InputOption);
|
||||
command.AddOption(SharedCommandOptions.InputFileOption);
|
||||
command.AddArgument(SharedCommandOptions.InputArgument);
|
||||
command.AddOption(SharedCommandOptions.OutputOption);
|
||||
command.AddOption(SharedCommandOptions.OutputFileOption);
|
||||
|
||||
command.AddArgument(SharedCommandOptions.InputArgument);
|
||||
}
|
||||
}
|
@ -2,28 +2,28 @@
|
||||
|
||||
namespace DevDisciples.Json.Tools.CLI;
|
||||
|
||||
public static class IOHandler
|
||||
public static class InputOutputHandler
|
||||
{
|
||||
public static async Task<string> HandleInput(InputOptions input, string? inputArgument, FileInfo? inputFile)
|
||||
public static async Task<string> HandleInput(InputSource input, string? inputArgument, FileInfo? inputFile)
|
||||
{
|
||||
string json;
|
||||
|
||||
switch (input)
|
||||
{
|
||||
case InputOptions.s:
|
||||
case InputOptions.std:
|
||||
case InputOptions.stdin:
|
||||
case InputSource.s:
|
||||
case InputSource.std:
|
||||
case InputSource.stdin:
|
||||
json = inputArgument ?? string.Empty;
|
||||
break;
|
||||
|
||||
case InputOptions.c:
|
||||
case InputOptions.clip:
|
||||
case InputOptions.clipboard:
|
||||
case InputSource.c:
|
||||
case InputSource.clip:
|
||||
case InputSource.clipboard:
|
||||
json = await ClipboardService.GetTextAsync() ?? string.Empty;
|
||||
break;
|
||||
|
||||
case InputOptions.f:
|
||||
case InputOptions.file:
|
||||
case InputSource.f:
|
||||
case InputSource.file:
|
||||
if (inputFile is null)
|
||||
throw new ArgumentException("Input file was not specified.");
|
||||
|
@ -1,6 +1,6 @@
|
||||
namespace DevDisciples.Json.Tools.CLI;
|
||||
|
||||
public enum InputOptions
|
||||
public enum InputSource
|
||||
{
|
||||
// Standard input
|
||||
stdin,
|
@ -23,7 +23,7 @@ public partial class Json2CSharpCommand : Command
|
||||
AddAlias("2cs");
|
||||
AddAlias("2c#");
|
||||
|
||||
this.AddIOCommandOptions();
|
||||
this.AddInputOutputCommandOptions();
|
||||
AddOption(RootClassNameOption);
|
||||
AddOption(NamespaceOption);
|
||||
|
||||
@ -32,7 +32,7 @@ public partial class Json2CSharpCommand : Command
|
||||
|
||||
private static async Task ExecuteAsync(CommandOptions options)
|
||||
{
|
||||
var json = await IOHandler.HandleInput(options.Input, options.InputArgument, options.InputFile);
|
||||
var json = await InputOutputHandler.HandleInput(options.Input, options.InputArgument, options.InputFile);
|
||||
|
||||
var output = Json2CSharpTranslator.Translate(json, new()
|
||||
{
|
||||
@ -40,6 +40,6 @@ public partial class Json2CSharpCommand : Command
|
||||
Namespace = options.Namespace ?? Json2CSharpTranslator.Context.DefaultNamespace
|
||||
});
|
||||
|
||||
await IOHandler.HandleOutput(options.Output, options.OutputFile, output);
|
||||
await InputOutputHandler.HandleOutput(options.Output, options.OutputFile, output);
|
||||
}
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
namespace DevDisciples.Json.Tools.CLI;
|
||||
|
||||
public partial class JsonPrettifyCommand
|
||||
public partial class JsonBeautifyCommand
|
||||
{
|
||||
public class CommandOptions : CLI.CommandOptions
|
||||
{
|
@ -3,7 +3,7 @@ using DevDisciples.Json.Tools.CLI.Extensions;
|
||||
|
||||
namespace DevDisciples.Json.Tools.CLI;
|
||||
|
||||
public partial class JsonPrettifyCommand
|
||||
public partial class JsonBeautifyCommand
|
||||
{
|
||||
public class CommandOptionsBinder : BinderBase<CommandOptions>
|
||||
{
|
@ -3,23 +3,22 @@ using DevDisciples.Json.Tools.CLI.Extensions;
|
||||
|
||||
namespace DevDisciples.Json.Tools.CLI;
|
||||
|
||||
public partial class JsonPrettifyCommand : Command
|
||||
public partial class JsonBeautifyCommand : Command
|
||||
{
|
||||
private static readonly Option<int> IndentSizeOption =
|
||||
new(aliases: ["--indent", "--is"], description: "The indent size", getDefaultValue: () => 2);
|
||||
|
||||
public JsonPrettifyCommand() : base("prettify", "Prettify JSON")
|
||||
public JsonBeautifyCommand() : base("beautify", "Beautify JSON")
|
||||
{
|
||||
AddAlias("p");
|
||||
this.AddIOCommandOptions();
|
||||
AddAlias("b");
|
||||
this.AddInputOutputCommandOptions();
|
||||
AddOption(IndentSizeOption);
|
||||
|
||||
this.SetHandler(ExecuteAsync, new CommandOptionsBinder());
|
||||
}
|
||||
|
||||
private static async Task ExecuteAsync(CommandOptions options)
|
||||
{
|
||||
var json = await IOHandler.HandleInput(options.Input, options.InputArgument, options.InputFile);
|
||||
var json = await InputOutputHandler.HandleInput(options.Input, options.InputArgument, options.InputFile);
|
||||
|
||||
var output = JsonFormatter.Format(json, new()
|
||||
{
|
||||
@ -27,6 +26,6 @@ public partial class JsonPrettifyCommand : Command
|
||||
IndentSize = options.IndentSize
|
||||
});
|
||||
|
||||
await IOHandler.HandleOutput(options.Output, options.OutputFile, output);
|
||||
await InputOutputHandler.HandleOutput(options.Output, options.OutputFile, output);
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
namespace DevDisciples.Json.Tools.CLI;
|
||||
|
||||
public partial class JsonPathCommand
|
||||
{
|
||||
public class CommandOptions : CLI.CommandOptions
|
||||
{
|
||||
public string PathExpression { get; init; }
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
using System.CommandLine.Binding;
|
||||
using DevDisciples.Json.Tools.CLI.Extensions;
|
||||
|
||||
namespace DevDisciples.Json.Tools.CLI;
|
||||
|
||||
public partial class JsonPathCommand
|
||||
{
|
||||
public class CommandOptionsBinder : BinderBase<CommandOptions>
|
||||
{
|
||||
protected override CommandOptions GetBoundValue(BindingContext context) =>
|
||||
new CommandOptions
|
||||
{
|
||||
PathExpression = context.ParseResult.GetValueForOption(PathExpressionOption)
|
||||
}.WithCommonBindings(context);
|
||||
}
|
||||
}
|
32
DevDisciples.Json.Tools.CLI/JsonPathCommand.cs
Normal file
32
DevDisciples.Json.Tools.CLI/JsonPathCommand.cs
Normal file
@ -0,0 +1,32 @@
|
||||
using System.CommandLine;
|
||||
using DevDisciples.Json.Tools.CLI.Extensions;
|
||||
|
||||
namespace DevDisciples.Json.Tools.CLI;
|
||||
|
||||
public partial class JsonPathCommand : Command
|
||||
{
|
||||
private static readonly Option<string> PathExpressionOption =
|
||||
new(
|
||||
aliases: ["--expr", "-e"],
|
||||
description: "The path expression", getDefaultValue: () => "$"
|
||||
) { IsRequired = true };
|
||||
|
||||
public JsonPathCommand() : base("path", "Evaluate a JSON path expression")
|
||||
{
|
||||
AddAlias("p");
|
||||
this.AddInputOutputCommandOptions();
|
||||
this.AddOption(PathExpressionOption);
|
||||
this.SetHandler(ExecuteAsync, new CommandOptionsBinder());
|
||||
}
|
||||
|
||||
private static async Task ExecuteAsync(CommandOptions options)
|
||||
{
|
||||
var json = await InputOutputHandler.HandleInput(options.Input, options.InputArgument, options.InputFile);
|
||||
|
||||
var output = JsonPath.Interpreter.Evaluate(json, options.PathExpression);
|
||||
|
||||
var beautifiedOutput = JsonFormatter.Format(output, new() { Beautify = true });
|
||||
|
||||
await InputOutputHandler.HandleOutput(options.Output, options.OutputFile, beautifiedOutput);
|
||||
}
|
||||
}
|
@ -8,16 +8,16 @@ public class JsonUglifyCommand : Command
|
||||
public JsonUglifyCommand() : base("uglify", "Uglify JSON")
|
||||
{
|
||||
AddAlias("u");
|
||||
this.AddIOCommandOptions();
|
||||
this.AddInputOutputCommandOptions();
|
||||
this.SetHandler(ExecuteAsync, new CommandOptionsBinder());
|
||||
}
|
||||
|
||||
private static async Task ExecuteAsync(CommandOptions options)
|
||||
{
|
||||
var json = await IOHandler.HandleInput(options.Input, options.InputArgument, options.InputFile);
|
||||
var json = await InputOutputHandler.HandleInput(options.Input, options.InputArgument, options.InputFile);
|
||||
|
||||
var output = JsonFormatter.Format(json, new() { Beautify = false });
|
||||
|
||||
await IOHandler.HandleOutput(options.Output, options.OutputFile, output);
|
||||
await InputOutputHandler.HandleOutput(options.Output, options.OutputFile, output);
|
||||
}
|
||||
}
|
@ -7,7 +7,8 @@ public class RootCommand : System.CommandLine.RootCommand
|
||||
public RootCommand() : base("A JSON transform CLI tool by DevDisciples.")
|
||||
{
|
||||
AddCommand(new JsonUglifyCommand());
|
||||
AddCommand(new JsonPrettifyCommand());
|
||||
AddCommand(new JsonBeautifyCommand());
|
||||
AddCommand(new Json2CSharpCommand());
|
||||
AddCommand(new JsonPathCommand());
|
||||
}
|
||||
}
|
@ -4,8 +4,8 @@ namespace DevDisciples.Json.Tools.CLI;
|
||||
|
||||
public static class SharedCommandOptions
|
||||
{
|
||||
public static readonly Option<InputOptions> InputOption =
|
||||
new(aliases: ["--input", "-i"], getDefaultValue: () => InputOptions.stdin) { IsRequired = false };
|
||||
public static readonly Option<InputSource> InputOption =
|
||||
new(aliases: ["--input", "-i"], getDefaultValue: () => InputSource.stdin) { IsRequired = false };
|
||||
|
||||
public static readonly Argument<string?> InputArgument =
|
||||
new(name: "input", description: "The input argument.", getDefaultValue: () => default);
|
||||
|
0
DevDisciples.Json.Tools.CLI/scripts/publish_as_tool.sh
Normal file → Executable file
0
DevDisciples.Json.Tools.CLI/scripts/publish_as_tool.sh
Normal file → Executable file
@ -11,6 +11,8 @@ public static partial class Json2CSharpTranslator
|
||||
|
||||
public void Translate(Context context)
|
||||
{
|
||||
if (Properties.Count == 0) return;
|
||||
|
||||
context.Builder.Append($"public class {Name.Pascalize()}\n");
|
||||
context.Builder.Append("{\n");
|
||||
|
||||
|
@ -1,6 +1,7 @@
|
||||
using DevDisciples.Json.Parser;
|
||||
using DevDisciples.Json.Parser.Syntax;
|
||||
using DevDisciples.Parsing;
|
||||
using DevDisciples.Parsing.Extensions;
|
||||
using Humanizer;
|
||||
|
||||
namespace DevDisciples.Json.Tools;
|
||||
@ -19,10 +20,10 @@ public static partial class Json2CSharpTranslator
|
||||
Visitors.Register<JsonNullSyntax>(Null);
|
||||
}
|
||||
|
||||
public static string Translate(string source, Context? context = null)
|
||||
public static string Translate(string input, Context? context = null)
|
||||
{
|
||||
if (JsonParser.Parse("<source>", source) is not JsonObjectSyntax root)
|
||||
throw new ParsingException("Expected a JSON object.");
|
||||
if (JsonParser.Parse("<input>", input) is not JsonObjectSyntax root)
|
||||
throw new SyntaxException("Expected a JSON object.");
|
||||
|
||||
context ??= new();
|
||||
context.CurrentName = context.RootClassName;
|
||||
@ -41,7 +42,7 @@ public static partial class Json2CSharpTranslator
|
||||
|
||||
private static ITranslation Object(IJsonSyntax visitee, Context context)
|
||||
{
|
||||
var @object = (JsonObjectSyntax)visitee;
|
||||
var @object = visitee.As<JsonObjectSyntax>();
|
||||
var @class = new ClassTranslation
|
||||
{
|
||||
Name = context.CurrentName,
|
||||
@ -76,10 +77,14 @@ public static partial class Json2CSharpTranslator
|
||||
|
||||
private static ITranslation Array(IJsonSyntax visitee, Context context)
|
||||
{
|
||||
var array = (JsonArraySyntax)visitee;
|
||||
var array = visitee.As<JsonArraySyntax>();
|
||||
var type = "object";
|
||||
|
||||
if (array.Elements.All(e => e is JsonObjectSyntax))
|
||||
if (array.Elements.Length == 0)
|
||||
{
|
||||
type = "object";
|
||||
}
|
||||
else if (array.Elements.All(e => e is JsonObjectSyntax))
|
||||
{
|
||||
context.Classes.Add(SquashObjects(context.CurrentName, array.Elements, context));
|
||||
type = context.Classes.Last().Name;
|
||||
@ -106,7 +111,7 @@ public static partial class Json2CSharpTranslator
|
||||
|
||||
private static ITranslation String(IJsonSyntax visitee, Context context)
|
||||
{
|
||||
var @string = (JsonStringSyntax)visitee;
|
||||
var @string = visitee.As<JsonStringSyntax>();
|
||||
var type = DateTime.TryParse(@string.Value, out _) ? "DateTime" : "string";
|
||||
|
||||
return new PropertyTranslation
|
||||
@ -120,7 +125,7 @@ public static partial class Json2CSharpTranslator
|
||||
{
|
||||
return new PropertyTranslation
|
||||
{
|
||||
Type = ((JsonNumberSyntax)visitee).Token.Lexeme.Contains('.') ? "double" : "int",
|
||||
Type = visitee.As<JsonNumberSyntax>().Token.Lexeme.Contains('.') ? "double" : "int",
|
||||
Name = context.CurrentName,
|
||||
};
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
using DevDisciples.Json.Parser;
|
||||
using DevDisciples.Json.Parser.Syntax;
|
||||
using DevDisciples.Parsing;
|
||||
using DevDisciples.Parsing.Extensions;
|
||||
|
||||
namespace DevDisciples.Json.Tools;
|
||||
|
||||
@ -18,9 +19,9 @@ public static partial class JsonFormatter
|
||||
Visitors.Register<JsonNullSyntax>(PrintNull);
|
||||
}
|
||||
|
||||
public static string Format(string source, Context? context)
|
||||
public static string Format(string input, Context? context)
|
||||
{
|
||||
var node = JsonParser.Parse("<source>", source);
|
||||
var node = JsonParser.Parse("<input>", input);
|
||||
return Format(node, context);
|
||||
}
|
||||
|
||||
@ -33,7 +34,7 @@ public static partial class JsonFormatter
|
||||
|
||||
private static void PrintArray(IJsonSyntax visitee, Context context)
|
||||
{
|
||||
var array = (JsonArraySyntax)visitee;
|
||||
var array = visitee.As<JsonArraySyntax>();
|
||||
|
||||
context.Builder.Append($"[{context.NewLine}");
|
||||
context.IncrementDepth();
|
||||
@ -52,7 +53,7 @@ public static partial class JsonFormatter
|
||||
|
||||
private static void PrintObject(IJsonSyntax visitee, Context context)
|
||||
{
|
||||
var @object = (JsonObjectSyntax)visitee;
|
||||
var @object = visitee.As<JsonObjectSyntax>();
|
||||
|
||||
context.Builder.Append($"{{{context.NewLine}");
|
||||
context.IncrementDepth();
|
||||
@ -72,19 +73,19 @@ public static partial class JsonFormatter
|
||||
|
||||
private static void PrintString(IJsonSyntax visitee, Context context)
|
||||
{
|
||||
var @string = (JsonStringSyntax)visitee;
|
||||
var @string = visitee.As<JsonStringSyntax>();
|
||||
context.Builder.Append($"\"{@string.Token.Lexeme}\"");
|
||||
}
|
||||
|
||||
private static void PrintNumber(IJsonSyntax visitee, Context context)
|
||||
{
|
||||
var number = (JsonNumberSyntax)visitee;
|
||||
var number = visitee.As<JsonNumberSyntax>();
|
||||
context.Builder.Append($"{number.Value}");
|
||||
}
|
||||
|
||||
private static void PrintBool(IJsonSyntax visitee, Context context)
|
||||
{
|
||||
var @bool = (JsonBoolSyntax)visitee;
|
||||
var @bool = visitee.As<JsonBoolSyntax>();
|
||||
context.Builder.Append($"{@bool.Value.ToString().ToLower()}");
|
||||
}
|
||||
|
||||
|
@ -13,21 +13,21 @@ public static partial class JsonPath
|
||||
|
||||
static Interpreter()
|
||||
{
|
||||
Visitors.Register<WildCardSyntax>(WildCardExpression);
|
||||
Visitors.Register<PropertyAccessorSyntax>(PropertyAccessorExpression);
|
||||
Visitors.Register<PropertySyntax>(PropertyExpression);
|
||||
Visitors.Register<ArrayIndexSyntax>(ArrayIndexExpression);
|
||||
Visitors.Register<ArrayIndexListSyntax>(ArrayIndexListExpression);
|
||||
Visitors.Register<ObjectIndexSyntax>(ObjectIndexExpression);
|
||||
Visitors.Register<ObjectIndexListSyntax>(ObjectIndexListExpression);
|
||||
Visitors.Register<WildCardSyntax>(WildCard);
|
||||
Visitors.Register<PropertyAccessorSyntax>(PropertyAccessor);
|
||||
Visitors.Register<PropertySyntax>(Property);
|
||||
Visitors.Register<ArrayIndexSyntax>(ArrayIndex);
|
||||
Visitors.Register<ArrayIndexListSyntax>(ArrayIndexList);
|
||||
Visitors.Register<ObjectIndexSyntax>(ObjectIndex);
|
||||
Visitors.Register<ObjectIndexListSyntax>(ObjectIndexList);
|
||||
}
|
||||
|
||||
public static IJsonSyntax Evaluate(string source, string path)
|
||||
public static IJsonSyntax Evaluate(string input, string path)
|
||||
{
|
||||
var root = JsonParser.Parse("<json>", source);
|
||||
var root = JsonParser.Parse("<input>", input);
|
||||
|
||||
if (root is not JsonArraySyntax && root is not JsonObjectSyntax)
|
||||
throw Report.Error(root.Token, "Expected a JSON array or object.");
|
||||
throw Report.SyntaxException(root.Token, "Expected a JSON array or object.");
|
||||
|
||||
var expressions = Parser.Parse(path);
|
||||
|
||||
@ -41,7 +41,7 @@ public static partial class JsonPath
|
||||
|
||||
private static void Evaluate(IJsonPathSyntax node, Context context) => Visitors[node.GetType()](node, context);
|
||||
|
||||
private static void WildCardExpression(IJsonPathSyntax visitee, Context context)
|
||||
private static void WildCard(IJsonPathSyntax visitee, Context context)
|
||||
{
|
||||
switch (context.Target)
|
||||
{
|
||||
@ -57,17 +57,17 @@ public static partial class JsonPath
|
||||
|
||||
default:
|
||||
var syntax = visitee.As<WildCardSyntax>();
|
||||
throw Report.Error(syntax.Token, "Invalid target for '*'.");
|
||||
throw Report.SyntaxException(syntax.Token, "Invalid target for '*'.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void PropertyAccessorExpression(IJsonPathSyntax visitee, Context context)
|
||||
private static void PropertyAccessor(IJsonPathSyntax visitee, Context context)
|
||||
{
|
||||
var accessor = visitee.As<PropertyAccessorSyntax>();
|
||||
Evaluate(accessor.Getter, context);
|
||||
}
|
||||
|
||||
private static void PropertyExpression(IJsonPathSyntax visitee, Context context)
|
||||
private static void Property(IJsonPathSyntax visitee, Context context)
|
||||
{
|
||||
var property = visitee.As<PropertySyntax>();
|
||||
|
||||
@ -90,10 +90,10 @@ public static partial class JsonPath
|
||||
}
|
||||
}
|
||||
|
||||
private static void ArrayIndexExpression(IJsonPathSyntax visitee, Context context)
|
||||
private static void ArrayIndex(IJsonPathSyntax visitee, Context context)
|
||||
{
|
||||
if (context.Target is not JsonArraySyntax array)
|
||||
throw Report.Error(context.Target.Token, "Integer indexes are only allowed on arrays.");
|
||||
throw Report.SyntaxException(context.Target.Token, "Integer indexes are only allowed on arrays.");
|
||||
|
||||
var index = visitee.As<ArrayIndexSyntax>();
|
||||
|
||||
@ -102,15 +102,15 @@ public static partial class JsonPath
|
||||
if (value >= 0 && value < array.Elements.Length)
|
||||
context.Target = array.Elements[value];
|
||||
|
||||
else throw Report.Error(index.Token, "Index out of range.");
|
||||
else throw Report.SyntaxException(index.Token, "Index out of range.");
|
||||
}
|
||||
|
||||
private static void ArrayIndexListExpression(IJsonPathSyntax visitee, Context context)
|
||||
private static void ArrayIndexList(IJsonPathSyntax visitee, Context context)
|
||||
{
|
||||
var indices = visitee.As<ArrayIndexListSyntax>();
|
||||
|
||||
if (context.Target is not JsonArraySyntax array)
|
||||
throw Report.Error(indices.Token, "Integer indices are only allowed on arrays.");
|
||||
throw Report.SyntaxException(indices.Token, "Integer indices are only allowed on arrays.");
|
||||
|
||||
var list = new List<IJsonSyntax>();
|
||||
|
||||
@ -125,10 +125,10 @@ public static partial class JsonPath
|
||||
context.Target = new JsonArraySyntax(array.Token, list.ToArray());
|
||||
}
|
||||
|
||||
private static void ObjectIndexExpression(IJsonPathSyntax visitee, Context context)
|
||||
private static void ObjectIndex(IJsonPathSyntax visitee, Context context)
|
||||
{
|
||||
if (context.Target is not JsonObjectSyntax @object)
|
||||
throw Report.Error(context.Target.Token, "String indices are only allowed on objects.");
|
||||
throw Report.SyntaxException(context.Target.Token, "String indices are only allowed on objects.");
|
||||
|
||||
var index = visitee.As<ObjectIndexSyntax>();
|
||||
|
||||
@ -142,10 +142,10 @@ public static partial class JsonPath
|
||||
context.Target = new JsonNullSyntax(@object.Token);
|
||||
}
|
||||
|
||||
private static void ObjectIndexListExpression(IJsonPathSyntax visitee, Context context)
|
||||
private static void ObjectIndexList(IJsonPathSyntax visitee, Context context)
|
||||
{
|
||||
if (context.Target is not JsonObjectSyntax @object)
|
||||
throw Report.Error(context.Target.Token, "Index strings are only allowed on objects.");
|
||||
throw Report.SyntaxException(context.Target.Token, "Index strings are only allowed on objects.");
|
||||
|
||||
var indices = visitee.As<ObjectIndexListSyntax>();
|
||||
|
||||
|
@ -8,7 +8,7 @@ public static partial class JsonPath
|
||||
{
|
||||
public static List<IJsonPathSyntax> Parse(string path)
|
||||
{
|
||||
var pathTokens = Lexer.Default.Lex("<path>", path);
|
||||
var pathTokens = Lexer.Default.Lex("<path_expression>", path);
|
||||
var context = new Context(pathTokens.ToArray());
|
||||
|
||||
context.Match(JsonPathToken.DollarSign); // Match the '$' eagerly. This will make it optional by default.
|
||||
@ -28,7 +28,7 @@ public static partial class JsonPath
|
||||
if (context.Match(JsonPathToken.LeftBracket))
|
||||
return IndexAccessorExpression(context);
|
||||
|
||||
throw context.Error("Invalid expression.");
|
||||
throw context.Error($"Invalid expression '{context.Current.Lexeme}'.");
|
||||
}
|
||||
|
||||
private static IJsonPathSyntax PropertyAccessorExpression(Context context)
|
||||
|
@ -6,7 +6,6 @@ namespace DevDisciples.Json.Tools;
|
||||
|
||||
public static partial class JsonPath
|
||||
{
|
||||
|
||||
public interface IJsonPathSyntax
|
||||
{
|
||||
public Lexer<JsonPathToken>.Token Token { get; }
|
||||
|
@ -73,7 +73,7 @@ public abstract partial class Lexer<TToken> where TToken : Enum
|
||||
|
||||
if (src.Ended())
|
||||
{
|
||||
throw new ParsingException(
|
||||
throw new SyntaxException(
|
||||
$"[line: {src.Line}, column: {src.Column}] Unterminated string near '{src.Last}'."
|
||||
);
|
||||
}
|
||||
@ -117,7 +117,7 @@ public abstract partial class Lexer<TToken> where TToken : Enum
|
||||
|
||||
if (src.Ended())
|
||||
{
|
||||
throw new ParsingException(
|
||||
throw new SyntaxException(
|
||||
$"[line: {src.Line}, column: {src.Column}] Unterminated string near '{src.Last}'."
|
||||
);
|
||||
}
|
||||
|
@ -25,7 +25,7 @@ public abstract partial class Lexer<TToken> where TToken : Enum
|
||||
|
||||
if (!matched)
|
||||
{
|
||||
Report.Halt(ctx.Source, $"Unexpected character '{ctx.Source.Current}'.");
|
||||
Report.SyntaxHalt(ctx.Source, $"Unexpected character '{ctx.Source.Current}'.");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -91,11 +91,11 @@ public class ParserContext<TToken> : ParsableStream<Lexer<TToken>.Token> where T
|
||||
|
||||
public Exception Error(string message)
|
||||
{
|
||||
return new ParsingException(Report.FormatMessage(Current, message));
|
||||
return new SyntaxException(Report.FormatMessage(Current, message));
|
||||
}
|
||||
|
||||
public Exception Error(Lexer<TToken>.Token token, string message)
|
||||
{
|
||||
return new ParsingException(Report.FormatMessage(token, message));
|
||||
return new SyntaxException(Report.FormatMessage(token, message));
|
||||
}
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
namespace DevDisciples.Parsing;
|
||||
|
||||
public class ParsingException : Exception
|
||||
{
|
||||
public ParsingException()
|
||||
{
|
||||
}
|
||||
|
||||
public ParsingException(string? message) : base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public ParsingException(string? message, Exception? innerException) : base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
@ -2,14 +2,14 @@
|
||||
|
||||
public static class Report
|
||||
{
|
||||
public static ParsingException Error(ISourceLocation token, string message)
|
||||
public static SyntaxException SyntaxException(ISourceLocation token, string message)
|
||||
{
|
||||
return new ParsingException(FormatMessage(token, message));
|
||||
return new SyntaxException(FormatMessage(token, message));
|
||||
}
|
||||
|
||||
public static void Halt(ISourceLocation token, string message)
|
||||
public static void SyntaxHalt(ISourceLocation token, string message)
|
||||
{
|
||||
throw new ParsingException(FormatMessage(token, message));
|
||||
throw new SyntaxException(FormatMessage(token, message));
|
||||
}
|
||||
|
||||
public static string FormatMessage(ISourceLocation token, string msg)
|
||||
|
16
DevDisciples.Parsing/SyntaxException.cs
Normal file
16
DevDisciples.Parsing/SyntaxException.cs
Normal file
@ -0,0 +1,16 @@
|
||||
namespace DevDisciples.Parsing;
|
||||
|
||||
public class SyntaxException : Exception
|
||||
{
|
||||
public SyntaxException()
|
||||
{
|
||||
}
|
||||
|
||||
public SyntaxException(string? message) : base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public SyntaxException(string? message, Exception? innerException) : base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user