为什么默认情况下 Forth 中的所有词都是全局的?

Why are all words in Forth by default global?

我正在学习Forth。为什么默认情况下该语言中的所有单词都是全局的?

如果我正确地命名了字典的关键字 -- 单词,请纠正我。

如果我们谈论 scoping,我认为原因是全局范围只是在任何地方都可用的最简单的方法。

是的,默认情况下所有标准和用户定义的词都具有全局范围。但是对于每个单词,它的范围仅从其 定义结束 开始(以此类推 ,前一个单词可以用于同名新单词的定义中)。并且局部变量的范围受声明这些变量的定义体的限制。

Forth 还提供了更高级的技术来控制单词的可见性。

单词被分组到单词列表中(一种 namespaces). And any part of a program can be excluded from the scope of a word list (i.e. the words from this word list). For that this word list should be excluded from the search order 在程序的这一部分开始(并在最后恢复)。 同样,通过将单词列表包含在搜索顺序中(并在末尾恢复),程序的任何部分都可以包含在单词列表的范围内。当然我们这里的效果是name masking

许多 Forth 系统也提供 API 允许使用由单词列表部分限定的名称。 例如:module1::submodule2::word3,其中module1是按搜索顺序可用的词,returns是词表标识符wid1submodule2是词表wid1中定义的词,而returns是词表标识符wid2word3 是在单词列表 wid2 中定义的单词。 (参见 my implementation 中的 RESOLVE-PQNAME 词作为参考)。

要缩短对某些模块的访问权限,您可以定义同义词,例如module1::submodule2 constant m 并使用前缀 m:: 访问此子模块中的单词 m::word3.

在我的 Forth 系统上,默认情况下,单词是在 FORTH 词汇表中创建的。检查您的 Forth 文档以获取 VOCABULARYWORDLIST。我可以创建我需要的任何词汇表并将它们设为默认词汇表。下面是一个简单的操作,用于在两个词汇表中创建两个具有相同名称的词以及如何访问它们。

\ Create two vocabularies ( in the FORTH vocabulary )
VOCABULARY ENGLISH
VOCABULARY FRENCH

ORDER   \ Show the search order and current vocabulary
\ FORTH  EXTERNALS  ROOT
\ Current: FORTH

ALSO ENGLISH
ORDER
\ ENGLISH  FORTH  EXTERNALS  ROOT  \ ENGLISH added to the search order
\ Current: FORTH                   \ New words created in FORTH

DEFINITIONS  ok      \ Change 'Current' to the top of the search order.
ORDER
\ ENGLISH  FORTH  EXTERNALS  ROOT
\ Current: ENGLISH                 \ New words created in ENGLISH

: trans  \ n -- ;
  1- 6 * s" One   Two   Three Four  " DROP + 6 TYPE ;

PREVIOUS  \ Remove the top vocabulary from the search order
ORDER
\ FORTH  EXTERNALS  ROOT  \ ENGLISH dropped from the search order.
\ Current: ENGLISH        \ but still where new words will be created.

ALSO FRENCH DEFINITIONS
ORDER
\ FRENCH  FORTH  EXTERNALS  ROOT
\ Current: FRENCH                 \ New words created in FRENCH

: trans  \ n -- ;
  1- 6 * s" Un    Deux  Trois Quatre" DROP + 6 TYPE ;

PREVIOUS DEFINITIONS

ALSO ENGLISH
1 trans 2 trans 3 trans 4 trans
\ One   Two   Three Four   ok

PREVIOUS ALSO FRENCH
1 trans 2 trans 3 trans 4 trans
\ Un    Deux  Trois Quatre ok

例如,汇编程序将在另一个VOCABULARY 中,一旦执行了CODE 定义字,该VOCABULARY 就会打开。之后,首先在 ASSEMBLER 词汇表中搜索任何单词。

一些 Forth 实现允许 MODULES。我从未使用过它们,但请查看您系统的文档。