Pegjs: Comportamento inconsistente do analisador gerado

Criado em 8 mar. 2018  ·  15Comentários  ·  Fonte: pegjs/pegjs

Tipo de problema

  • Relatório de erro:

Pré-requisitos

  • Você pode reproduzir o problema ?: _sim_
  • Você pesquisou os
  • Você verificou os fóruns ?: _não_
  • Você fez uma pesquisa na web (google, yahoo, etc) ?: _yes_

Descrição

No momento estou usando a API JS para gerar o analisador em tempo de execução. Isso funciona bem.

Em seguida, tentei gerar o analisador usando a CLI, para evitar gerá-lo durante o tempo de execução. Quando eu o uso, porém, obtenho erros (~ metade dos meus testes para analisar os erros de lançamento de string).

Passos para reproduzir

  1. Mova a gramática em seu próprio arquivo grammar.pegjs
  2. Gere o analisador usando a CLI
pegjs -o parser.js grammar.pegjs
  1. Remova o peg.generate('...') e substitua-o pelo novo analisador
const parser = require('./parser');
parser.parse('...');
  1. Execute os testes

Comportamento esperado:
Eu esperaria que o analisador gerado pela CLI funcionasse da mesma forma que o analisador gerado pela API JS.

Comportamento real:
Usando a API JS, quando passo esta string ( 'foo = "bar"' ) para o analisador, obtenho o seguinte AST:

{
  kind: 'condition',
  target: 'foo',
  operator: '=',
  value: 'bar',
  valueType: 'string',
  attributeType: undefined
}

No entanto, quando eu uso o analisador "gerado" usando a CLI e passo a mesma string ( 'foo = "bar"' ), recebo o seguinte erro:

SyntaxError: Expected "(", boolean, date, datetime, number, string, or time but "\"" found.
    at peg$buildStructuredError (/Users/emmenko/xxx/parser.js:446:12)
    at Object.peg$parse [as parse] (/Users/emmenko/xxx/parser.js:2865:11)
    at repl:1:7
    at ContextifyScript.Script.runInThisContext (vm.js:50:33)
    at REPLServer.defaultEval (repl.js:240:29)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at REPLServer.onLine (repl.js:441:10)
    at emitOne (events.js:121:20)
    at REPLServer.emit (events.js:211:7) 

Programas

  • PEG.js: 0.10.0
  • Node.js: 8.9.1
  • NPM ou Yarn: [email protected]
  • Navegador: Chrome
  • OS: OSX
  • Editor: VSCode
question

Todos 15 comentários

Legal, você preencheu corretamente 👍, agora só precisamos da gramática e eu posso te ajudar 😄

Aqui está:

