How do Ruby and Python implement their interactive consoles?

眉间皱痕 提交于 2019-12-04 03:44:54

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.

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.

You can learn more about the Python interactive console by reading the documentation for the code module:

The code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications which provide an interactive interpreter prompt.

http://docs.python.org/library/code.html

Most of these languages use a parser which has a kind of "token stream" -- that is, the parser keeps taking tokens (a string, symbol, operator, etc) from the input stream until it has a full expression, then it returns that parsed expression where it might be compiled to bytecode or otherwise executed. A REPL loop is relatively simple to handle given that structure, as the parser basically asks for more input, and you give the user a prompt and have the user enter more input. You might need a bit of communication from the parser to the reader to make it render things like continuation prompts.

Python and Ruby both execute statements immediately, in-order (a function declaration is one statement). So you can execute code statement-by-statement at the interpreter to largely the same effect as in a source file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!