我的编程语言的 Lexer 不会处理 NEWLINE(用 moo js 完成)

My programing language's Lexer will not process NEWLINE (done with 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 处理换行符的方式不同( To find out more. check this out )。你提到的那个:

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

适用于 Linux

要对两者都起作用,请使用此正则表达式:

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