// GRAMMAR
const parser = peg.generate(`
{
  function getFlattenedValue (value) {
    if (!value) return undefined
    return Array.isArray(value)
      ? value.map(function(v){return v.value})
      : value.value
  }
  function getValueType (value) {
    if (!value) return undefined
    var rawType = value.type
    if (Array.isArray(value))
      rawType = value[0].type
    switch (rawType) {
      case 'string':
      case 'number':
      case 'boolean':
        return rawType
      default:
        return 'string'
    }
  }
  function getAttributeType (target, op, val) {
    if (typeof target === 'string' && target.indexOf('attributes.') === 0) {
      if (!val)
        return undefined
      switch (op) {
        case 'in':
        case 'not in':
          return val[0].type;
        case 'contains':
          return 'set-' + val.type
        default:
          return Array.isArray(val) ? 'set-' + val[0].type : val.type;
      }
    }
  }
  function transformToCondition (target, op, val) {
    return {
      kind: "condition",
      target: target,
      operator: op,
      value: getFlattenedValue(val),
      valueType: getValueType(val),
      attributeType: getAttributeType(target, op, val),
    }
  }

  function createIdentifier (body) {
    return body
      .map(identifiers => identifiers.filter(identifier => (identifier && identifier !== '.'))) // gets raw_identifiers without dots and empty identifiers
      .filter(identifiers => identifiers.length > 0) // filter out empty identifiers arrays
      .map(identifiers => identifiers.join('.'))
      .join('.') // join back to construct the path
  }
}

// ----- DSL Grammar -----
predicate
  = ws exp:expression ws { return exp; }

expression
  = head:term tail:("or" term)*
    {
      if (tail.length === 0) {
        return head;
      }

      return {
        kind: "logical",
        logical: "or",
        conditions: [head].concat(tail.map(function(el){return el[1];})),
      };
    }

term
  = head:factor tail:("and" factor)*
    {
      if (tail.length === 0) {
        return head;
      }

      return {
        kind: "logical",
        logical: "and",
        conditions: [head].concat(tail.map(function(el){return el[1];})),
      };
    }

factor
  = ws negation:"not" ws primary:primary ws
    {
      return {
        kind: "negation",
        condition: primary,
      };
    }
  / ws primary:primary ws { return primary; }

primary
  = basic_comparison
  / list_comparison
  / empty_comparison
  / parens

// ----- Comparators -----
basic_comparison
  = target:val_expression ws op:single_operators ws val:value
    { return transformToCondition(target, op, val); }

list_comparison
  = target:val_expression ws op:list_operators ws val:list_of_values
    { return transformToCondition(target, op, val); }

empty_comparison
  = target:val_expression ws op:empty_operators
    { return transformToCondition(target, op); }

// ----- Operators -----
single_operators
  = "!="
  / "="
  / "<>"
  / ">="
  / ">"
  / "<="
  / "<"
  / "contains"

list_operators
  = "!="
  / "="
  / "<>"
  / "not in"
  / "in"
  / "contains all"
  / "contains any"

empty_operators
  = "is not empty"
  / "is empty"
  / "is not defined"
  / "is defined"

list_of_values
  = ws "(" ws head:value tail:(ws "," ws value)* ws ")" ws
    {
      if (tail.length === 0) {
        return [head];
      }
      return [head].concat(tail.map(function(el){ return el[el.length -1];}));
    }

// ----- Expressions -----
val_expression
  = application_expression
  / constant_expression
  / field_expression

application_expression
  = identifier ws "(" ws function_argument (ws "," ws function_argument)* ws ")"
constant_expression = ws val:value ws { return val; }
field_expression = ws i:identifier ws { return i; }

function_argument
  = expression
  / constant_expression
  / field_expression

value
  = v:boolean { return { type: 'boolean', value: v }; }
  / v:datetime { return { type: 'datetime', value: v }; }
  / v:date { return { type: 'date', value: v }; }
  / v:time { return { type: 'time', value: v }; }
  / v:number { return { type: 'number', value: v }; }
  / v:string { return { type: 'string', value: v }; }

// ----- Common rules -----
parens
  = ws "(" ws ex:expression ws ")" ws { return ex; }

identifier
  = body:((raw_identifier "." escaped_identifier)+ / (raw_identifier "." raw_identifier)+)
    { 
      return createIdentifier(body)
    }
    / i:raw_identifier { return i; }

escaped_identifier
  = "\`" head:raw_identifier tail:("-" raw_identifier)* "\`"
    { return [head].concat(tail.map(function(el){return el.join('');})).join(''); }

raw_identifier = i:[a-zA-Z0-9_]* { return i.join(''); }

ws "whitespace" = [ \\t\\n\\r]*

// ----- Types: booleans -----
boolean "boolean"
  = "false" { return false; }
  / "true" { return true; }

// ----- Types: datetime -----
datetime "datetime"
  =  quotation_mark datetime:datetime_format quotation_mark
    { return datetime.map(function(el){return Array.isArray(el) ? el.join('') : el;}).join(''); }

datetime_format = date_format time_mark time_format zulu_mark
time_mark = "T"
zulu_mark = "Z"

// ----- Types: date -----
date "date"
  =  quotation_mark date:date_format quotation_mark { return date.join("");}

date_format = [0-9][0-9][0-9][0-9] minus [0-9][0-9] minus [0-9][0-9]

// ----- Types: time -----
time "time"
  =  quotation_mark time:time_format quotation_mark { return time.join("");}

time_format = [0-2][0-9] colon [0-5][0-9] colon [0-5][0-9] decimal_point [0-9][0-9][0-9]
colon = ":"

// ----- Types: numbers -----
number "number"
  = minus? int frac? exp? { return parseFloat(text()); }

decimal_point = "."
digit1_9 = [1-9]
e = [eE]
exp = e (minus / plus)? DIGIT+
frac = decimal_point DIGIT+
int = zero / (digit1_9 DIGIT*)
minus = "-"
plus = "+"
zero = "0"

// ----- Types: strings -----
string "string"
  = quotation_mark chars:char* quotation_mark { return chars.join(""); }

char
  = unescaped
  / escape
    sequence:(
        '"'
      / "\\\\"
      / "/"
      / "b" { return "\\b"; }
      / "f" { return "\\f"; }
      / "n" { return "\\n"; }
      / "r" { return "\\r"; }
      / "t" { return "\\t"; }
      / "u" digits:$(HEXDIG HEXDIG HEXDIG HEXDIG)
        { return String.fromCharCode(parseInt(digits, 16)); }
    )
    { return sequence; }

escape = "\\\\"
quotation_mark = '"'
unescaped = [^\\0-\\x1F\\x22\\x5C]
// See RFC 4234, Appendix B (http://tools.ietf.org/html/rfc4234).
DIGIT  = [0-9]
HEXDIG = [0-9a-f]i

Uma pequena adição relacionada ao bug. Eu configurei pegjs através do pegjs-loader . Ele opera na API JS nos bastidores chamando parser.generate e também leva ao mesmo erro.

A propósito, muito obrigado pelo projeto!

@emmenko Não sei por que sua gramática estava funcionando com a API (continuarei tentando descobrir o porquê), mas sua gramática estava incorreta, a regra unescaped deveria ser:

unescaped = !'"' [^\\0-\\x1F\\x22\\x5C]

Diga-me se isso corrige o problema do seu lado

@tdeekens Se for o mesmo erro (por exemplo, Expected ... but "\"" found. ), verifique se a sua gramática está correta ou poste aqui

@futagoza eu e @tdeekens estamos no mesmo time, então é o mesmo problema 😅

Manteremos você informado! Obrigado pelo seu apoio até agora 🙏

Não sei por que sua gramática estava funcionando com a API

Nunca tivemos problemas com isso, para ser honesto. Obrigado por apontar isso de qualquer maneira!

Está funcionando agora?

Infelizmente não ajudou ☹️

Usando sua gramática, PEG.js 0.10, Node 8.9.0 e a entrada foo = "bar" , tentei fazer isso por meio de 3 rotas:

  1. https://pegjs.org/online
  2. API PEG.js
  3. pegjs CLI

Todos os 3 mostraram o mesmo erro: Line 1, column 7: Expected "(", boolean, date, datetime, number, string, or time but "\"" found.

Se eu mudar sua gramática, ele corrigirá este erro para todas as 3 rotas:

// orignal
unescaped = [^\\0-\\x1F\\x22\\x5C]

// fixed
unescaped = !'"' [^\\0-\\x1F\\x22\\x5C]

Depois de aplicar a regra fixa, você pode verificar se:

  • você está recebendo a mesma mensagem de erro ou um erro diferente
  • você está fazendo algo diferente (ou etapas adicionais) do que mencionei
  • você está usando opções ao usar a API PEG.js.

Além disso, depois de ajustar um pouco a entrada, percebi que sua gramática não considera as novas linhas como espaços em branco corretamente, isso provavelmente se deve à sua regra ws .

EDIT: Aqui está meu script de teste:

/* eslint node/no-unsupported-features: 0 */

"use strict";

const { exec } = require( "child_process" );
const { readFileSync } = require( "fs" );
const { join } = require( "path" );
const { generate } = require( "pegjs" );

function test( parser ) {

    try {

        console.log( parser.parse( `foo = "bar"` ) );

    } catch ( error ) {

        if ( error.name !== "SyntaxError" ) throw error;

        const loc = error.location.start;

        console.log( `Line ${ loc.line }, column ${ loc.column }: ${ error.message }` );

    }

}

const COMMAND = process.argv[ 2 ];
switch ( COMMAND ) {

    case "api":
        test( generate( readFileSync( join( __dirname, "grammar.pegjs" ), "utf8" ) ) );
        break;

    case "cli":
        exec( "node node_modules/pegjs/bin/pegjs -o parser.js grammar.pegjs", error => {

            if ( error ) console.error( error ), process.exit( 1 );

            test( require( "./parser" ) );

        } );
        break;

    default:
        console.error( `Invalid command "${ COMMAND }" passed to test script.` );
        process.exit( 1 );

}

Muito obrigado pelo feedback! Tentaremos amanhã com sua sugestão e avisaremos o mais rápido possível se isso ajudou. 🙏

Obrigado pelo feedback. Em primeiro lugar, desculpas pela confusão. Eu só queria salientar que o problema também estava no webpack-loader. Desculpe, isso causou confusão neste assunto.

Nós experimentamos a melhoria. Ele corrige o analisador em geral, mas nos deparamos com um novo problema, agora que é difícil entender o motivo.

Um exemplo é de um teste (mais abaixo)

Object {
+   "attributeType": undefined,
    "kind": "condition",
    "operator": "=",
    "target": "foo",
-   "value": "bar",
+   "value": ",b,a,r",
    "valueType": "string",
}

Achamos que o erro provavelmente está do nosso lado, mas ainda não sabemos onde. Isso acontece, por exemplo, com a seguinte entrada

categories.id != ("b33f8e3a-f8d1-476f-a595-2615c4b57556")

que se torna

categories.id != (",b,3,3,f,8,e,3,a,-,f,8,d,1,-,4,7,6,f,-,a,5,9,5,-,2,6,1,5,c,4,b,5,7,5,5,6")

quando analisado.

Obviamente, ficaríamos muito gratos por uma pista, mas também entenderíamos se podemos nos apoiar nisso.

opa, erro meu 😨, isso deve consertar isso

unescaped = !'"' value:[^\\0-\\x1F\\x22\\x5C] { return value; }

Obrigado pela resposta super rápida. Ajuda, mas não ao usar o CLI ou o webpack-loader, que geralmente retorna o erro inicial de SyntaxError: Expected "(", boolean, date, datetime, number, string, or time but "\"" found. . Algo que acontece, por exemplo, com not(sku = "123") ou um exemplo mais complexo lineItemTotal(sku = "SKU1" or list contains all (1,2,3), field.name, "third arg") = "10 EUR" . Será que isso ainda tem algo a ver com a fuga?

Sim, acontece que é por causa do duplo escape. Aqui estão as regras fixas:

ws "whitespace" = [ \t\n\r]*

char
  = unescaped
  / escape
    sequence:(
        '"'
      / "\\"
      / "/"
      / "b" { return "\b"; }
      / "f" { return "\f"; }
      / "n" { return "\n"; }
      / "r" { return "\r"; }
      / "t" { return "\t"; }
      / "u" digits:$(HEXDIG HEXDIG HEXDIG HEXDIG)
        { return String.fromCharCode(parseInt(digits, 16)); }
    )
    { return sequence; }

escape = "\\"

unescaped = !'"' value:[^\0-\x1F\x22\x5C] { return value; }

EDIT: Parece que você pode querer trabalhar nas regras que analisam o exemplo complexo: lineItemTotal(sku = "SKU1" or list contains all (1,2,3), field.name, "third arg") = "10 EUR" , ele está atualmente produzindo um nó estranho "kind":"condition"

Muito obrigado pela ajuda e conselhos. Parece resolver os problemas que tínhamos. Veremos o conselho sobre o nó "condição".

De nada

Esta página foi útil?
0 / 5 - 0 avaliações