forked from AdaCore/langkit-query-language
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlkql_repl.py
executable file
·160 lines (120 loc) · 4.02 KB
/
lkql_repl.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#! /usr/bin/env python
import argparse
import itertools
import liblkqllang as lkql
from prompt_toolkit import PromptSession, print_formatted_text
from prompt_toolkit.history import FileHistory
from prompt_toolkit.lexers import PygmentsLexer
from prompt_toolkit.completion import Completer, Completion, FuzzyCompleter
from prompt_toolkit.patch_stdout import patch_stdout
from prompt_toolkit.styles import Style
from prompt_toolkit.formatted_text import HTML
style = Style.from_dict({
'prompt': 'ansigreen bold',
'logo': 'yellow bold'
})
ctx = lkql.AnalysisContext()
parser = argparse.ArgumentParser()
parser.add_argument(
"-P", "--project",
help="Ada project file to base the queries upon",
required=True
)
parser.add_argument("-s", "--script", help="LKQL script to load")
class LKQLCompleter(Completer):
"""
LKQL completer, based on p_interp_complete.
"""
def get_completions(self, document, complete_event):
doc = "\n".join(document.lines)
cmd_unit = ctx.get_from_buffer('<complete>', doc)
n = cmd_unit.root.lookup(lkql.Sloc(1, len(cmd_unit.text)))
if n is None:
return
for sym in n.p_interp_complete:
yield Completion(sym)
builtins = {}
global dummy_unit
HELP_MESSAGE = """
LKQL read eval print loop. You can use it to evaluate LKQL statements on an Ada
project
Here are the list of built-in commands:
""".strip()
WELCOME_PROMPT = r"""
<logo>.-. .-. .-..----. .-. </logo>
<logo>| | | |/ // {} \| | </logo> Welcome to LKQL repl
<logo>| `--.| |\ \\ /| `--. </logo> type 'help' for more information
<logo>`----'`-' `-'`-----``----' </logo>
"""
def register_builtin(fn):
builtins[fn.__name__] = fn
return fn
@register_builtin
def exit():
"""
Exit the REPL
"""
raise EOFError()
@register_builtin
def reload():
"""
Reload the Ada sources the REPL was started on
"""
print("Reloading sources ...")
dummy_unit.root.p_interp_init_from_project(args.project)
@register_builtin
def load_file(file_path):
"""
Load lkql file given in argument.
"""
print(file_path)
unit = ctx.get_from_file(file_path)
print(unit.root.p_interp_eval)
del unit
@register_builtin
def help():
"""
Print the help
"""
commands_help = "\n".join(
f"%{fn.__name__}: {fn.__doc__}" for fn in builtins.values()
)
print(f"{HELP_MESSAGE}\n\n{commands_help}")
if __name__ == '__main__':
print_formatted_text(HTML(WELCOME_PROMPT), style=style)
args, _ = parser.parse_known_args()
our_history = FileHistory(".example-history-file")
session = PromptSession(
history=our_history, lexer=PygmentsLexer(lkql.LKQLPygmentsLexer),
completer=FuzzyCompleter(LKQLCompleter())
)
dummy_unit = ctx.get_from_buffer('<dummy>', '12')
dummy_unit.root.p_interp_init_from_project(args.project)
if args.script:
cmd_unit = ctx.get_from_file(args.script)
cmd_unit.root.p_interp_eval
for i in itertools.count(start=1):
# We have a new buffer name at each iteration, to create a new buffer
# for each repl input, so that references to old buffers are still
# valid.
# Due to the way LKQL is interpreted, references to old code can still
# be made, so we must make sure we don't deallocate old buffers.
buffer_name = f'<repl_input_{i}>'
try:
with patch_stdout():
cmd = session.prompt(HTML("<prompt> > </prompt>"), style=style)
if cmd.startswith("%"):
cmd, *args = cmd[1:].split(' ')
builtins[cmd](*args)
else:
cmd_unit = ctx.get_from_buffer(buffer_name, cmd)
print(cmd_unit.root.p_interp_eval)
except EOFError:
try:
cmd = session.prompt('Do you really want to exit ([y]/n)? ')
if cmd == 'y' or cmd == '':
break
else:
continue
except EOFError:
break