Skip to content

Commit

Permalink
refactor: use path type stack to handle child paths
Browse files Browse the repository at this point in the history
  • Loading branch information
koladilip committed May 22, 2024
1 parent 3b90cc9 commit a2af49f
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
15 changes: 14 additions & 1 deletion src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,15 @@ export class JsonTemplateParser {

private options?: EngineOptions;

private pathTypesStack: PathType[];

// indicates currently how many loops being parsed
private loopCount = 0;

constructor(lexer: JsonTemplateLexer, options?: EngineOptions) {
this.lexer = lexer;
this.options = options;
this.pathTypesStack = [];
}

parse(): Expression {
Expand Down Expand Up @@ -289,6 +292,13 @@ export class JsonTemplateParser {
}
}

private getCurrentPathType(): PathType | undefined {
if (this.pathTypesStack.length > 0) {
return this.pathTypesStack[this.pathTypesStack.length - 1];
}
return undefined;
}

private parsePathType(): PathType {
if (this.lexer.matchSimplePath()) {
this.lexer.ignoreTokens(1);
Expand All @@ -302,11 +312,13 @@ export class JsonTemplateParser {
this.lexer.ignoreTokens(1);
return PathType.JSON;
}
return this.options?.defaultPathType ?? PathType.RICH;

return this.getCurrentPathType() ?? this.options?.defaultPathType ?? PathType.RICH;
}

private parsePath(options?: { root?: Expression }): PathExpression | Expression {
const pathType = this.parsePathType();
this.pathTypesStack.push(pathType);
const expr: PathExpression = {
type: SyntaxType.PATH,
root: this.parsePathRoot(pathType, options?.root),
Expand All @@ -317,6 +329,7 @@ export class JsonTemplateParser {
expr.pathType = PathType.SIMPLE;
return expr;
}
this.pathTypesStack.pop();
return JsonTemplateParser.updatePathExpr(expr);
}

Expand Down
1 change: 1 addition & 0 deletions test/scenarios/paths/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export const data: Scenario[] = [
templatePath: 'json_path.jt',
input: {
foo: 'bar',
min: 1,
items: [
{
a: 1,
Expand Down
2 changes: 1 addition & 1 deletion test/scenarios/paths/json_path.jt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[
~j $.foo,
~j $.items[*],
~j $.items[?(@.a>1)],
~j $.items[?(@.a>$.min)],
~j $.items.(@.a + @.b)
]

0 comments on commit a2af49f

Please sign in to comment.