这是用户在 2024-5-8 9:38 为 https://ics.uci.edu/~thornton/ics33/ProjectGuide/Project3/ 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

ICS 33 Spring 2024 2024 年春季 ICS 33
Project 3: Why Not Smile?
项目 3:为什么不微笑?

Due date and time: Monday, May 20, 11:59pm
截止日期和时间:5 月 20 日星期一,晚上 11:59

Git repository: https://ics.uci.edu/~thornton/ics33/ProjectGuide/Project3/Project3.git
Git 存储库:https://ics.uci.edu/~thornton/ics33/ProjectGuide/Project3/Project3.git


Introduction 介绍

When I was a young kid, one of my teachers introduced me to a computer for the first time; it was a state of the art (in those days) personal computer called a Radio Shack TRS-80 Model I. First, I played little math games and messed around with other new-fangled educational tools from 1980; the state of the art wasn't much then, but it was fun and new, and felt alive with possibility.
当我还是个小孩的时候,我的一位老师第一次向我介绍了一台计算机;那是一台当时最先进的个人电脑,名为 Radio Shack TRS-80 Model I。起初,我玩一些小数学游戏,还尝试了一些来自 1980 年的新奇教育工具;那时的技术水平并不高,但很有趣,充满了新奇感,让人感觉到无限可能。

