简体   繁体   English

如何使用 Peg.js 打开文件?

[英]How open files with Peg.js?

How can I read the file within my language?我怎样才能用我的语言阅读文件?

I am trying to understand how languages ​​work.我试图了解语言是如何工作的。 I would like to know how to create a simple grammar to read files using Peg.js .我想知道如何使用Peg.js创建一个简单的语法来读取文件。
In Python it is something like this在 Python 中它是这样的

f= open("testfile.txt","w+")

Grammar Example in Peg.js Peg.js 中的语法示例

{
   var keywords = ["f=", "open"];
}

Expression =
    word:$(Word) { return { word: word } } /
    keyword:$(Keyword) { return { keyword: keyword } }

// Word will match everything except "f" and "open"
Word = word:$([a-zA-Z]+) &{ return !keywords.includes(word) }

Keyword = [a-zA-Z]+

start
  = f open symbol

open
  = attribute:',"w+"'? __ { return write; }
  = attribute:'include'? __ { return include; }

include
  = include : "'_ exp:[a-zA-Z]+ _'" _ { return include; }

symbol
  = '("' _ exp:[a-zA-Z]+ _ '")' { return [ exp.join('') ]; }

// optional whitespace
_  = [ \t\r\n]*

// mandatory whitespace
__ = [ \t\r\n]+

But I get this error:但我收到此错误:

Line 21, column 3: Expected "/", ";", comment, end of input, end of line, identifier, or whitespace but "=" found.第 21 行,第 3 列:应为“/”、“;”、注释、输入结束、行结束、标识符或空格,但找到了“=”。

Sample: Peg.js示例: Peg.js

f= open("testfile.txt","w+")

You're getting the syntax error because your definition of open contains two = s.您收到语法错误,因为您的open定义包含两个= s。 I assume you want the second one to be a / instead.我假设您希望第二个成为/ Then open would match either the string ,"w+" (or nothing) or include .然后open将匹配字符串,"w+" (或什么都不匹配)或include

That's not the only issue in your code though.不过,这并不是您代码中的唯一问题。 Here are some others I've noticed:以下是我注意到的其他一些:

  • Your first three rules and the other rules don't use each other.您的前三个规则和其他规则不相互使用。 So if you're using Expression as your start rule (the default as it comes first), only the first three rules will matter.因此,如果您使用Expression作为您的开始规则(默认为先),则只有前三个规则很重要。 And if you use start as the start rule, the first three rules won't matter at all.如果您使用start作为开始规则,则前三个规则根本无关紧要。
  • You list "f=" in your array of keywords and then check whether a string matching [a-zA-Z]+ is inside that array.您在关键字数组中列出"f=" ,然后检查匹配[a-zA-Z]+的字符串是否在该数组中。 But f= does not match that pattern, so having it in the array is pointless.但是f=与该模式不匹配,因此将它放在数组中毫无意义。
  • You define start as f open symbol , but f isn't defined anywhere.您将start定义为f open symbol ,但f未在任何地方定义。
  • "'_ exp:[a-zA-Z]+ _'" matches the literal string '_ exp:[a-zA-Z]+ _' . "'_ exp:[a-zA-Z]+ _'"匹配文字字符串'_ exp:[a-zA-Z]+ _' That is almost certainly not what you want.这几乎肯定不是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM