javascript - 我的编程语言的 Lexer 不会处理 NEWLINE(用 moo js 完成)
问题描述
我正在创建一种新的编程语言,只是为了好玩和了解更基本的语言。我开始用 moo js 编写一个词法分析器,除了 NEWLINE 之外一切都运行良好。我尝试了很多事情,但它不会解决。我什至尝试从 moo js 的文档中复制一段确切的代码,但仍然没有帮助。
词法分析器代码:
const moo = require("moo");
const lexer = moo.compile({
whitespace: /[ \t]+/,
// comment: /\/\/.*?$/,
number: /0|[1-9][0-9]*/,
string: /"(?:\\["\\]|[^\n"\\])*"/,
leftParen: '(',
rightParen: ')',
// keyword: ['while', 'if', 'else', 'moo', 'cows'],
assignmentOp: "=",
identifier: /[a-zA-Z_][a-zA-Z0-9_]*/,
newline: { match: /\n/, lineBreaks: true },
});
module.exports = lexer;
文本词法分析器代码:
const fs = require("fs").promises;
const lexer = require("./lexer");
async function main() {
const code = (await fs.readFile("example1.hin")).toString();
lexer.reset(code);
let token;
while (true) {
token = lexer.next();
if (token) {
console.log("Got token", token);
} else {
break;
}
}
}
main().catch(err => console.log(err.stack));
测试示例:
n = 4
m = 6
解决方案
我也遇到了同样的问题,解决方案是更改新行的正则表达式,因为 Windows 和 Linux 处理换行的方式不同(要了解更多信息,请查看此内容)。你提到的那个:
newline: { match: /\n/, lineBreaks: true },
适用于 Linux
要同时处理两者,请使用此正则表达式:
newline: { match: /\r?\n/, lineBreaks: true },
推荐阅读
- php - 邮件类未在电子邮件中使用正确的“发件人”
- node.js - 在 NodeJs 中使用 if(==) 运算符检查来自 MongoDb 的文档
- python - 尝试 pip install multiparse for Python 2.7 时出现“ImportError: No module named parse”
- php - 提交输入日期后部分为空 $_POST
- csound - CSound 忽略 0dbfs 分配并立即终止
- node.js - 为什么我不能在 crontab 中运行 node.js 文件?
- javascript - 仅使用 Javascript 或 nodejs 上传图像以进行客户端修改?
- javascript - 如果其他行较小,CSS Grid 一列具有最大高度,但如果其他行较大,则调整更高
- javascript - 检测 MIDI 连接事件
- python - 解释器说 n = list[0] 是一个列表