Debian Codegraph @

lib_pypy/pyrepl/simple_interact.py

raw symbols SCIP
1 # Copyright 2000-2010 Michael Hudson-Doyle <[email protected]>
2 # Armin Rigo
3 #
4 # All Rights Reserved
5 #
6 #
7 # Permission to use, copy, modify, and distribute this software and
8 # its documentation for any purpose is hereby granted without fee,
9 # provided that the above copyright notice appear in all copies and
10 # that both that copyright notice and this permission notice appear in
11 # supporting documentation.
12 #
13 # THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
14 # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15 # AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
16 # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
17 # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
18 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
19 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20
21 """This is an alternative to python_reader which tries to emulate
22 the CPython prompt as closely as possible, with the exception of
23 allowing multiline input and multiline history entries.
24 """
25
26 from __future__ import annotations
27
28 import _sitebuiltins
29 import linecache
30 import functools
31 import os
32 import sys
33 import code
34 import ast
35
36 from .readline import _get_reader, multiline_input
37
38 TYPE_CHECKING = False
39
40 if TYPE_CHECKING:
41 from typing import Any
42
43
44 _error: tuple[type[Exception], ...] | type[Exception]
45 try:
46 from .unix_console import _error
47 except ModuleNotFoundError:
48 from .windows_console import _error
49
50 def check() -> str:
51 """Returns the error message if there is a problem initializing the state."""
52 try:
53 _get_reader()
54 except _error as e:
55 if term := os.environ.get("TERM", ""):
56 term = f"; TERM={term}"
57 return str(str(e) or repr(e) or "unknown error") + term
58 return ""
59
60
61 def _strip_final_indent(text: str) -> str:
62 # kill spaces and tabs at the end, but only if they follow '\n'.
63 # meant to remove the auto-indentation only (although it would of
64 # course also remove explicitly-added indentation).
65 short = text.rstrip(" \t")
66 n = len(short)
67 if n > 0 and text[n - 1] == "\n":
68 return short
69 return text
70
71
72 def _clear_screen():
73 reader = _get_reader()
74 reader.scheduled_commands.append("clear_screen")
75
76
77 REPL_COMMANDS = {
78 "exit": _sitebuiltins.Quitter('exit', ''),
79 "quit": _sitebuiltins.Quitter('quit' ,''),
80 "copyright": _sitebuiltins._Printer('copyright', sys.copyright),
81 "help": "help",
82 "clear": _clear_screen,
83 }
84
85
86 def _more_lines(console: code.InteractiveConsole, unicodetext: str) -> bool:
87 # ooh, look at the hack:
88 src = _strip_final_indent(unicodetext)
89 try:
90 code = console.compile(src, "<stdin>", "single")
91 except (OverflowError, SyntaxError, ValueError):
92 lines = src.splitlines(keepends=True)
93 if len(lines) == 1:
94 return False
95
96 last_line = lines[-1]
97 was_indented = last_line.startswith((" ", "\t"))
98 not_empty = last_line.strip() != ""
99 incomplete = not last_line.endswith("\n")
100 return (was_indented or not_empty) and incomplete
101 else:
102 return code is None
103
104
105 def run_multiline_interactive_console(
106 console: code.InteractiveConsole,
107 *,
108 future_flags: int = 0,
109 ) -> None:
110 from .readline import set_completer, _setup
111 from rlcompleter import Completer as RLCompleter
112 _setup(console.locals)
113 # pypy change: setup has likely run already, set the correct completer
114 # explicitly
115 set_completer(RLCompleter(console.locals).complete)
116 if future_flags:
117 console.compile.compiler.flags |= future_flags
118
119 more_lines = functools.partial(_more_lines, console)
120 input_n = 0
121
122 def maybe_run_command(statement: str) -> bool:
123 statement = statement.strip()
124 if statement in console.locals or statement not in REPL_COMMANDS:
125 return False
126
127 reader = _get_reader()
128 reader.history.pop() # skip internal commands in history
129 command = REPL_COMMANDS[statement]
130 if callable(command):
131 command()
132 return True
133
134 if isinstance(command, str):
135 # Internal readline commands require a prepared reader like
136 # inside multiline_input.
137 reader.prepare()
138 reader.refresh()
139 reader.do_cmd((command, [statement]))
140 reader.restore()
141 return True
142
143 return False
144
145 while 1:
146 try:
147 try:
148 sys.stdout.flush()
149 except Exception:
150 pass
151
152 ps1 = getattr(sys, "ps1", ">>> ")
153 ps2 = getattr(sys, "ps2", "... ")
154 try:
155 statement = multiline_input(more_lines, ps1, ps2)
156 except EOFError:
157 break
158
159 if maybe_run_command(statement):
160 continue
161
162 input_name = f"<python-input-{input_n}>"
163 linecache._register_code(input_name, statement, "<stdin>") # type: ignore[attr-defined]
164 more = console.push(_strip_final_indent(statement), filename=input_name, _symbol="single") # type: ignore[call-arg]
165 assert not more
166 input_n += 1
167 except KeyboardInterrupt:
168 r = _get_reader()
169 if r.input_trans is r.isearch_trans:
170 r.do_cmd(("isearch-end", [""]))
171 r.pos = len(r.get_unicode())
172 r.dirty = True
173 r.refresh()
174 r.in_bracketed_paste = False
175 console.write("\nKeyboardInterrupt\n")
176 console.resetbuffer()
177 except MemoryError:
178 console.write("\nMemoryError\n")
179 console.resetbuffer()