現在、JS APIを使用して、実行時にパーサーを生成しています。 これは正常に機能します。
次に、実行時に生成されないように、CLIを使用してパーサーを生成しようとしました。 エラーが発生しますが、使用すると(文字列スローエラーを解析するためのテストの半分まで)。
grammar.pegjs
pegjs -o parser.js grammar.pegjs
peg.generate('...')
を削除し、新しいパーサーと交換しますconst parser = require('./parser');
parser.parse('...');
予想される行動:
CLIから生成されたパーサーは、JSAPIから生成されたパーサーと同じように機能することを期待します。
実際の動作:
JS APIを使用して、この文字列( 'foo = "bar"'
)をパーサーに渡すと、次のASTが取得されます。
{
kind: 'condition',
target: 'foo',
operator: '=',
value: 'bar',
valueType: 'string',
attributeType: undefined
}
ただし、CLIを使用して「生成された」パーサーを使用し、同じ文字列( 'foo = "bar"'
)を渡すと、次のエラーが発生します。
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)
0.10.0
8.9.1
[email protected]
いいですね、あなたはそれを正しく記入しました👍、今私たちは文法が必要です、そして私はあなたを助けることができます😄
どうぞ:
// 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
バグへの少し関連した追加。 pegjs-loaderを介してpegjs
を設定します。 parser.generate
呼び出す内部でJS APIで動作し、同じエラーが発生します。
ちなみにプロジェクトに感謝します!
@emmenkoなぜあなたの文法がAPIで機能していたのかわかりませんが(理由を見つけようとし続けます)、あなたの文法は正しくありませんunescaped
ルールは次のようになります。
unescaped = !'"' [^\\0-\\x1F\\x22\\x5C]
これで問題が解決するかどうか教えてください
@tdeekens同じエラー(例: Expected ... but "\"" found.
)の場合は、文法が正しいかどうかを確認するか、ここに投稿してください
@futagoza meと@tdeekensは同じチームに所属しているので、同じ問題です😅
私たちはあなたを投稿し続けます! これまでのサポートに感謝します🙏
文法がAPIで機能していた理由がわかりません
正直なところ、問題はありませんでした。 とにかくそれを指摘してくれてありがとう!
今は動いていますか?
残念ながらそれは役に立ちませんでした☹️
文法、PEG.js 0.10、ノード8.9.0、および入力foo = "bar"
、次の3つのルートでこれを試しました。
pegjs
CLI3つすべてが同じエラーを示しました: Line 1, column 7: Expected "(", boolean, date, datetime, number, string, or time but "\"" found.
文法を変更すると、3つのルートすべてでこのエラーが修正されます。
// orignal
unescaped = [^\\0-\\x1F\\x22\\x5C]
// fixed
unescaped = !'"' [^\\0-\\x1F\\x22\\x5C]
固定ルールを適用した後、次のことを確認できますか?
また、入力を少し調整した後、文法が改行を空白として正しく考慮していないことに気付きました。これは、 ws
ルールが原因である可能性があります。
編集:これが私のテストスクリプトです:
/* 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 );
}
フィードバックをありがとう! 明日はあなたの提案で試してみますが、それが役に立ったらできるだけ早くお知らせします。 🙏
フィードバックをお寄せいただきありがとうございます。 最初に混乱をお詫びします。 この問題はwebpack-loaderにもあることを指摘したいと思います。 申し訳ありませんが、この問題で混乱を引き起こしました。
改善を試みました。 これは一般的にパーサーを修正しますが、新しい問題が発生し、その理由を理解するのに苦労しています。
テストの例は次のとおりです(以下で詳しく説明します)
Object {
+ "attributeType": undefined,
"kind": "condition",
"operator": "=",
"target": "foo",
- "value": "bar",
+ "value": ",b,a,r",
"valueType": "string",
}
エラーは私たちの側にある可能性が高いと思いますが、まだどこにあるのかわかりません。 これは、たとえば次の入力で発生します
categories.id != ("b33f8e3a-f8d1-476f-a595-2615c4b57556")
これは
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")
解析されたとき。
私たちは明らかに手がかりに非常に感謝しますが、そこで私たちをサポートできるかどうかも理解しています。
おっと、私の間違い😨、これはそれを修正する必要があります
unescaped = !'"' value:[^\\0-\\x1F\\x22\\x5C] { return value; }
超迅速な対応をありがとう。 それは役に立ちますが、 SyntaxError: Expected "(", boolean, date, datetime, number, string, or time but "\"" found.
の初期エラーを返すことが多いCLIまたはwebpack-loaderを使用する場合には役立ちません。 たとえば、 not(sku = "123")
またはより複雑な例lineItemTotal(sku = "SKU1" or list contains all (1,2,3), field.name, "third arg") = "10 EUR"
で発生する何か。 それはまだ逃げることと関係があるのでしょうか?
うん、それは二重の脱出のせいであることがわかった。 固定ルールは次のとおりです。
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; }
編集:複雑な例を解析するルールに取り組みたいと思われるかもしれません: lineItemTotal(sku = "SKU1" or list contains all (1,2,3), field.name, "third arg") = "10 EUR"
、それは現在、奇妙な"kind":"condition"
ノードを出力しています
助けとアドバイスをどうもありがとう。 それは私たちが抱えていた問題を解決しているようです。 「状態」ノードに関するアドバイスを調べます。
どういたしまして😄