Booting up a TRS-80 took the user directly into the equivalent of a Python shell; you could load programs from external storage like floppy disks or cassette tapes, but the computer's default mode was an environment for writing programs. My teacher asked me if I wanted to learn how to write my own programs, which I thought sounded like a great idea, though I had no idea how to do it. So, I opened up a book of his about the TRS-80's primary programming language, which was called BASIC, which was a good teaching and learning tool for its day: versatile and easy to start with, much like Python is today. I typed in a short program that asked a user for a number of hits and a number of at-bats and printed out a batting average (foreshadowing my later interest in baseball, though I didn't know what it meant at the time). I ran the program, tried it out, and I was mesmerized; the computer did exactly what I asked it to, exactly the way I asked it to. I was hooked. Over forty years later, I still am.
启动 TRS-80 会直接进入类似 Python shell 的界面;你可以从外部存储设备如软盘或磁带加载程序,但计算机的默认模式是一个编写程序的环境。我的老师问我是否想学习如何编写自己的程序,我觉得这听起来是个好主意,尽管我不知道该如何做。于是,我打开了他关于 TRS-80 主要编程语言 BASIC 的一本书,这是一个很好的教学和学习工具:当时多才多艺且易于入门,就像今天的 Python 一样。我输入了一个简短的程序,要求用户输入击中次数和上场次数,然后输出击球率(预示着我后来对棒球的兴趣,尽管当时我不知道这意味着什么)。我运行了程序,尝试了一下,我被迷住了;计算机完全按照我的要求、按照我要求的方式运行。我着了迷。四十多年后,我依然如此。

A natural progression of one's curiosity about programming revolves around the question of how to implement one's own programming language. Where do they come from? How are they built? While we won't be able to tackle these questions in too much depth — there are at least three different courses in our undergraduate curriculum that cover aspects of this — this project will ask you to begin exploring them. For that purpose, I've designed a considerably limited (and somewhat different) version of BASIC called Grin, which supports a small handful of statements. You'll be building a Grin interpreter, a program written in Python that takes a Grin program as its input, executes the Grin program, then shows its output. (This may sound a little mind-bending, but it's not as crazy as it sounds. The Python interpreter you've been using was most likely written in a language other than Python; the most popular one is written in a language called C.)
一个人对编程的好奇心自然而然地发展到如何实现自己的编程语言的问题。它们从哪里来?它们是如何构建的?虽然我们无法深入探讨这些问题 —— 我们本科课程中至少有三门不同的课程涵盖了这方面的内容 —— 但这个项目将要求您开始探索这些问题。为此,我设计了一个名为 Grin 的相当有限(并且略有不同)版本的 BASIC,它支持少量语句。您将构建一个 Grin 解释器,这是一个用 Python 编写的程序,它以 Grin 程序作为输入,执行 Grin 程序,然后显示其输出。(这听起来有点令人费解,但实际上并没有那么疯狂。您一直在使用的 Python 解释器很可能是用 Python 以外的语言编写的;最流行的一个是用一种叫做 C 的语言编写的。)

In the process of building your interpreter, you'll gain experience in a few areas that will stretch your abilities:
在构建您的解释器的过程中,您将在一些领域获得经验,这将拓展您的能力:


The Grin language 格林语

The precise requirements for your interpreter are discussed later in this write-up, but we'll first need to agree on the definition of the Grin language that your interpreter will implement. Grin is a programming language, though its design is quite different from Python's, so we'll first need to acquaint ourselves with how it works. Given a Grin program, you'll need to know, first and foremost, what its output is meant to be.
在本文稍后讨论您的解释器的精确要求,但我们首先需要就您的解释器将要实现的 Grin 语言的定义达成一致。Grin 是一种编程语言,尽管其设计与 Python 的设计有很大不同,因此我们首先需要了解它的工作原理。给定一个 Grin 程序,您首先需要知道它的输出应该是什么。

A Grin program is a sequence of statements, one per line. Here's an example of a Grin program:
一个 Grin 程序是一系列语句,每行一个。这是一个 Grin 程序的示例:

LET MESSAGE "Hello Boo!"
PRINT MESSAGE
.

Each line contains exactly one statement (i.e., there can be no blank lines). Grin assigns a line number to each of the statements, where the first statement in the program is numbered 1, the second statement is numbered 2, and so on. There is no predefined limit on the number of statements in a Grin program. Execution of a Grin program always begins at line number 1. The last line contains only a dot (.) and nothing else, as a way to mark that the program has ended; it's not a statement, but any subsequent lines of text in the Grin program after that end-of-program marker are ignored.
每行都只包含一个语句(即不能有空行)。Grin 为每个语句分配一个行号,程序中的第一个语句编号为 1,第二个语句编号为 2,依此类推。Grin 程序中的语句数量没有预定义的限制。Grin 程序的执行总是从行号 1 开始。最后一行只包含一个句点(.),没有其他内容,作为标记程序已结束的方式;它不是一个语句,但在该结束程序标记之后的 Grin 程序中任何后续文本行都会被忽略。

The program above consists of two statements. The first one stores the text Hello Boo! into a variable named MESSAGE, then the second one prints the value of that same variable. The output of the program is what you'd expect, given that description.
上面的程序由两个语句组成。第一个语句将文本 Hello Boo! 存储到名为 MESSAGE 的变量中,然后第二个语句打印相同变量的值。根据该描述,程序的输出是您所期望的。

Hello Boo!

Lexical rules 词汇规则

Like most programming languages (including Python), a Grin program is made up of a sequence of lexemes, which is a fancy-sounding term for a sequence of characters that combine together with a single meaning and comprise one of the indivisible "atoms" in the language, similar to the role that words play in sentences written in natural languages like English. Programming languages that are written textually generally define a set of lexical rules that specify which lexemes are valid and how to derive a meaning for each of them; Grin is no different, in that respect, so we'll need to start our journey with Grin by acquainting ourselves with those rules.
像大多数编程语言(包括 Python)一样,Grin 程序由一系列词素组成,这是一个花哨的术语,表示一系列字符结合在一起具有单一含义,并构成语言中不可分割的“原子”之一,类似于自然语言(如英语)中句子中单词的作用。通常以文本形式编写的编程语言通常定义一组词法规则,指定哪些词素是有效的,以及如何为每个词素推导含义;在这方面,Grin 并无不同,因此我们需要通过熟悉这些规则来开始我们的 Grin 之旅。

Grin programs are made up of the following kinds of lexemes.
笑容程序由以下类型的词素组成。

Some examples of Grin lexemes and their meanings follow.
一些 Grin 词汇及其含义的例子如下。

0                   # Integer literal (zero)
13                  # Integer literal (positive)
-18                 # Integer literal (negative)
0.0                 # Floating-point literal (zero)
11.75               # Floating-point literal (positive)
-3.0                # Floating-point literal (negative)
""                  # String literal (an empty one)
"Boo!"              # String literal (containing four characters)
A                   # Identifier
BOO                 # Identifier
THIS1ISTHELAST1     # Identifier
IF                  # Keyword
GOTO                # Keyword
=                   # Comparison operator
>=                  # Comparison operator
:                   # Label marker
.                   # End-of-program marker

Labels 标签

Any statement in a Grin program can begin with a label, which is a name that can be used to refer to that statement elsewhere in the program without having to rely on knowing its line number. Labels appear at the beginning of a line, and are made up of an identifier followed by a colon.
Grin 程序中的任何语句都可以以标签开头,标签是一个名称,可用于在程序的其他地方引用该语句,而无需依赖于知道其行号。标签出现在一行的开头,由标识符后跟冒号组成。

        LET A 3
        PRINT A
        GOSUB "CHUNK"
        PRINT A
        PRINT B
        GOTO "FINAL"
CHUNK:  LET A 4
        LET B 6
        RETURN
FINAL:  PRINT A
        .

In the program above, two statements have labels on them: LET A 4 is labeled as CHUNK and the last statement is labeled as FINAL.
在上面的程序中,两个语句带有标签: LET A 4 标记为 CHUNK ,最后一个语句标记为 FINAL

Spacing 空格

One of the features of Python's syntax is that the way you space your program — indention, empty lines, and so on — has an effect on your program's meaning. Grin, in that sense, is different. Grin programs cannot have blank lines in them, each statement must be on its own line, and at least one space is required to separate lexemes that would otherwise be combined, but the specific amount and placement of blank space between the lexemes on each line is otherwise irrelevant. So, the following program is legal and equivalent Grin to the previous one shown, though obviously there's a lot to be said for using spacing to make a program's meaning more obvious to a human reader.
Python 语法的一个特点是,程序中的空格、空行等方式会影响程序的含义。而 Grin 在这方面是不同的。Grin 程序中不能有空行,每个语句必须独占一行,且至少需要一个空格来分隔本应合并的词元,但每行词元之间的空格数量和位置是无关紧要的。因此,下面的程序是合法的,与之前显示的程序等效,尽管显然使用空格来使程序的含义对人类读者更明显是有很多好处的。

            LET        A    3
   PRINT        A
      GOSUB    "CHUNK"
        PRINT    A
  PRINT   B
     GOTO         "FINAL"
         CHUNK   :  LET A 4
  LET   B                            6
              RETURN
  FINAL:     PRINT    A
    .

Variables 变量

A Grin program can utilize variables to store values that can be accessed again (or modified) later. Each variable is named by an identifier. Variables do not need to have values assigned to them before they are used, and any variable that is used before it is assigned has the integer value 0.
Grin 程序可以利用变量来存储值,这些值可以在以后再次访问(或修改)。每个变量都由标识符命名。变量在使用之前不需要分配值给它们,任何在分配之前使用的变量都具有整数值 0。

The primary way to change the value of a variable is with a LET statement. A LET statement changes the value of one variable, by either assigning it a literal value or the value of another variable.
更改变量值的主要方法是使用 LET 语句。 LET 语句通过分配文字值或另一个变量的值来更改一个变量的值。

You can print the value of a variable to the output by using a PRINT statement. A PRINT statement prints the value of one variable, followed by a newline.
您可以使用 PRINT 语句将变量的值打印到输出。 PRINT 语句打印一个变量的值,然后换行。

So, consider the following short Grin program:
因此,请考虑以下简短的 Grin 程序:

LET NAME "Boo"
LET AGE 13.015625
PRINT NAME
PRINT AGE
.

Its output would be:
它的输出将是:

Boo
13.015625

The formatting rules used when printing the values of variables depend on their types.
打印变量值时使用的格式规则取决于它们的类型。

Reading input 读取输入

Grin includes two statements for reading input from the console:
Grin 包含两个语句,用于从控制台读取输入:

Either way, the syntax is mostly the same: We write INNUM or INSTR, followed by the name of the variable into which you want to read the input value. A short Grin program demonstrates the idea.
无论哪种方式,语法大致相同:我们写 INNUMINSTR ,然后是要读取输入值的变量名称。一个简短的 Grin 程序演示了这个想法。

PRINT "Number:"
INNUM X
ADD X 7
PRINT X
.

This program prints output and also reads input, so let's imagine what that might look like when we execute it.
这个程序会输出结果并且读取输入,让我们想象一下当我们执行它时会是什么样子。

    Number:
    ​11​
    18

First, the PRINT statement on line 1 will have printed Number:. Next, a line of input will have been read and treated, in this case, as the integer 11, which will be stored in the variable named X. We'd then add 7 to X, causing its value to become the integer 18. Finally, we'd print X's value, which causes 18 to be printed.
首先,在第 1 行上的 PRINT 语句将打印 Number: 。接下来,将读取并处理一行输入,本例中将其视为整数 11 ,将存储在名为 X 的变量中。然后,我们将 7 添加到 X ,导致其值变为整数 18 。最后,我们将打印 X 的值,这将导致 18 被打印。

The precise rules for INNUM need to be specified, though, since not all inputs are valid.
对于 INNUM ,需要明确规定准确的规则,因为并非所有输入都是有效的。

Meanwhile, the precise rules for INSTR are much simpler, because not much can go wrong. We read a line of text, then store the contents of that line (without a trailing newline) into the given variable. Any line of text, including empty lines or very long lines, is permitted, so there are no error conditions to consider.
与此同时, INSTR 的精确规则要简单得多,因为不太可能出错。我们读取一行文本,然后将该行的内容(不包括尾随换行符)存储到给定变量中。允许任何文本行,包括空行或非常长的行,因此没有需要考虑的错误条件。

Control flow and how to alter it
控制流程及如何更改它

A Grin program is executed one statement at a time, beginning at line number 1. Ordinarily, execution proceeds forward, so that line 1 will execute first, followed by line 2, followed by line 3, and so on. Execution continues until either an END statement is reached, or until execution proceeds beyond the last statement in the program.
一个 Grin 程序逐条执行,从第 1 行开始。通常情况下,执行是向前进行的,因此第 1 行将首先执行,然后是第 2 行,然后是第 3 行,依此类推。执行会一直持续,直到达到 END 语句,或者执行超出程序中的最后一个语句。

Like most programming languages, Grin makes it possible to write programs that execute out of sequence, though the mechanisms are a bit more primitive than they are in a language like Python. A GOTO statement causes execution to "jump" immediately forward or backward by the given number of lines. For example, the statement GOTO 4 jumps execution to the line number that's 4 greater than the current one. Here's an example Grin program that uses GOTO:
与大多数编程语言一样,Grin 使得编写可以按照非顺序执行的程序成为可能,尽管其机制比像 Python 这样的语言更为原始。一个 GOTO 语句会导致执行立即向前或向后跳转给定行数。例如,该语句 GOTO 4 会将执行跳转到比当前行数大 4 的行号。以下是一个使用 GOTO 的示例 Grin 程序:

LET A 1
GOTO 2
LET A 2
PRINT A
.

In this program, line 1 is executed first, setting the variable A's value to 1. Then the GOTO statement will immediately jump execution of the program to line 4 — the GOTO statement is on line 2, and two lines beyond that is line 4 — skipping the second LET. Line 4 prints the value of A, which is still 1. So, the output of the program is simply 1.
在这个程序中,首先执行第 1 行,将变量 A 的值设置为 1。然后 GOTO 语句将立即将程序的执行跳转到第 4 行 — GOTO 语句在第 2 行,再往后两行是第 4 行 — 跳过第二个 LET 。第 4 行打印 A 的值,仍然是 1。因此,程序的输出就是 1

A GOTO statement may jump either forward or backward, meaning that the following program is a legal Grin program. See if you can figure out what its output would be. (Remember that the value of a variable that hasn't yet been assigned with a LET is 0.)
GOTO 语句可以向前或向后跳转,这意味着以下程序是合法的 Grin 程序。看看你能否弄清楚它的输出是什么。(请记住,尚未使用 LET 分配值的变量的值为 0。)

LET Z 5
GOTO 5
LET C 4
PRINT C
PRINT Z
END
PRINT C
PRINT Z
GOTO -6
.

Alternatively, GOTO statements can specify a string literal specifying a label instead of a line number, in which case execution jumps to the line that is marked with that label. A Grin program equivalent to the previous one, but that uses labels instead of line numbers, follows.
或者, GOTO 语句可以指定一个字符串文字来指定一个标签,而不是一个行号,这种情况下,执行会跳转到带有该标签的行。一个等价于前一个程序的 Grin 程序,但是使用标签而不是行号,如下所示。

        LET Z 5
        GOTO "CZ"
CCZ:    LET C 4
        PRINT C
        PRINT Z
        END
CZ:     PRINT C
        PRINT Z
        GOTO "CCZ"
        .

GOTO statements can cause the program to terminate with an error message in a few circumstances.
GOTO 语句在某些情况下可能会导致程序终止并显示错误消息。

Finally, it should be noted that GOTO statements can use variables to specify their target, as long as the variable contains either an integer or a string value, in which case that value is treated the same as it would have been if it had been specified literally.
最后,应该注意到 GOTO 语句可以使用变量来指定它们的目标,只要变量包含整数或字符串值,那么该值将被视为与直接指定的值相同。

        LET Z 1
        LET C 11
        LET F 4
        LET B "ZC"
        GOTO F
ZC:     PRINT Z
        PRINT C
        END
CZ:     PRINT C
        PRINT Z
        GOTO B
        .

When the target of a GOTO is a variable containing something other than an integer or a string, that, too, terminates the interpreter with an error message.
GOTO 的目标是一个包含除整数或字符串之外的其他内容的变量时,解释器也会显示错误消息并终止。

Arithmetic operations 算术运算

Grin provides the typical arithmetic operations that can be performed on variables: addition, subtraction, multiplication, and division. Each operation is provided as a statement that updates the value of the given variable by combining it with another value, making it equivalent to operators like +=, -=, etc., in Python. The first operand must be the name of a variable; the second can either be a literal value or the name of a variable. Here are examples of their use on integers:
Grin 提供了可以在变量上执行的典型算术运算:加法、减法、乘法和除法。每个操作都作为一个语句提供,通过将给定变量的值与另一个值组合来更新它,使其等效于 Python 中的运算符 +=-= 等。第一个操作数必须是一个变量的名称;第二个可以是一个文字值或一个变量的名称。以下是它们在整数上的使用示例:

LET A 4
ADD A 3
PRINT A
LET B 5
SUB B 3
PRINT B
LET C 6
MULT C B
PRINT C
LET D 8
DIV D 2
PRINT D
.

In the example above, the ADD statement adds 3 to the value of A, storing the result in A. So, printing A will display 7 on the output. The output of the entire program above is as follows.
在上面的示例中, ADD 语句将 3 添加到 A 的值中,并将结果存储在 A 中。因此,打印 A 将在输出上显示 7 。上面整个程序的输出如下。

7
2
12
4

Like Python, arithmetic operations have a different meaning when operating on different types of values. Note, though, that some of the rules in Grin are different from the ones you learned in Python. (These are among the subtleties you'll find that change from one programming language to another.)
就像 Python 一样,对不同类型的值进行运算时,算术运算具有不同的含义。请注意,Grin 中的一些规则与您在 Python 中学到的规则不同。(这些是您会发现从一种编程语言到另一种编程语言会发生变化的微妙之处之一。)

Statement Type (in variable) 类型(在变量中) Type (in operand) 类型(在操作数中) Result Type 结果类型 Example
ADD Integer Integer Integer 11 + 7 = 18
ADD Float Float Float 11.5 + 7.0 = 18.5
ADD Integer Float Float 11 + 7.5 = 18.5
ADD Float Integer Float 11.5 + 7 = 18.5
ADD String String String "Boo" + "lean" = "Boolean"
Boo" + "lean" = "布尔值
SUB Integer Integer Integer 18 - 7 = 11
SUB Float Float Float 18.5 - 7.0 = 11.5
SUB Integer Float Float 18 - 6.5 = 11.5
SUB Float Integer Float 18.5 - 7 = 11.5
MULT Integer Integer Integer 5 * 11 = 55
MULT Float Float Float 3.5 * 12.0 = 42.0
MULT Integer Float Float 3 * 12.5 = 37.5
MULT Float Integer Float 3.5 * 12 = 42.0
MULT String Integer String "Boo" * 3 = "BooBooBoo"
MULT Integer String String 3 * "Boo" = "BooBooBoo"
DIV Integer Integer Integer 7 / 2 = 3
DIV Float Float Float 7.5 / 3.0 = 2.5
DIV Integer Float Float 7 / 2.0 = 3.5
DIV Float Integer Float 7.0 / 2 = 3.5

Any combination of types not listed above (e.g., dividing a float by a string) is a runtime error, which means that the program terminates with an error message. Additionally, there are two scenarios that are runtime errors, even though the types are permissible.
任何未列出的类型组合(例如,将浮点数除以字符串)都会导致运行时错误,这意味着程序将以错误消息终止。此外,即使类型是允许的,也有两种会导致运行时错误的情况。

Subroutines 子程序

There are no functions or methods in Grin, but there is a simplified mechanism called a subroutine. A subroutine is a sequence of Grin statements that can be "called" by executing a GOSUB statement. GOSUB is much like GOTO; it causes execution to jump either by a given number of lines or to a label. However, GOSUB also causes Grin to remember where it jumped from. Subsequently, when a RETURN statement is reached, execution continues at the line following the GOSUB statement that caused the jump. Here's an example:
Grin 中没有函数或方法,但有一个简化的机制称为子程序。子程序是一系列 Grin 语句,可以通过执行 GOSUB 语句来“调用”。 GOSUB 类似于 GOTO ;它会导致执行跳转到指定行数或标签。然而, GOSUB 还会让 Grin 记住跳转的位置。随后,当达到 RETURN 语句时,执行会继续到导致跳转的 GOSUB 语句后面的行。这里是一个示例:

LET A 1
GOSUB 4
PRINT A
PRINT B
END
LET A 2
LET B 3
RETURN
.

In the program above, line 1 is executed first, setting the value of A to 1. Next, a GOSUB statement is reached. Execution jumps to line 6 (4 greater than the line 2 it appears on), but Grin also remembers that when a RETURN statement is reached, execution should jump back to the line following the GOSUB — in this case, line 3. Line 6 is executed next, setting A to 2, then line 7 sets B to 3. Now, we reach a RETURN statement, causing execution to jump back to the line number that we're remembering — line 3. Line 3 prints the value of A (which is 2), then line 4 prints the value of B (which is 3). Next, we reach line 5, which is an END statement, so the program ends.
在上面的程序中,首先执行第 1 行,将 A 的值设置为 1 。接下来,到达一个 GOSUB 语句。执行跳转到第 6 行(4 大于它所在的第 2 行),但 Grin 也记住了当到达一个 RETURN 语句时,执行应该跳回到 GOSUB 后面的行 — 在这种情况下,是第 3 行。接着执行第 6 行,将 A 设置为 2 ,然后第 7 行将 B 设置为 3 。现在,我们到达一个 RETURN 语句,导致执行跳回到我们记住的行号 — 第 3 行。第 3 行打印 A 的值(即 2 ),然后第 4 行打印 B 的值(即 3 )。接下来,到达第 5 行,这是一个 END 语句,因此程序结束。

Subroutines can be used very similarly to Python functions or methods, except they do not take parameters or return a value. Consider the following example, which contains a subroutine that prints the values of A, B, and C each time it's called:
子程序可以与 Python 函数或方法非常相似地使用,只是它们不接受参数或返回值。考虑以下示例,其中包含一个子程序,每次调用时都会打印 ABC 的值:

           LET A 3
           GOSUB "PRINTABC"
           LET B 4
           GOSUB "PRINTABC"
           LET C 5
           GOSUB "PRINTABC"
           LET A 1
           GOSUB "PRINTABC"
           END
PRINTABC:  PRINT A
           PRINT B
           PRINT C
           RETURN
           .

Subroutines can call other subroutines, meaning that two or more GOSUBs may be reached before a RETURN is reached. The rules for this are very similar to functions that call other functions in Python; for each GOSUB that is reached, Grin will remember the line to which it should return. When a RETURN is reached, execution will move to the line remembered from the most recent GOSUB. Here's an example.
子程序可以调用其他子程序,这意味着在到达 RETURN 之前可能会到达两个或更多个 GOSUB 。这方面的规则与 Python 中调用其他函数的规则非常相似;对于到达的每个 GOSUB ,Grin 都会记住应返回的行。当到达 RETURN 时,执行将移动到最近 GOSUB 记住的行。以下是一个示例。

LET A 1
GOSUB 5
PRINT A
END
LET A 3
RETURN
PRINT A
LET A 2
GOSUB -4
PRINT A
RETURN
.

In this example, execution begins at line 1 by setting the variable A to 1. Next, we jump to line 7 with a GOSUB, but remember that we should jump back to line 3 when we encounter a RETURN. Line 7 prints A (which is 1), then line 8 changes A's value to 2. Now we've reached line 9, which is another GOSUB statement. At this point, execution will jump to line 5, but we'll also need to remember to jump back to the line following this GOSUB — line 10 — when we reach a RETURN. But we also need to remember the line from the previous GOSUB — line 3.
在这个例子中,执行从第 1 行开始,通过将变量 A 设置为 1 。接下来,我们使用 GOSUB 跳转到第 7 行,但请记住,当遇到 RETURN 时,我们应该跳回第 3 行。第 7 行打印 A (即 1 ),然后第 8 行将 A 的值更改为 2 。现在我们到达第 9 行,这是另一个 GOSUB 语句。在这一点上,执行将跳转到第 5 行,但当我们到达 RETURN 时,我们还需要记住跳回到这个 GOSUB 后面的一行——第 10 行。但我们还需要记住前一个 GOSUB 的行——第 3 行。

Line 5 sets A to 3, then we encounter our first RETURN statement. We're remembering two lines — line 3 and line 10. But line 10 is the most recently remembered line, so execution jumps to line 10. Line 10 prints A (which is 3). Now, we encounter another RETURN statement on line 11. We're remembering the line 3 from the first GOSUB. So, execution jumps to line 3, printing A (which is still 3), then ending the program on line 4.
第 5 行将 A 设置为 3 ,然后我们遇到第一个 RETURN 语句。我们记住了两行——第 3 行和第 10 行。但第 10 行是最近记住的行,所以执行跳转到第 10 行。第 10 行打印 A (即 3 )。现在,我们在第 11 行遇到另一个 RETURN 语句。我们记住了第一个 GOSUB 的第 3 行。因此,执行跳转到第 3 行,打印 A (仍然是 3 ),然后在第 4 行结束程序。

So, the output of this program is as follows.
因此,此程序的输出如下。

1
3
3

Like GOTO statements, GOSUB statements are not permitted to jump beyond the boundaries of the program or to non-existent labels, nor can they jump to the same line they came from. If such a GOSUB statement is encountered while a program is executed, the program terminates with an error message.
GOTO 语句一样, GOSUB 语句不允许跳出程序边界或跳转到不存在的标签,也不能跳转到它们所在的同一行。如果在执行程序时遇到这样的 GOSUB 语句,程序将以错误消息终止。

It is also an error for a RETURN statement to be encountered when there has been no previous GOSUB. The Grin program will immediately terminate and print an error message in this case, as well.
当之前没有 GOSUB 时遇到 RETURN 语句也是一个错误。在这种情况下,Grin 程序将立即终止并打印错误消息。

Conditionally altering control flow
有条件地改变控制流程

Grin provides no precise equivalent of Python's if statement, but it does offer a form of conditionality, in the sense that both GOTO and GOSUB statements can operate conditionally. Optionally, after the target of a GOTO or GOSUB, we can write the word IF, followed by a comparison expression that compares two values — literal values or the values in variables — with the result of that comparison determining whether the statement should cause execution to jump.
Grin 没有 Python 的 if 语句的精确等价物,但它提供了一种条件性形式,即 GOTOGOSUB 语句都可以有条件地运行。在 GOTOGOSUB 的目标之后,我们可以选择写上单词 IF ,然后是一个比较表达式,用于比较两个值(文字值或变量中的值),比较的结果决定该语句是否应该导致执行跳转。

LET A 3
LET B 5
GOTO 2 IF A < 4
PRINT A
PRINT B
.

In the program above, the variables A and B are given the values 3 and 5, respectively. A GOTO statement compares A to 4. Since A is less than 4, the GOTO statement jumps to line 5 — 2 lines beyond itself — and B is printed, but A is not. The output of the program is as follows.
在上面的程序中,变量 AB 分别被赋值为 35 。一个 GOTO 语句将 A 与 4 进行比较。由于 A 小于 4, GOTO 语句跳转到第 5 行 — 超出自身 2 行 — 并打印 B ,但不打印 A 。程序的输出如下。

5

Both GOTO and GOSUB can be executed conditionally in this way. The comparison can use one of these six relational operators.
这种方式可以有条件地执行 GOTOGOSUB 。比较可以使用这六个关系运算符中的一个。

The types of values being compared partly determine the result of their comparison.
被比较的值的类型在一定程度上决定了它们比较的结果。

Comparisons between any other pair of values (e.g., integers to strings) result in runtime errors.
任何其他值对之间的比较(例如,整数与字符串)会导致运行时错误。


Getting started 入门指南

Near the top of this project write-up, you'll find a link to a Git repository that provides the starting point for this project. Using the instructions you followed in Project 0 (in the section titled Starting a new project), create a new PyCharm project using that Git repository; you'll do your work within that PyCharm project.
在这个项目写作的开头附近,您会找到一个指向 Git 存储库的链接,该存储库为这个项目提供了起点。使用您在项目 0 中遵循的说明(标题为“开始一个新项目”的部分),使用该 Git 存储库创建一个新的 PyCharm 项目;您将在该 PyCharm 项目中进行工作。

Acquainting yourself with the provided code
熟悉所提供的代码

There's one bit of good news right off the bat: You aren't implementing this project from scratch. Some of the details have been implemented already, and they've been provided to you in their entirety, including the unit tests used to test them. While you won't need to have an expert understanding of every line of that code, you'll need to gain some familiarity with the "public" parts of it (i.e., you'll need to understand the problems solved by the provided code and how to use it), like you would with the Python libraries you've likely used in your prior coursework.
一开始就有一个好消息:您不需要从头开始实施这个项目。一些细节已经实施过了,并且已经完整地提供给您,包括用于测试它们的单元测试。虽然您不需要对那些代码的每一行都有专家级的理解,但您需要对其“公共”部分(即,您需要理解由提供的代码解决的问题以及如何使用它)有一定的了解,就像您可能在之前的课程中使用过的 Python 库一样。

Once you create your new PyCharm project, you'll notice that they're organized similarly to the code in Project 2, with multiple packages used to separate different areas of the program's functionality.
一旦您创建了新的 PyCharm 项目,您会注意到它们的组织方式与项目 2 中的代码类似,使用多个包来分隔程序功能的不同区域。

Have a look around what's been provided. You'll find that each file contains documentation describing its purpose, and that each one also describes what ways (if any) you'll need to change them, though most of what you'll be writing will be in new files you'll be adding within the grin package and its corresponding test directory.
看看提供的内容。您会发现每个文件都包含描述其目的的文档,并且每个文件还描述了您需要更改的方式(如果有的话),尽管您将要编写的大部分内容将在 grin 软件包及其相应的测试目录中添加的新文件中。


The program 该程序

To satisfy this project's requirements, you'll be building your own Grin interpreter, using the provided code as a starting point. The most basic requirements that your program will need to meet are the following ones.
为了满足该项目的要求,您将构建自己的 Grin 解释器,使用提供的代码作为起点。您的程序需要满足的最基本要求如下。


Designing your interpreter
设计您的口译员

As the size of a program increases, one of the most difficult obstacles that inexperienced programmers face is their ability to keep separate issues isolated from one another, so they can work on one problem, get all the way to the bottom of it, and then move on to another. This is sometimes referred to as separation of concerns, one of the primary strategies for which is to break a large program into a set of smaller pieces. The obvious mechanism for breaking up a program in Python is the use of classes and functions, though the finesse is in deciding where the seams between those classes and functions should be.
随着程序规模的增加,经验不足的程序员面临的最困难的障碍之一是他们保持将不同问题相互隔离的能力,以便他们可以解决一个问题,一直解决到底,然后转移到另一个问题。这有时被称为关注点分离,其中的主要策略之一是将大型程序分解为一组较小的部分。在 Python 中分解程序的明显机制是使用类和函数,尽管关键在于决定这些类和函数之间的接缝应该在哪里。

The temptation, especially for novices, is always to try to think about the complete picture, since this strategy works well for the short programs that you write when you're first starting out. As programs become larger, confusion naturally sets in, as the complete picture can be difficult to keep in your brain all at once. Even moderately small Python programs are typically built out of many interacting parts and encompass a great deal of complexity. My complete Grin interpreter has around a dozen modules and several hundred unit tests. (Yours may have fewer, because I implemented a couple of features that I haven't assigned, but this gives you a rough idea about size.) Now, before you freak out, bear in mind that many of those modules contain relatively short classes, a few relatively short functions, and so on. I opted to write more modules with less code in each, so that I could concentrate my efforts on implementing and testing each one largely in the absence of the others.
诱惑,尤其是对于新手来说,总是试图考虑整体情况,因为这种策略对于刚开始编写的短程序非常有效。随着程序变得更大,混乱自然而然地产生,因为一次性在脑中保持整体情况可能会很困难。即使是相对较小的 Python 程序通常由许多相互作用的部分构成,并包含大量复杂性。我的完整的 Grin 解释器大约有十几个模块和几百个单元测试。(你的可能较少,因为我实现了一些我尚未分配的功能,但这给你一个大致的大小概念。)现在,在你惊慌之前,请记住,许多模块包含相对较短的类、一些相对较短的函数等。我选择编写更多的模块,每个模块的代码较少,这样我就可以集中精力在实现和测试每个模块时,大部分时间不受其他模块的影响。

This project will encourage you to begin thinking about your programs the same way, which will give you the ability to write much larger programs than you could before, as well as enable you to be able to write unit tests at a level of depth you weren't able to do previously.
这个项目将鼓励您以相同的方式开始思考您的程序,这将使您能够编写比以前更大的程序,并使您能够以之前无法做到的深度编写单元测试。

Design requirements 设计要求

As you work on your interpreter, you'll want to keep the following requirements in mind.
在您开发解释器时,您需要牢记以下要求。

We don't have specific requirements about how many modules you'll need to have, or precisely the way you break your program up, but we'll be evaluating whether you've approached the problem in a way that keeps separate concerns separate.
我们对您需要拥有多少模块或者如何精确地拆分程序没有具体要求,但我们将评估您是否以一种保持不同关注点分开的方式来解决问题。

Within your modules, you'll need to look for opportunities to use classes and inheritance wherever appropriate, both because they're topics we've been exploring in some depth in lecture, and because this problem is one that's amenable to being solved with them, since there are behavioral similarities that can be implemented once and reused using inheritance.
在你的模块中,你需要寻找机会在适当的地方使用类和继承,这是因为这些主题是我们在讲座中深入探讨的内容,也因为这个问题适合使用它们来解决,因为有一些行为上的相似之处可以通过继承实现一次并重复使用。

The basic concepts underlying the interpreter
解释器基本概念

While it's certainly not the case that I start every design by thinking about it in its entirety, one way to start thinking about this particular problem is to brainstorm about the concepts that underlie it. You can then think about the way those concepts fit together, and the ways you might be able to keep them separate. In general, separate concepts should be kept separate until they can't be — which might be quite the opposite of the way you've approached design in your past, because it's not a technique that pays off until programs grow to sizes like this one.
尽管并非每次设计都是从整体思考开始,但解决这个特定问题的一种方法是对潜在概念进行头脑风暴。然后,您可以考虑这些概念如何相互配合,以及您可能如何保持它们分开的方式。一般来说,应该保持不同的概念分开,直到它们无法分开为止 — 这可能与您过去的设计方式恰恰相反,因为这种技术直到程序增长到像这样的规模时才会产生回报。

Each of those concepts could potentially be implemented in a module, and by one or more classes. Don't feel as though you need to build an entire design in your head at once; focus instead on one problem that you can isolate from the others, get your head around that problem, implement (and test) something that you think solves it, and move forward from there. Allow yourself the freedom to be wrong sometimes — not every design idea will pan out, but when you have Git backing you up, you can give up on a bad idea by simply rolling back your changes to the most recent "stable ground" commit.
这些概念中的每一个都有可能在一个模块中实现,并由一个或多个类实现。不要觉得自己需要一次性在脑海中构建整个设计;相反,专注于一个你可以从其他问题中隔离出来的问题,理解这个问题,实现(和测试)你认为解决它的东西,然后从那里继续前进。允许自己有时候犯错 —— 并非每个设计想法都会成功,但当你有 Git 支持时,你可以通过简单地将更改回滚到最近的“稳定基础”提交来放弃一个糟糕的想法。


Unit testing 单元测试

Along with your Grin interpreter, you will be required to write unit tests, implemented using the unittest module in the Python standard library, and covering as much of your interpreter as is practical.
除了您的 Grin 解释器外,您还需要编写单元测试,使用 Python 标准库中的 unittest 模块实现,并尽可能涵盖您的解释器的大部分内容。

Note that how you design aspects of your interpreter has a positive impact on whether you can unit test it, as well as how hard you might have to work to do it; that's one of the reasons why you're aiming to write multiple modules in the grin package, and to tackle separate issues separately. For example, the fact that lexing and parsing are handled separately in the provided code means they can be tested separately; the fact that the result of parsing is a sequence of opaque tokens (instead of strings that need to be parsed again later) makes the code that uses the results of parsing similarly easier to test, since the tests can be written in terms of those higher-level tokens.
请注意,您如何设计解释器的各个方面会对您是否能够进行单元测试以及需要付出多少努力产生积极影响;这就是您希望在 grin 包中编写多个模块并分别解决不同问题的原因之一。例如,提供的代码中将词法分析和语法分析分开处理意味着它们可以分别进行测试;解析的结果是一系列不透明标记(而不是需要稍后重新解析的字符串)的事实使得使用解析结果的代码同样更容易测试,因为测试可以根据这些更高级别的标记编写。

There is not a strict requirement around code coverage measurement, nor a specific number of tests that must be written, but we'll be evaluating whether your design accommodates your ability to test it, and whether you've written unit tests that substantially cover the portions that can be tested. (Isolating code that has side effects — such as reading and writing text in the Python shell — can go a long way toward making your program more testable.) The provided tests are there partly to give you an idea of what a reasonably complete set of unit tests look like; your goal is to do likewise.
代码覆盖率测量没有严格的要求,也没有必须编写的特定测试数量,但我们将评估您的设计是否适合进行测试,以及您是否编写了充分覆盖可测试部分的单元测试。(隔离具有副作用的代码,比如在 Python shell 中读写文本,可以大大提高程序的可测试性。)提供的测试部分是为了让您了解一个相当完整的单元测试集是什么样子的;您的目标是做同样的事情。


Grin quick reference 咧牙快速参考

Here is a list of all of the Grin statements (and their different variants) that should be supported by your interpreter, with a brief description of the effect of each.
这是您的解释器应支持的所有 Grin 语句(及其不同变体)列表,其中包括每个语句效果的简要描述。

Statement Description
LET var value Changes the value of the variable var to the given value, which will either be a literal value or the name of another variable.
将变量 var 的值更改为给定值,该值可以是文字值或另一个变量的名称。
PRINT value Prints the given value to the console, where value will be either a literal value or the name of a variable.
将给定值打印到控制台,其中值可以是文字值或变量的名称。
INNUM var Reads a number (either integer or floating-point) into the variable var, which must be the name of a variable.
将一个数字(整数或浮点数)读入变量 var 中,var 必须是一个变量的名称。
INSTR var Reads a line of text and stores it (as a string) in the variable var, which must be the name of a variable.
读取一行文本并将其存储(作为字符串)在变量 var 中,var 必须是一个变量的名称。
ADD var value Adds the given value to the value of the variable var, where value will be either a literal value or the name of another variable.
将给定值添加到变量 var 的值中,其中值可以是字面值,也可以是另一个变量的名称。
SUB var value Subtracts the given value from the value of the variable var, where value will be either a literal value or the name of another variable.
从变量 var 的值中减去给定的值,其中值可以是字面值或另一个变量的名称。
MULT var value Multiplies the value of the variable var by the given value, where value will be either a literal value or the name of another variable.
将变量 var 的值乘以给定的值,其中值可以是字面值,也可以是另一个变量的名称。
DIV var value Divides the given value to the value of the variable var, where value will be either a literal value or the name of another variable.
将给定值除以变量 var 的值,其中 value 可以是文字值或另一个变量的名称。
GOTO target Jumps execution of the program to the given target, which will be an integer specifying a relative number of lines or a string containing a label.
将程序的执行跳转到给定的目标,该目标可以是指定相对行数的整数或包含标签的字符串。
GOTO target IF value1 op value2 Jumps execution of the program to the given target, but only if the values of value1 and value2 compare true using the relational operator op (=, <>, <, <=, >, >=). If the comparison is false, the statement has no effect.
将程序的执行跳转到给定的目标,但仅当 value1 和 value2 的值使用关系运算符 op( =<><<=>>= )比较为 true 时。如果比较结果为 false,则语句不起作用。
GOSUB target Temporarily jumps execution of the program to the given target, which will be an integer specifying a relative number of lines or a string containing a label. A subsequent RETURN statement will cause execution to jump back to the line followed the GOSUB.
临时跳转程序执行到给定的目标,该目标可以是指定相对行数的整数,也可以是包含标签的字符串。后续的 RETURN 语句将导致执行跳回 GOSUB 后面的行。
GOSUB target IF value1 op value2 Temporarily jumps execution of the program to the given target, but only if the values of value1 and value2 compare true using the relational operator op (=, <>, <, <=, >, >=). If the comparison is false, the statement has no effect.
暂时跳转程序执行到给定的目标,但仅当使用关系运算符 op(=,<>,<,<=,>,>=)比较 value1 和 value2 的值为真时。如果比较为假,则该语句无效。
RETURN Jumps execution of the program back to the line following the most recently-executed GOSUB statement.
跳转执行程序返回到最近执行的 GOSUB 语句后面的行。
END Ends the program immediately.
立即结束程序。
. Special marker that indicates the end of the program text. Behaves as an END statement when encountered.
表示程序文本结束的特殊标记。遇到时的行为类似于 END 语句。


Sanity-checking your output
检查您的输出

We are providing a tool that you can use to sanity check whether you've followed the basic requirements above. It will only give you a "passing" result in these circmustances.
我们提供了一个工具,您可以使用它来检查您是否遵循了上述的基本要求。在这些情况下,它只会给您一个“通过”的结果。

It should be noted that there are many additional tests you'll be want to perform, and that there are many additional tests that we'll be using when we grade your project. The way to understand the sanity checker's output is to think of it this way: Just because the sanity checker says your program passes doesn't mean it's close to perfect, but if you cannot get the sanity checker to report that your program passes, it surely will not pass all of our automated tests (and may well fail all of them).
需要注意的是,您将要执行许多额外的测试,并且我们在评分项目时将使用许多额外的测试。理解健全性检查器的输出方式是这样的:仅仅因为健全性检查器说您的程序通过了,并不意味着它接近完美,但如果您无法让健全性检查器报告您的程序通过,那么它肯定不会通过我们所有的自动化测试(而且很可能全部失败)。

You'll find the sanity checker in your project directory, in a file named project3_sanitycheck.py. Run that program like you would any other, and it will report a result.
您会在项目目录中找到名为 project3_sanitycheck.py 的文件中的健全性检查器。像运行其他程序一样运行该程序,它会报告一个结果。


Limitations 限制

You can use the Python standard library where appropriate in this project, but you will otherwise not be able to use code written by anyone else other than you. Notably, this includes third-party libraries (i.e., those that are not part of Python's standard library); colloquially, if we have to install something other than Python, Git, and PyCharm in order for your program to work, it's considered off-limits.
在这个项目中,您可以在适当的情况下使用 Python 标准库,但除此之外,您将无法使用其他人编写的代码。特别是,这包括第三方库(即不属于 Python 标准库的库);俗称,如果我们必须安装除 Python、Git 和 PyCharm 之外的东西才能使您的程序正常工作,那就被视为禁止。


Preparing your submission
准备您的提交

When you're ready to submit your work, run the provided prepare_submission.py script, as you did in prior projects, which will create a Git bundle from the Git repository in your project directory; that Git bundle will be your submission.
当您准备提交您的工作时,请运行提供的 prepare_submission.py 脚本,就像在之前的项目中一样,该脚本将从您的项目目录中的 Git 存储库创建一个 Git 捆绑包;该 Git 捆绑包将是您的提交。

Verifying your bundle before submission
提交前验证您的捆绑包

If you're feeling unsure of whether your bundle is complete and correct, you can verify it by creating a new PyCharm project from it, as you did in Project 0. (You'll want to create this project in a different directory from your project directory, so it's separate and isolated.) Afterward, you should see the files in their final form, and the Git tab in PyCharm should show your entire commit history. If so, you're in business; go ahead and submit your work.
如果您对您的捆绑包是否完整和正确感到不确定,您可以通过从中创建一个新的 PyCharm 项目来验证它,就像在项目 0 中所做的那样。(您需要在与项目目录不同的目录中创建此项目,以便它是独立的。)之后,您应该看到文件以最终形式呈现,并且 PyCharm 中的 Git 选项卡应显示您的整个提交历史。如果是这样,您就可以继续提交您的工作。


Deliverables 可交付成果

Submit your project3.bundle file (and no others) to Canvas. There are a few rules to be aware of.
将您的 project3.bundle 文件(而不是其他文件)提交到 Canvas。有一些规则需要注意。

Can I submit after the deadline?
我可以在截止日期后提交吗?

Yes, it is possible, subject to the late work policy for this course, which is described in the section titled Late work at this link. Beyond the late work deadline described there, we will no longer accept submissions.
是的,这是可能的,但要遵守本课程的迟交作业政策,该政策在标题为迟交作业的部分中有描述。在那里描述的迟交作业截止日期之后,我们将不再接受提交。

What do I do if Canvas adjusts my filename?
如果 Canvas 调整了我的文件名,我该怎么办?

Canvas will sometimes modify your filenames when you submit them (e.g., by adding a numbering scheme like -1 or a long sequence of hexadecimal digits to its name). In general, this is fine; as long as the file you submitted has the correct name prior to submission, we'll be able to obtain it with that same name, even if Canvas adjusts it.
当您提交文件时,Canvas 有时会修改您的文件名(例如,通过添加类似于-1 的编号方案或一长串十六进制数字到文件名)。总的来说,这没问题;只要您在提交之前提交的文件名是正确的,我们就能够以相同的名称获取它,即使 Canvas 对其进行了调整。