首页 > 解决方案 > 我的编程语言的 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

标签: javascriptcompiler-errorsnewlinemoo

解决方案


我也遇到了同样的问题,解决方案是更改新行的正则表达式,因为 Windows 和 Linux 处理换行的方式不同(要了解更多信息,请查看此内容)。你提到的那个:

newline: { match: /\n/, lineBreaks: true },

适用于 Linux

要同时处理两者,请使用此正则表达式:

newline: { match: /\r?\n/, lineBreaks: true },

推荐阅读