Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup #115

Merged
merged 2 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Changed
- Minor performance improvements

## [0.7.4] - 2024-08-03
### Changed
- CTS updated
Expand Down Expand Up @@ -205,6 +209,7 @@ Previously, no modification would be made and no errors/exceptions thrown.
### Added
- Basic design draft

[Unreleased]: https://github.com/f3ath/jessie/compare/0.7.4...HEAD
[0.7.4]: https://github.com/f3ath/jessie/compare/0.7.3...0.7.4
[0.7.3]: https://github.com/f3ath/jessie/compare/0.7.2...0.7.3
[0.7.2]: https://github.com/f3ath/jessie/compare/0.7.1...0.7.2
Expand Down
23 changes: 23 additions & 0 deletions benchmark/parsing.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import 'package:json_path/json_path.dart';

void main() {
const e1 =
r"$..store[?(@.type == 'electronics')].items[?(@.price > 100 && @.availability == 'in stock')].details[?(@.specs.screen.size >= 40 && search(@.specs.processor, 'Intel|AMD'))].reviews[*].comments[?(@.rating >= 4 && @.verified == true)].content[?(length(@) > 100)]";
const e2 =
r"$..book[0:10][?(match(@.author, '(J.K.|George R.R.) Martin') && @.price < 30 && @.published >= '2010-01-01')].summary[?(length(@) > 200)]";
const e3 =
r"$..store.bicycle[?(@.price > 50)].model[?match(@, '(Mountain|Road)')]";
const e4 =
r"$..orders[*][?(@.status == 'delivered' && value(@.items[0:5][?(@.price > 50 && match(@.category, '(Electronics|Books)'))].quantity) > 1)].tracking[*].history[?(@.location == 'Warehouse' && @.status == 'out for delivery')]";

final start = DateTime.now();
for (var i = 0; i < 50000; i++) {
JsonPath(e1);
JsonPath(e2);
JsonPath(e3);
JsonPath(e4);
}
final end = DateTime.now();
print(
'Duration: ${end.difference(start).inMilliseconds} ms');
}
20 changes: 7 additions & 13 deletions lib/src/fun/fun_factory.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,11 @@ class FunFactory {
Expression<NodeList> nodes(FunCall call) => _any<NodeList>(call);

/// Returns a function to use as an argument for another function.
Expression<T> _any<T extends Object>(FunCall call) {
final name = call.name;
final args = call.args;
try {
if (args.length == 1) return _any1<T>(name, args[0]);
if (args.length == 2) return _any2<T>(name, args[0], args[1]);
} on StateError catch (e) {
throw FormatException(e.message);
}
throw Exception('Type mismatch');
}
Expression<T> _any<T extends Object>(FunCall call) => switch (call.args) {
[var a] => _any1<T>(call.name, a),
[var a, var b] => _any2<T>(call.name, a, b),
_ => throw Exception('Invalid number of args for ${call.name}()'),
};

Expression<T> _any1<T extends Object>(String name, Expression a0) {
final f = _getFun1<T>(name);
Expand Down Expand Up @@ -79,13 +73,13 @@ class FunFactory {
Fun1<T, Object> _getFun1<T extends Object>(String name) {
final f = _fun1[name];
if (f is Fun1<T, Object>) return f;
throw StateError('Function "$name" of 1 argument is not found');
throw FormatException('Function "$name" of 1 argument is not found');
}

Fun2<T, Object, Object> _getFun2<T extends Object>(String name) {
final f = _fun2[name];
if (f is Fun2<T, Object, Object>) return f;
throw StateError('Function "$name" of 2 arguments is not found');
throw FormatException('Function "$name" of 2 arguments is not found');
}

static Expression cast(Expression arg,
Expand Down
137 changes: 58 additions & 79 deletions lib/src/grammar/json_path.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import 'package:json_path/src/grammar/negatable.dart';
import 'package:json_path/src/grammar/parser_ext.dart';
import 'package:json_path/src/grammar/select_all_recursively.dart';
import 'package:json_path/src/grammar/sequence_selector.dart';
import 'package:json_path/src/grammar/singular_segment_sequence.dart';
import 'package:json_path/src/grammar/strings.dart';
import 'package:json_path/src/grammar/union_selector.dart';
import 'package:json_path/src/grammar/wildcard.dart';
Expand All @@ -28,27 +29,25 @@ class JsonPathGrammarDefinition
final FunFactory _fun;

@override
Parser<Expression<NodeList>> start() => ref0(_absPath).end();
Parser<Expression<NodeList>> start() => _absPath().end();

Parser<Selector> _unionElement() => [
arraySlice,
arrayIndex,
wildcard,
quotedString.map(childSelector),
_expressionFilter()
].toChoiceParser().trim();
Parser<Expression<NodeList>> _absPath() => _segmentSequence()
.skip(before: char(r'$'))
.map((expr) => Expression((node) => expr.call(node.root)));

Parser<SingularSelector> _singularUnionElement() => [
arrayIndex,
quotedString.map(childSelector),
Parser<Expression<NodeList>> _segmentSequence() =>
_segment().star().map(sequenceSelector).map(Expression.new);

Parser<Selector> _segment() => [
dotName,
wildcard.skip(before: char('.')),
ref0(_union),
ref0(_recursion),
].toChoiceParser().trim();

Parser<Selector> _union() =>
_unionElement().toList().inBrackets().map(unionSelector);

Parser<SingularSelector> _singularUnion() =>
_singularUnionElement().inBrackets();

Parser<Selector> _recursion() => [
wildcard,
_union(),
Expand All @@ -58,38 +57,18 @@ class JsonPathGrammarDefinition
.skip(before: string('..'))
.map((value) => sequenceSelector([selectAllRecursively, value]));

Parser<Expression<bool>> _parenExpr() => negatable(_logicalExpr().inParens());

Parser<Expression> _funArgument() => [
literal,
ref0(_singularFilterPath),
ref0(_filterPath),
ref0(_valueFunExpr),
ref0(_logicalFunExpr),
ref0(_nodesFunExpr),
ref0(_logicalExpr),
Parser<Selector> _unionElement() => [
arraySlice,
arrayIndex,
wildcard,
quotedString.map(childSelector),
_expressionFilter()
].toChoiceParser().trim();

Parser<T> _funCall<T>(T Function(FunCall) toFun) =>
(funName & _funArgument().toList().inParens())
.map((v) => FunCall(v[0], v[1]))
.tryMap(toFun);

Parser<Expression<Maybe>> _valueFunExpr() => _funCall(_fun.value);

Parser<Expression<NodeList>> _nodesFunExpr() => _funCall(_fun.nodes);

Parser<Expression<bool>> _logicalFunExpr() => _funCall(_fun.logical);

Parser<Expression<Maybe>> _comparable() => [
literal,
_singularFilterPath().map((expr) => expr.map((v) => v.asValue)),
_valueFunExpr(),
].toChoiceParser();

Parser<Expression<bool>> _logicalExpr() => _logicalOrExpr();
Parser<Selector> _expressionFilter() =>
_logicalExpr().skip(before: string('?').trim()).map(filterSelector);

Parser<Expression<bool>> _logicalOrExpr() => _logicalOrSequence()
Parser<Expression<bool>> _logicalExpr() => _logicalOrSequence()
.map((list) => list.reduce((a, b) => a.merge(b, (a, b) => a || b)));

Parser<List<Expression<bool>>> _logicalOrSequence() =>
Expand All @@ -109,61 +88,61 @@ class JsonPathGrammarDefinition
failureJoiner: (a, b) =>
Failure(a.buffer, a.position, 'Expression expected'));

Parser<Expression<NodeList>> _filterPath() => [
ref0(_relPath),
ref0(_absPath),
].toChoiceParser();

Parser<Expression<SingularNodeList>> _singularFilterPath() => [
ref0(_singularRelPath),
ref0(_singularAbsPath),
].toChoiceParser();

Parser<Expression<bool>> _existenceTest() =>
ref0(_filterPath).map((value) => value.map((v) => v.asLogical));
Parser<Expression<bool>> _parenExpr() => negatable(_logicalExpr().inParens());

Parser<Expression<bool>> _testExpr() => negatable([
_existenceTest(),
_logicalFunExpr(),
].toChoiceParser());

Parser<Selector> _expressionFilter() =>
_logicalExpr().skip(before: string('?').trim()).map(filterSelector);
Parser<Expression<bool>> _existenceTest() =>
_filterPath().map((value) => value.map((v) => v.asLogical));

Parser<Selector> _segment() => [
dotName,
wildcard.skip(before: char('.')),
ref0(_union),
ref0(_recursion),
].toChoiceParser().trim();
Parser<Expression<bool>> _logicalFunExpr() => _funCall(_fun.logical);

Parser<SingularSelector> _singularSegment() => [
dotName,
ref0(_singularUnion),
Parser<T> _funCall<T>(T Function(FunCall) toFun) =>
(funName & _funArgument().toList().inParens())
.map((v) => FunCall(v[0], v[1]))
.tryMap(toFun);

Parser<Expression> _funArgument() => [
literal,
_singularFilterPath(),
_filterPath(),
ref0(_valueFunExpr),
ref0(_logicalFunExpr),
ref0(_nodesFunExpr),
ref0(_logicalExpr),
].toChoiceParser().trim();

Parser<Expression<NodeList>> _segmentSequence() =>
_segment().star().map(sequenceSelector).map(Expression.new);
Parser<Expression<SingularNodeList>> _singularFilterPath() => [
ref0(_singularRelPath),
ref0(_singularAbsPath),
].toChoiceParser();

Parser<Expression<SingularNodeList>> _singularSegmentSequence() =>
_singularSegment()
.star()
.map(singularSequenceSelector)
.map(Expression.new);
Parser<Expression<Maybe>> _valueFunExpr() => _funCall(_fun.value);

Parser<Expression<NodeList>> _absPath() => _segmentSequence()
.skip(before: char(r'$'))
.map((expr) => Expression((node) => expr.call(node.root)));
Parser<Expression<NodeList>> _nodesFunExpr() => _funCall(_fun.nodes);

Parser<Expression<Maybe>> _comparable() => [
literal,
_singularFilterPath().map((expr) => expr.map((v) => v.asValue)),
_valueFunExpr(),
].toChoiceParser();

Parser<Expression<NodeList>> _filterPath() => [
ref0(_relPath),
ref0(_absPath),
].toChoiceParser();

Parser<Expression<SingularNodeList>> _singularAbsPath() =>
_singularSegmentSequence()
singularSegmentSequence
.skip(before: char(r'$'), after: _segment().not())
.map((expr) => Expression((node) => expr.call(node.root)));

Parser<Expression<NodeList>> _relPath() =>
_segmentSequence().skip(before: char('@'));

Parser<Expression<SingularNodeList>> _singularRelPath() =>
_singularSegmentSequence()
.skip(before: char('@'), after: _segment().not());
singularSegmentSequence.skip(before: char('@'), after: _segment().not());
}
23 changes: 23 additions & 0 deletions lib/src/grammar/singular_segment_sequence.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import 'package:json_path/src/expression/expression.dart';
import 'package:json_path/src/grammar/array_index.dart';
import 'package:json_path/src/grammar/child_selector.dart';
import 'package:json_path/src/grammar/dot_name.dart';
import 'package:json_path/src/grammar/parser_ext.dart';
import 'package:json_path/src/grammar/sequence_selector.dart';
import 'package:json_path/src/grammar/strings.dart';
import 'package:petitparser/petitparser.dart';

final _singularUnionElement = [
arrayIndex,
quotedString.map(childSelector),
].toChoiceParser().trim();

final _singularUnion = _singularUnionElement.inBrackets();

final _singularSegment = [
dotName,
_singularUnion,
].toChoiceParser().trim();

final singularSegmentSequence =
_singularSegment.star().map(singularSequenceSelector).map(Expression.new);
4 changes: 1 addition & 3 deletions lib/src/grammar/strings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ final _escapedControl = [
_escapedTab
].toChoiceParser();

// The parser does not seem to support Unicode 6.0 boundary (0x10FFFF).
// We're limiting ourselves to Unicode 1.0 boundary (0xFFFF).
// TODO: work around by using surrogate pairs
// The highest unicode character
final _unicodeBoundary = String.fromCharCode(0xFFFF);

// Exclude double quote '"' and back slash '\'
Expand Down
2 changes: 1 addition & 1 deletion lib/src/json_path_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class JsonPathParser {

JsonPathParser._(Iterable<Fun> functions)
: _parser =
JsonPathGrammarDefinition(FunFactory([..._stdFun, ...functions]))
JsonPathGrammarDefinition(FunFactory(_stdFun.followedBy(functions)))
.build<Expression<NodeList>>();

/// The standard instance is pre-cached to speed up parsing when only
Expand Down
8 changes: 4 additions & 4 deletions lib/src/node_match.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class NodeMatch implements JsonPathMatch {
final Object? value;
}

extension _NodeExt<T> on Node<T> {
extension<T> on Node<T> {
Iterable<Object> trace() sync* {
if (key != null) {
yield* parent!.trace();
Expand All @@ -35,7 +35,7 @@ extension _NodeExt<T> on Node<T> {
JsonPointer pointer() => JsonPointer.build(trace().map((e) => e.toString()));

String path() => r'$' + trace().map(_segment).join();
}

Object _segment(Object? v) =>
v is int ? IndexSelector(v) : NameSelector(v.toString());
Object _segment(Object? v) =>
v is int ? IndexSelector(v) : NameSelector(v.toString());
}
2 changes: 1 addition & 1 deletion lib/src/normalized/name_selector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class NameSelector {
String toString() => "['${name.escaped}']";
}

extension _StringExt on String {
extension on String {
/// Returns a string with all characters escaped as unicode entities.
String get unicodeEscaped =>
codeUnits.map((c) => '\\u${c.toRadixString(16).padLeft(4, '0')}').join();
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ dependencies:

dev_dependencies:
check_coverage: ^0.0.4
lints: ">=3.0.0 <5.0.0"
lints: ^4.0.0
path: ^1.8.2
test: ^1.21.1

Expand Down
Loading