Pegjs: ¿Cómo puedo crear un patrón PEG.js para mi consulta de base de datos (X "Y" Y "Y" ...)

Creado en 27 nov. 2018  ·  3Comentarios  ·  Fuente: pegjs/pegjs

Tipo de problema

PREGUNTA

Prerrequisitos

  • ¿Puedes reproducir el problema ?: SI
  • ¿Buscaste los problemas del repositorio ?:
  • ¿Revisaste los foros ?: SI
  • ¿Realizó una búsqueda en la web (google, yahoo, etc.) ?:

Descripción / código de ejemplo

Hasta ahora, mi analizador se ve así.

const parser = peg.generate(`

eq
  = left:attribute "=" right:value { return left == right; }

and
  = left:eq "AND" right:eq { return left && right; }

Puede leer consultas como id = 2 AND createdOn = 193242 . Quiero poder leer id = 2 AND secondId = 444 AND createdOn = 193242 y así sucesivamente ... (Cualquier número de "Y"). ¿Cómo puedo lograr esto a través de PEG.js?

question

Todos 3 comentarios

Esto debería hacerlo:

and
  = left:eq right:and_eq+ {
      if ( right.length === 1 ) return left && right;
      // handle more then 1 'AND eq' here
    }

and_eq
  = "AND" e:eq { return e; }

Solución genérica para cualquier número de operadores con cualquier precedencia (crea AST):

{
function leftAssotiative(left, tail) {
  let r = left;
  for (let i = 0; i < tail.length; ++i) {
    r = { kind: tail[i][0], left: r, right: tail[i][1] };
  }
  return r;
}
function rightAssotiative(left, tail) {
  if (tail.length > 1) {
    let r = tail[tail.length-1][1];
    for (let i = tail.length-2; i >= 0; --i) {
      r = { kind: tail[i+1][0], left: tail[i][1], right: r };
    }
    return { kind: tail[0][0], left: left, right: r };
  }
  return left;
}
}

// Expressions
Expr// minimal priority
  = l:Expr0 t:(p0 Expr0)* { return rightAssotiative(l, t); };
Expr0
  = l:Expr1 t:(p1 Expr1)* { return leftAssotiative(l, t); };
...
ExprN// maximal priority
  = '(' <strong i="6">@Expr</strong> ')';

// Operators
p0 = [+-];
p1 = [*/];
...

@futagoza cerebro sexy. ¡Gracias!

¿Fue útil esta página
0 / 5 - 0 calificaciones

Temas relacionados

mreinstein picture mreinstein  ·  12Comentarios

mattkanwisher picture mattkanwisher  ·  5Comentarios

dmajda picture dmajda  ·  15Comentarios

futagoza picture futagoza  ·  6Comentarios

StoneCypher picture StoneCypher  ·  8Comentarios