/** * @fileoverview Query parser for loq DSL and SQL-like queries * @module query/parser * * Parses tokenized query strings into an Abstract Syntax Tree (AST). * Supports both the loq DSL syntax and SQL-like SELECT queries. * * @example * ```ts * // DSL syntax * const query = parseQuery(['where', 'level=error', 'and', 'status>=400']); * * // SQL syntax * const query = parseQuery(['sql', "SELECT * FROM app.log WHERE level='error'"]); * ``` */ import type { Token, TokenType } from './lexer'; import { tokenize } from './lexer'; import type { QueryNode, ParsedQuery, ComparisonExpr, TimeFilterExpr, AggregationExpr, SelectExpr } from './ast'; /** * Query parser class for parsing loq queries * Uses recursive descent parsing for expression handling */ export class QueryParser { private tokens: Token[] = []; private pos = 0; parse(queryParts: string[]): ParsedQuery { if (queryParts.length === 0) { return {}; } // Check for SQL mode if (queryParts[0] === 'sql') { return this.parseSql(queryParts[1]); } const query = queryParts.join(' '); this.tokens = tokenize(query); this.pos = 0; return this.parseQuery(); } private parseQuery(): ParsedQuery { const result: ParsedQuery = {}; while (!this.isAtEnd()) { const token = this.current(); if (token.type === 'KEYWORD') { switch (token.value) { case 'where': this.advance(); result.where = this.parseExpression(); break; case 'count': this.advance(); if (this.match('KEYWORD', 'by')) { this.advance(); const field = this.expect('FIELD'); result.aggregation = { type: 'count', groupBy: field.value }; } else { result.aggregation = { type: 'count' }; } break; case 'between': result.timeFilter = this.parseTimeFilter(); break; case 'after': case 'before': result.timeFilter = this.parseTimeFilter(); break; case 'limit': this.advance(); const num = this.expect('NUMBER'); result.limit = parseInt(num.value, 10); break; default: this.advance(); } } else { this.advance(); } } return result; } private parseExpression(): QueryNode { return this.parseOr(); } private parseOr(): QueryNode { let left = this.parseAnd(); while (this.match('KEYWORD', 'or')) { this.advance(); const right = this.parseAnd(); left = { type: 'binary', operator: 'or', left, right }; } return left; } private parseAnd(): QueryNode { let left = this.parseNot(); while (this.match('KEYWORD', 'and')) { this.advance(); const right = this.parseNot(); left = { type: 'binary', operator: 'and', left, right }; } return left; } private parseNot(): QueryNode { if (this.match('KEYWORD', 'not')) { this.advance(); return { type: 'not', operand: this.parseNot() }; } return this.parsePrimary(); } private parsePrimary(): QueryNode { // Handle parentheses if (this.match('LPAREN')) { this.advance(); const expr = this.parseExpression(); this.expect('RPAREN'); return expr; } // Field comparison const field = this.current(); if (field.type === 'FIELD') { this.advance(); const op = this.expect('OPERATOR'); const value = this.parseValue(); return { type: 'comparison', field: field.value, operator: op.value as ComparisonExpr['operator'], value, }; } throw new Error(`Unexpected token: ${field.value} at position ${field.position}`); } private parseValue(): string | number { const token = this.current(); this.advance(); if (token.type === 'NUMBER') { return parseFloat(token.value); } if (token.type === 'STRING') { return token.value; } if (token.type === 'FIELD') { return token.value; } throw new Error(`Expected value, got ${token.type}`); } private parseTimeFilter(): TimeFilterExpr { const op = this.current().value as 'between' | 'after' | 'before'; this.advance(); if (op === 'between') { const start = this.parseTimeValue(); this.expect('KEYWORD', 'and'); const end = this.parseTimeValue(); const relative = this.parseRelativeTime(); return { type: 'timefilter', operator: 'between', start, end, relative }; } const time = this.parseTimeValue(); return { type: 'timefilter', operator: op, start: time }; } private parseTimeValue(): string { const token = this.current(); this.advance(); return token.value; } private parseRelativeTime(): string | undefined { if (this.match('KEYWORD', 'today') || this.match('KEYWORD', 'yesterday')) { const val = this.current().value; this.advance(); return val; } return undefined; } private parseSql(sql: string): ParsedQuery { this.tokens = tokenize(sql); this.pos = 0; const result: ParsedQuery = {}; // Expect SELECT this.expect('KEYWORD', 'select'); const select: SelectExpr = { type: 'select', fields: [], from: '', }; // Parse fields if (this.match('OPERATOR', '*')) { this.advance(); select.fields = '*'; } else { const fields: string[] = []; const aggregations: AggregationExpr[] = []; do { if (this.matchAny('KEYWORD', ['count', 'sum', 'avg', 'min', 'max'])) { aggregations.push(this.parseAggregation()); } else { const field = this.expect('FIELD'); fields.push(field.value); } } while (this.matchAdvance('OPERATOR', ',')); select.fields = fields; if (aggregations.length > 0) { select.aggregations = aggregations; } } // FROM this.expect('KEYWORD', 'from'); const from = this.current(); this.advance(); select.from = from.value; result.source = from.value; // WHERE (optional) if (this.match('KEYWORD', 'where')) { this.advance(); select.where = this.parseExpression(); result.where = select.where; } // GROUP BY (optional) if (this.match('KEYWORD', 'group')) { this.advance(); this.expect('KEYWORD', 'by'); const field = this.expect('FIELD'); select.groupBy = field.value; } // LIMIT (optional) if (this.match('KEYWORD', 'limit')) { this.advance(); const num = this.expect('NUMBER'); select.limit = parseInt(num.value, 10); result.limit = select.limit; } result.select = select; return result; } private parseAggregation(): AggregationExpr { const func = this.current().value as AggregationExpr['func']; this.advance(); this.expect('LPAREN'); let field: string | undefined; if (this.match('OPERATOR', '*')) { this.advance(); } else { field = this.expect('FIELD').value; } this.expect('RPAREN'); let alias: string | undefined; if (this.match('KEYWORD', 'as')) { this.advance(); alias = this.expect('FIELD').value; } return { type: 'aggregation', func, field, alias }; } // Helper methods private current(): Token { return this.tokens[this.pos] || { type: 'EOF', value: '', position: -1 }; } private advance(): Token { const token = this.current(); if (!this.isAtEnd()) this.pos++; return token; } private isAtEnd(): boolean { return this.current().type === 'EOF'; } private match(type: TokenType, value?: string): boolean { const token = this.current(); if (token.type !== type) return false; if (value !== undefined && token.value !== value) return false; return true; } private matchAny(type: TokenType, values: string[]): boolean { const token = this.current(); return token.type === type && values.includes(token.value); } private matchAdvance(type: TokenType, value?: string): boolean { if (this.match(type, value)) { this.advance(); return true; } return false; } private expect(type: TokenType, value?: string): Token { const token = this.current(); if (!this.match(type, value)) { throw new Error(`Expected ${type}${value ? ` '${value}'` : ''}, got ${token.type} '${token.value}'`); } return this.advance(); } } /** * Parse a query from command-line arguments * @param queryParts - Array of query tokens from CLI args * @returns Parsed query AST * @example * ```ts * const query = parseQuery(['where', 'level=error']); * if (query.where) { * // Filter entries * } * ``` */ export function parseQuery(queryParts: string[]): ParsedQuery { const parser = new QueryParser(); return parser.parse(queryParts); }