Ruby和Python如何实现其交互式控制台? [英] How do Ruby and Python implement their interactive consoles?

查看:66
本文介绍了Ruby和Python如何实现其交互式控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为我的编程语言实现解释器时,我首先想到了一个简单的控制台窗口,该窗口允许用户输入一些代码,然后将这些代码作为独立程序作为外壳执行。

When implementing the interpreter for my programming language I first thought of a simple console window which allows the user to enter some code which is then executed as a standalone program as a shell.

但是有严重的问题:如果用户输入的每一行代码都作为一个独立的程序进行处理,则它必须经过标记器和解析器,然后才由解释器执行-那么函数呢?

But there are severe problems: If every line of code the user enters is handled as a standalone program, it has to go through the tokenizer and parser and is then just executed by the interpreter - what about functions then?


  • Python / Ruby交互式控制台(IDLE,irb)如何共享代码?输入的代码如何处理?

示例:

>> def x:
>>  print("Blah")
>> 
>> x()

该函数存储在哪里,以便可以在任何时候再次调用它?

Where is the function stored so it can be called at any time again?

交互式控制台如何将输入的所有内容视为一个程序而又不需一遍又一遍地执行所有操作?

推荐答案

对于Python,在所有括号,方括号等都匹配之前,表达式是不完整的。这相当容易检测。在输入完全空白的行之前,功能/类的定义是不完整的。然后,编译器会编译输入的表达式或定义,然后运行它。

For Python, an expression isn't complete until all parentheses, brackets, etc. match up. This is fairly easy to detect. A function/class definition isn't complete until a completely blank line is entered. The compiler then compiles the entered expression or definition, and runs it.

REPL与普通函数,类,模块等类似,具有自己的局部作用域。此范围用于在REPL中输入的变量和定义。

Much like a normal function, class, module, etc., the REPL has its own local scope. It's this scope that is used for variables and definitions entered into the REPL.

这篇关于Ruby和Python如何实现其交互式控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