Debian Codegraph @

doc/tools/rocqrst/repl/rocqtop.py

raw symbols SCIP
1 ##########################################################################
2 ## # The Rocq Prover / The Rocq Development Team ##
3 ## v # Copyright INRIA, CNRS and contributors ##
4 ## <O___,, # (see version control and CREDITS file for authors & dates) ##
5 ## \VV/ ###############################################################
6 ## // # This file is distributed under the terms of the ##
7 ## # GNU Lesser General Public License Version 2.1 ##
8 ## # (see LICENSE file for the text of the license) ##
9 ##########################################################################
10 """
11 Drive rocq top with Python!
12 =========================
13
14 This module is a simple pexpect-based driver for rocq top, based on the old
15 REPL interface.
16 """
17
18 import os
19 import re
20 import tempfile
21
22 import pexpect
23
24
25 class RocqTopError(Exception):
26 def __init__(self, err, last_sentence, before):
27 super().__init__()
28 self.err = err
29 self.before = before
30 self.last_sentence = last_sentence
31
32 class RocqTop:
33 """Create an instance of rocq top.
34
35 Use this as a context manager: no instance of rocq top is created until
36 you call `__enter__`. rocq top is terminated when you `__exit__` the
37 context manager.
38
39 Sentence parsing is very basic for now (a "." in a quoted string will
40 confuse it).
41
42 When environment variable ROCQ_DEBUG_REFMAN is set, all the input
43 we send to rocq top is copied to a temporary file "/tmp/rocqdomainXXXX.v".
44 """
45
46 ROCQTOP_PROMPT = re.compile("\r\n[^< \r\n]+ < ")
47
48 def __init__(self, rocqbin=None, color=False, args=None) -> str:
49 """Configure a rocq top instance (but don't start it yet).
50
51 :param rocqbin: The path to rocq; uses $COQBIN by default, falling
52 back to "rocq"
53 :param color: When True, tell "rocq top" to produce ANSI color
54 codes (see the ansicolors module)
55 :param args: Additional arguments to "rocq top".
56 """
57 self.rocqbin = rocqbin or os.path.join(os.getenv("COQBIN", ""), "rocq")
58 if not pexpect.utils.which(self.rocqbin):
59 raise ValueError("'{}: not found".format(rocqbin))
60 self.args = ["top"] + (args or []) + ["-q"] + ["-color", "on"] * color
61 self.rocqtop = None
62 self.debugfile = None
63
64 def __enter__(self):
65 if self.rocqtop:
66 raise ValueError("This module isn't re-entrant")
67 self.rocqtop = pexpect.spawn(self.rocqbin, args=self.args, echo=False, encoding="utf-8")
68 # Disable delays (http://pexpect.readthedocs.io/en/stable/commonissues.html?highlight=delaybeforesend)
69 self.rocqtop.delaybeforesend = 0
70 if os.getenv ("ROCQ_DEBUG_REFMAN"):
71 self.debugfile = tempfile.NamedTemporaryFile(mode="w+", prefix="rocqdomain", suffix=".v", delete=False, dir="/tmp/")
72 self.next_prompt()
73 return self
74
75 def __exit__(self, type, value, traceback):
76 if self.debugfile:
77 self.debugfile.close()
78 self.debugfile = None
79 self.rocqtop.kill(9)
80
81 def next_prompt(self):
82 """Wait for the next rocq top prompt, and return the output preceding it."""
83 self.rocqtop.expect(RocqTop.ROCQTOP_PROMPT, timeout = 10)
84 return self.rocqtop.before
85
86 def sendone(self, sentence):
87 """Send a single sentence to rocq top.
88
89 :sentence: One Rocq sentence (otherwise, rocq top will produce multiple
90 prompts and we'll get confused)
91 """
92 # Suppress newlines, but not spaces: they are significant in notations
93 sentence = re.sub(r"[\r\n]+", " ", sentence).strip()
94 try:
95 if self.debugfile:
96 self.debugfile.write(sentence+"\n")
97 self.rocqtop.sendline(sentence)
98 output = self.next_prompt()
99 except Exception as err:
100 raise RocqTopError(err, sentence, self.rocqtop.before)
101 return output
102
103 def send_initial_options(self):
104 """Options to send when starting the toplevel and after a Reset Initial."""
105 self.sendone('Set Rocqtop Exit On Error.')
106 self.sendone('Set Warnings "+default".')
107
108 def sendmany(*sentences):
109 """A small demo: send each sentence in sentences and print the output"""
110 with RocqTop() as rocqtop:
111 for sentence in sentences:
112 print("=====================================")
113 print(sentence)
114 print("-------------------------------------")
115 response = rocqtop.sendone(sentence)
116 print(response)
117
118 def main():
119 """Run a simple performance test and demo `sendmany`"""
120 with RocqTop() as rocqtop:
121 for _ in range(200):
122 print(repr(rocqtop.sendone("Check nat.")))
123 sendmany("Goal False -> True.", "Proof.", "intros H.",
124 "Check H.", "Chchc.", "apply I.", "Qed.")
125
126 if __name__ == '__main__':
127 main()