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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
|
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
import os
import shutil
import subprocess
import tempfile
from ipykernel.kernelbase import Kernel
__version__ = "0.0.1"
class TableGenKernelException(Exception):
pass
class TableGenKernel(Kernel):
"""Kernel using llvm-tblgen inside jupyter.
All input is treated as TableGen unless the first non whitespace character
is "%" in which case it is a "magic" line.
The supported cell magic is:
* %args - to set the arguments passed to llvm-tblgen.
* %reset - to reset the cached code and magic state.
* %noreset - to not reset the cached code and magic state
(useful when you have changed the default to always
reset the cache).
These are "cell magic" meaning it applies to the whole cell. Therefore
it must be the first line, or part of a run of magic lines starting
from the first line.
The following are global magic (that applies to all cells going
forward):
* %config - to change the behaviour of the kernel overall, including
changing defaults for things like resets.
Global magic must be written in the same way as cell magic.
```tablgen
%args
%reset
%args --print-records --print-detailed-records
class Stuff {
string Name;
}
def a_thing : Stuff {}
```
"""
implementation = "tablegen"
implementation_version = __version__
language_version = __version__
language = "tablegen"
language_info = {
"name": "tablegen",
"mimetype": "text/x-tablegen",
"file_extension": ".td",
"pygments_lexer": "text",
}
def __init__(self, **kwargs):
Kernel.__init__(self, **kwargs)
self._executable = None
# A list of (code, magic) tuples.
# All the previous cell's code we have run since the last reset.
# This emulates a persistent state like a Python interpreter would have.
self._previous_code = ""
# The most recent set of magic since the last reset.
self._previous_magic = {}
# The default cache reset behaviour. True means do not cache anything
# between cells.
self._cell_reset = False
@property
def banner(self):
return "llvm-tblgen kernel %s" % __version__
def get_executable(self):
"""If this is the first run, search for llvm-tblgen.
Otherwise return the cached path to it."""
if self._executable is None:
path = os.environ.get("LLVM_TBLGEN_EXECUTABLE")
if path is not None and os.path.isfile(path) and os.access(path, os.X_OK):
self._executable = path
else:
path = shutil.which("llvm-tblgen")
if path is None:
raise OSError(
"llvm-tblgen not found. Put it on your PATH or set the"
" environment variable LLVM_TBLGEN_EXECUTABLE to point to it."
)
self._executable = path
return self._executable
def parse_config_magic(self, config):
"""Config should be a list of parameters given to the %config command.
We allow only one setting per %config line and that setting can only
have one value.
Assuming the parameters are valid, update the kernel's setting with
the new value.
If there is an error, raise a TableGenKernelException.
>>> k.parse_config_magic([])
Traceback (most recent call last):
...
TableGenKernelException: Incorrect number of parameters to %config. Expected %config <setting> <value>.
>>> k._cell_reset
False
>>> k.parse_config_magic(["a", "b", "c"])
Traceback (most recent call last):
...
TableGenKernelException: Incorrect number of parameters to %config. Expected %config <setting> <value>.
>>> k.parse_config_magic(["notasetting", "..."])
Traceback (most recent call last):
...
TableGenKernelException: Unknown kernel setting "notasetting". Possible settings are: "cellreset".
>>> k.parse_config_magic(["cellreset", "food"])
Traceback (most recent call last):
...
TableGenKernelException: Invalid value for setting "cellreset", expected "on" or "off".
>>> k.parse_config_magic(["cellreset", "on"])
>>> k._cell_reset
True
>>> k.parse_config_magic(["cellreset", "off"])
>>> k._cell_reset
False
"""
if len(config) != 2:
raise TableGenKernelException(
"Incorrect number of parameters to %config. Expected %config <setting> <value>."
)
name, value = config
if name != "cellreset":
raise TableGenKernelException(
'Unknown kernel setting "{}". '
'Possible settings are: "cellreset".'.format(name)
)
try:
self._cell_reset = {"on": True, "off": False}[value.lower()]
except KeyError:
raise TableGenKernelException(
'Invalid value for setting "{}", '
'expected "on" or "off".'.format(name)
)
def get_magic(self, code):
"""Given a block of code remove the magic lines from it.
Returns a tuple of newline joined code lines and a dictionary of magic.
Where the key is the magic name (minus the %) and the values are lists
of the arguments to the magic.
Currently we only look for "cell magic" which must be at the start of
the cell. Meaning the first line, or a set of lines beginning with %
that come before the first non-magic line.
>>> k.get_magic("")
('', {})
>>> k.get_magic("Hello World.\\nHello again.")
('Hello World.\\nHello again.', {})
>>> k.get_magic(" %foo a b c")
('', {'foo': ['a', 'b', 'c']})
>>> k.get_magic("%foo\\n %foo a b c\\nFoo")
('Foo', {'foo': ['a', 'b', 'c']})
>>> k.get_magic("%foo\\n%bar\\nFoo")
('Foo', {'foo': [], 'bar': []})
>>> k.get_magic("Foo\\n%foo\\nFoo")
('Foo\\n%foo\\nFoo', {})
>>> k.get_magic("%bar\\n\\n%foo")
('\\n%foo', {'bar': []})
>>> k.get_magic("%foo a b\\n Foo\\n%foo c d")
(' Foo\\n%foo c d', {'foo': ['a', 'b']})
>>> k.get_magic("%foo a b\\n \\n%foo c d")
(' \\n%foo c d', {'foo': ['a', 'b']})
"""
magic = {}
code_lines = []
lines = code.splitlines()
while lines:
line = lines.pop(0)
possible_magic = line.lstrip()
if possible_magic.startswith("%"):
magic_parts = possible_magic.split()
# Key has the % removed
magic[magic_parts[0][1:]] = magic_parts[1:]
else:
code_lines = [line, *lines]
break
return "\n".join(code_lines), magic
def should_reset(self, magic):
"""Return true if we should reset the cache, based on the default
setting and the current cell's magic %reset and/or %noreset.
>>> k._cell_reset = False
>>> k.should_reset({})
False
>>> k.should_reset({'reset': [], 'noreset': []})
Traceback (most recent call last):
...
TableGenKernelException: %reset and %noreset in the same cell is not allowed. Use only one, or neither.
>>> k.should_reset({'reset': []})
True
>>> k.should_reset({'noreset': []})
False
>>> k._cell_reset = True
>>> k.should_reset({})
True
>>> k.should_reset({'reset': [], 'noreset': []})
Traceback (most recent call last):
...
TableGenKernelException: %reset and %noreset in the same cell is not allowed. Use only one, or neither.
>>> k.should_reset({'reset': []})
True
>>> k.should_reset({'noreset': []})
False
"""
# Cell reset is the default unless told otherwise.
should_reset = self._cell_reset
# Magic reset commands always win if present.
reset = magic.get("reset") is not None
noreset = magic.get("noreset") is not None
if reset and not noreset:
should_reset = True
elif noreset and not reset:
should_reset = False
elif noreset and reset:
raise TableGenKernelException(
"%reset and %noreset in the same cell is not allowed. Use only one, or neither."
)
# else neither are set so use the default.
return should_reset
def get_code_and_args(self, new_code):
"""Get the code that do_execute should use, taking into account
the code from any cached cells.
Returns the code to compile and the arguments to use to do so.
>>> k._previous_code = ""
>>> k._previous_magic = {}
>>> k.get_code_and_args("")
('', [])
>>> k.get_code_and_args("%args 1\\nSome code")
('Some code', ['1'])
>>> k.get_code_and_args("%args 2\\nSome more code")
('Some code\\nSome more code', ['2'])
>>> k.get_code_and_args("%reset\\n%args 3 4\\nSome new code")
('Some new code', ['3', '4'])
>>> k.get_code_and_args("%reset\\nSome new code")
('Some new code', [])
"""
new_code, new_magic = self.get_magic(new_code)
# Update kernel configuration first, if needed.
config_magic = new_magic.get("config")
if config_magic is not None:
self.parse_config_magic(config_magic)
if self.should_reset(new_magic):
self._previous_code = new_code
self._previous_magic = new_magic
else:
self._previous_code += ("\n" if self._previous_code else "") + new_code
self._previous_magic.update(new_magic)
return self._previous_code, self._previous_magic.get("args", [])
def make_status(self):
return {
"status": "ok",
"execution_count": self.execution_count,
"payload": [],
"user_expressions": {},
}
def send_stream(self, name, content):
self.send_response(self.iopub_socket, "stream", {"name": name, "text": content})
return self.make_status()
def send_stderr(self, stderr):
return self.send_stream("stderr", stderr)
def send_stdout(self, stdout):
return self.send_stream("stdout", stdout)
def do_execute(
self, code, silent, store_history=True, user_expressions=None, allow_stdin=False
):
"""Execute user code using llvm-tblgen binary."""
try:
all_code, args = self.get_code_and_args(code)
except TableGenKernelException as e:
return self.send_stderr(str(e))
# If we cannot find llvm-tblgen, propogate the error to the notebook.
# (in case the user is not able to see the output from the Jupyter server)
try:
executable = self.get_executable()
except Exception as e:
return self.send_stderr(str(e))
with tempfile.TemporaryFile("w+") as f:
f.write(all_code)
f.seek(0)
got = subprocess.run(
[executable, *args],
stdin=f,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True,
)
if not silent:
if got.stderr:
return self.send_stderr(got.stderr)
else:
return self.send_stdout(got.stdout)
else:
return self.make_status()
if __name__ == "__main__":
import doctest
doctest.testmod(extraglobs={"k": TableGenKernel()})
|