我使用pegjs来定义允许定义新类型的语法。那么,在定义这些类型之后,我如何识别它们呢?我有一个产品,它定义了内置的类型。
BuiltInType
= "int"
/ "float"
/ "string"
/ TYPE_NAME
但对于最后一个我该怎么办呢?在源代码中定义字符串之前,我不知道哪些字符串是类型名称。
在传统的解析方法中,语法分析器和解析器同时存在,解析器将将类型名称添加到表中,而lexer将使用此表来确定是否返回特定令牌的TYPE_NAME或标识符。但是pegjs没有这种分离。
发布于 2017-01-26 15:05:22
您是对的,您不能(很容易)动态地修改pegjs生成的解析器,而不知道它的内部结构。但是,从标准LALR中损失的是,在解析器规则本身中穿插JavaScript代码。
为了实现目标,您需要识别新类型(在上下文中),并保留它们供以后使用,如下所示:
{
// predefined types
const types = {'int':true, 'float':true, 'string':true}
// variable storage
const vars = {}
}
start = statement statement* {
console.log(JSON.stringify({types:types,vars:vars}, null, 2))
}
statement
= WS* typedef EOL
/ WS* vardef EOL
typedef "new type definition" // eg. 'define myNewType'
= 'define' SP+ type:symbol {
if(types[type]) {
throw `attempted redefinition of: "${type}"`
}
types[type]=true
}
// And then, when you need to recognize a type, something like:
vardef "variable declaration" // eg: 'let foo:myNewType=10'
= 'let' SP+ name:symbol COLON type:symbol SP* value:decl_assign? {
if(!types[type]) {
throw `unknown type encountered: ${type}`
}
vars[name] = { name: name, type:type, value: value }
}
decl_assign "variable declaration assignment"
= '=' SP* value:number {
return value
}
symbol = $( [a-zA-Z][a-zA-Z0-9]* )
number = $( ('+' / '-')? [1-9][0-9]* ( '.' [0-9]+ )? )
COLON = ':'
SP = [ \t]
WS = [ \t\n]
EOL = '\n'
当被要求解析时:
define fooType
let bar:fooType = 1
将印刷:
{
"types": {
"int": true,
"float": true,
"string": true,
"fooType": true
},
"vars": {
"bar": {
"name": "bar",
"type": "fooType",
"value": "1"
}
}
}
https://stackoverflow.com/questions/41027375
复制相似问题