Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何用JavaScript实现一门编程语言 - 字符流 #10

Open
llwanghong opened this issue Apr 28, 2023 · 0 comments
Open

如何用JavaScript实现一门编程语言 - 字符流 #10

llwanghong opened this issue Apr 28, 2023 · 0 comments

Comments

@llwanghong
Copy link
Owner

llwanghong commented Apr 28, 2023

整篇译文的目录章节如下:

字符流(Character Stream)

本节算是最小的一部分。我们将要创建一个“流对象”,该对象提供了从字符串读取字符的一些操作。流对象实现了下面4个方法:

  • peek() — 返回下一个字符,但是不会将其从流中删除。
  • next() — 返回下一个字符,同时将其从流中删除。
  • eof() — 当且仅当流中没有更多字符时返回true。
  • croak(msg) — 抛出错误throw new Error(msg).

之所以包括最后一个方法,是因为流可以很容易地追踪当前位置(如行/列),这对错误信息的显示很重要。

你可以根据自己的需要任意添加其它的方法,上述方法对于本教程已经足够了。

字符输入流是与字符打交道的,所以*next()/peek()*等函数的返回值都是字符(JS中没有字符char类型,就是单一字符的字符串)。

下面是流对象的完整代码, 这里称其为InputStream。足够简单,理解起来应该不会有问题。

function InputStream(input) {
    var pos = 0, line = 1, col = 0;
    return {
        next  : next,
        peek  : peek,
        eof   : eof,
        croak : croak,
    };
    function next() {
        var ch = input.charAt(pos++);
        if (ch == "\n") line++, col = 0; else col++;
        return ch;
    }
    function peek() {
        return input.charAt(pos);
    }
    function eof() {
        return peek() == "";
    }
    function croak(msg) {
        throw new Error(msg + " (" + line + ":" + col + ")");
    }
}

请注意它不是一个标准的类对象(通过new创建的那种)。你只需要通过var stream = InputStream(string)就可以得到一个流对象。

接下来,我们将基于流对象去抽象实现另外一个功能:分词器(the tokenizer)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant