| 1 |
"""Parser for bytecodes.inst.""" |
| 2 |
|
| 3 |
from dataclasses import dataclass, field |
| 4 |
from typing import NamedTuple, Callable, TypeVar, Literal, cast |
| 5 |
|
| 6 |
import lexer as lx |
| 7 |
from plexer import PLexer |
| 8 |
|
| 9 |
|
| 10 |
P = TypeVar("P", bound="Parser") |
| 11 |
N = TypeVar("N", bound="Node") |
| 12 |
|
| 13 |
|
| 14 |
def contextual(func: Callable[[P], N | None]) -> Callable[[P], N | None]: |
| 15 |
# Decorator to wrap grammar methods. |
| 16 |
# Resets position if `func` returns None. |
| 17 |
def contextual_wrapper(self: P) -> N | None: |
| 18 |
begin = self.getpos() |
| 19 |
res = func(self) |
| 20 |
if res is None: |
| 21 |
self.setpos(begin) |
| 22 |
return None |
| 23 |
end = self.getpos() |
| 24 |
res.context = Context(begin, end, self) |
| 25 |
return res |
| 26 |
|
| 27 |
return contextual_wrapper |
| 28 |
|
| 29 |
|
| 30 |
class Context(NamedTuple): |
| 31 |
begin: int |
| 32 |
end: int |
| 33 |
owner: PLexer |
| 34 |
|
| 35 |
def __repr__(self) -> str: |
| 36 |
return f"<{self.owner.filename}: {self.begin}-{self.end}>" |
| 37 |
|
| 38 |
|
| 39 |
@dataclass |
| 40 |
class Node: |
| 41 |
context: Context | None = field(init=False, compare=False, default=None) |
| 42 |
|
| 43 |
@property |
| 44 |
def text(self) -> str: |
| 45 |
return self.to_text() |
| 46 |
|
| 47 |
def to_text(self, dedent: int = 0) -> str: |
| 48 |
context = self.context |
| 49 |
if not context: |
| 50 |
return "" |
| 51 |
return lx.to_text(self.tokens, dedent) |
| 52 |
|
| 53 |
@property |
| 54 |
def tokens(self) -> list[lx.Token]: |
| 55 |
context = self.context |
| 56 |
if not context: |
| 57 |
return [] |
| 58 |
tokens = context.owner.tokens |
| 59 |
begin = context.begin |
| 60 |
end = context.end |
| 61 |
return tokens[begin:end] |
| 62 |
|
| 63 |
|
| 64 |
@dataclass |
| 65 |
class Block(Node): |
| 66 |
# This just holds a context which has the list of tokens. |
| 67 |
pass |
| 68 |
|
| 69 |
|
| 70 |
@dataclass |
| 71 |
class StackEffect(Node): |
| 72 |
name: str = field(compare=False) # __eq__ only uses type, cond, size |
| 73 |
type: str = "" # Optional `:type` |
| 74 |
cond: str = "" # Optional `if (cond)` |
| 75 |
size: str = "" # Optional `[size]` |
| 76 |
# Note: size cannot be combined with type or cond |
| 77 |
|
| 78 |
def __repr__(self) -> str: |
| 79 |
items = [self.name, self.type, self.cond, self.size] |
| 80 |
while items and items[-1] == "": |
| 81 |
del items[-1] |
| 82 |
return f"StackEffect({', '.join(repr(item) for item in items)})" |
| 83 |
|
| 84 |
|
| 85 |
@dataclass |
| 86 |
class Expression(Node): |
| 87 |
size: str |
| 88 |
|
| 89 |
|
| 90 |
@dataclass |
| 91 |
class CacheEffect(Node): |
| 92 |
name: str |
| 93 |
size: int |
| 94 |
|
| 95 |
|
| 96 |
@dataclass |
| 97 |
class OpName(Node): |
| 98 |
name: str |
| 99 |
|
| 100 |
|
| 101 |
InputEffect = StackEffect | CacheEffect |
| 102 |
OutputEffect = StackEffect |
| 103 |
UOp = OpName | CacheEffect |
| 104 |
|
| 105 |
|
| 106 |
@dataclass |
| 107 |
class InstHeader(Node): |
| 108 |
annotations: list[str] |
| 109 |
kind: Literal["inst", "op"] |
| 110 |
name: str |
| 111 |
inputs: list[InputEffect] |
| 112 |
outputs: list[OutputEffect] |
| 113 |
|
| 114 |
|
| 115 |
@dataclass |
| 116 |
class InstDef(Node): |
| 117 |
annotations: list[str] |
| 118 |
kind: Literal["inst", "op"] |
| 119 |
name: str |
| 120 |
inputs: list[InputEffect] |
| 121 |
outputs: list[OutputEffect] |
| 122 |
block: Block |
| 123 |
|
| 124 |
|
| 125 |
@dataclass |
| 126 |
class Macro(Node): |
| 127 |
name: str |
| 128 |
uops: list[UOp] |
| 129 |
|
| 130 |
|
| 131 |
@dataclass |
| 132 |
class Family(Node): |
| 133 |
name: str |
| 134 |
size: str # Variable giving the cache size in code units |
| 135 |
members: list[str] |
| 136 |
|
| 137 |
|
| 138 |
@dataclass |
| 139 |
class Pseudo(Node): |
| 140 |
name: str |
| 141 |
flags: list[str] # instr flags to set on the pseudo instruction |
| 142 |
targets: list[str] # opcodes this can be replaced by |
| 143 |
|
| 144 |
|
| 145 |
AstNode = InstDef | Macro | Pseudo | Family |
| 146 |
|
| 147 |
|
| 148 |
class Parser(PLexer): |
| 149 |
@contextual |
| 150 |
def definition(self) -> AstNode | None: |
| 151 |
if macro := self.macro_def(): |
| 152 |
return macro |
| 153 |
if family := self.family_def(): |
| 154 |
return family |
| 155 |
if pseudo := self.pseudo_def(): |
| 156 |
return pseudo |
| 157 |
if inst := self.inst_def(): |
| 158 |
return inst |
| 159 |
return None |
| 160 |
|
| 161 |
@contextual |
| 162 |
def inst_def(self) -> InstDef | None: |
| 163 |
if hdr := self.inst_header(): |
| 164 |
if block := self.block(): |
| 165 |
return InstDef( |
| 166 |
hdr.annotations, |
| 167 |
hdr.kind, |
| 168 |
hdr.name, |
| 169 |
hdr.inputs, |
| 170 |
hdr.outputs, |
| 171 |
block, |
| 172 |
) |
| 173 |
raise self.make_syntax_error("Expected block") |
| 174 |
return None |
| 175 |
|
| 176 |
@contextual |
| 177 |
def inst_header(self) -> InstHeader | None: |
| 178 |
# annotation* inst(NAME, (inputs -- outputs)) |
| 179 |
# | annotation* op(NAME, (inputs -- outputs)) |
| 180 |
annotations = [] |
| 181 |
while anno := self.expect(lx.ANNOTATION): |
| 182 |
if anno.text == "replicate": |
| 183 |
self.require(lx.LPAREN) |
| 184 |
times = self.require(lx.NUMBER) |
| 185 |
self.require(lx.RPAREN) |
| 186 |
annotations.append(f"replicate({times.text})") |
| 187 |
else: |
| 188 |
annotations.append(anno.text) |
| 189 |
tkn = self.expect(lx.INST) |
| 190 |
if not tkn: |
| 191 |
tkn = self.expect(lx.OP) |
| 192 |
if tkn: |
| 193 |
kind = cast(Literal["inst", "op"], tkn.text) |
| 194 |
if self.expect(lx.LPAREN) and (tkn := self.expect(lx.IDENTIFIER)): |
| 195 |
name = tkn.text |
| 196 |
if self.expect(lx.COMMA): |
| 197 |
inp, outp = self.io_effect() |
| 198 |
if self.expect(lx.RPAREN): |
| 199 |
if (tkn := self.peek()) and tkn.kind == lx.LBRACE: |
| 200 |
return InstHeader(annotations, kind, name, inp, outp) |
| 201 |
return None |
| 202 |
|
| 203 |
def io_effect(self) -> tuple[list[InputEffect], list[OutputEffect]]: |
| 204 |
# '(' [inputs] '--' [outputs] ')' |
| 205 |
if self.expect(lx.LPAREN): |
| 206 |
inputs = self.inputs() or [] |
| 207 |
if self.expect(lx.MINUSMINUS): |
| 208 |
outputs = self.outputs() or [] |
| 209 |
if self.expect(lx.RPAREN): |
| 210 |
return inputs, outputs |
| 211 |
raise self.make_syntax_error("Expected stack effect") |
| 212 |
|
| 213 |
def inputs(self) -> list[InputEffect] | None: |
| 214 |
# input (',' input)* |
| 215 |
here = self.getpos() |
| 216 |
if inp := self.input(): |
| 217 |
inp = cast(InputEffect, inp) |
| 218 |
near = self.getpos() |
| 219 |
if self.expect(lx.COMMA): |
| 220 |
if rest := self.inputs(): |
| 221 |
return [inp] + rest |
| 222 |
self.setpos(near) |
| 223 |
return [inp] |
| 224 |
self.setpos(here) |
| 225 |
return None |
| 226 |
|
| 227 |
@contextual |
| 228 |
def input(self) -> InputEffect | None: |
| 229 |
return self.cache_effect() or self.stack_effect() |
| 230 |
|
| 231 |
def outputs(self) -> list[OutputEffect] | None: |
| 232 |
# output (, output)* |
| 233 |
here = self.getpos() |
| 234 |
if outp := self.output(): |
| 235 |
near = self.getpos() |
| 236 |
if self.expect(lx.COMMA): |
| 237 |
if rest := self.outputs(): |
| 238 |
return [outp] + rest |
| 239 |
self.setpos(near) |
| 240 |
return [outp] |
| 241 |
self.setpos(here) |
| 242 |
return None |
| 243 |
|
| 244 |
@contextual |
| 245 |
def output(self) -> OutputEffect | None: |
| 246 |
return self.stack_effect() |
| 247 |
|
| 248 |
@contextual |
| 249 |
def cache_effect(self) -> CacheEffect | None: |
| 250 |
# IDENTIFIER '/' NUMBER |
| 251 |
if tkn := self.expect(lx.IDENTIFIER): |
| 252 |
if self.expect(lx.DIVIDE): |
| 253 |
num = self.require(lx.NUMBER).text |
| 254 |
try: |
| 255 |
size = int(num) |
| 256 |
except ValueError: |
| 257 |
raise self.make_syntax_error(f"Expected integer, got {num!r}") |
| 258 |
else: |
| 259 |
return CacheEffect(tkn.text, size) |
| 260 |
return None |
| 261 |
|
| 262 |
@contextual |
| 263 |
def stack_effect(self) -> StackEffect | None: |
| 264 |
# IDENTIFIER [':' IDENTIFIER [TIMES]] ['if' '(' expression ')'] |
| 265 |
# | IDENTIFIER '[' expression ']' |
| 266 |
if tkn := self.expect(lx.IDENTIFIER): |
| 267 |
type_text = "" |
| 268 |
if self.expect(lx.COLON): |
| 269 |
type_text = self.require(lx.IDENTIFIER).text.strip() |
| 270 |
if self.expect(lx.TIMES): |
| 271 |
type_text += " *" |
| 272 |
cond_text = "" |
| 273 |
if self.expect(lx.IF): |
| 274 |
self.require(lx.LPAREN) |
| 275 |
if not (cond := self.expression()): |
| 276 |
raise self.make_syntax_error("Expected condition") |
| 277 |
self.require(lx.RPAREN) |
| 278 |
cond_text = cond.text.strip() |
| 279 |
size_text = "" |
| 280 |
if self.expect(lx.LBRACKET): |
| 281 |
if type_text or cond_text: |
| 282 |
raise self.make_syntax_error("Unexpected [") |
| 283 |
if not (size := self.expression()): |
| 284 |
raise self.make_syntax_error("Expected expression") |
| 285 |
self.require(lx.RBRACKET) |
| 286 |
type_text = "PyObject **" |
| 287 |
size_text = size.text.strip() |
| 288 |
return StackEffect(tkn.text, type_text, cond_text, size_text) |
| 289 |
return None |
| 290 |
|
| 291 |
@contextual |
| 292 |
def expression(self) -> Expression | None: |
| 293 |
tokens: list[lx.Token] = [] |
| 294 |
level = 1 |
| 295 |
while tkn := self.peek(): |
| 296 |
if tkn.kind in (lx.LBRACKET, lx.LPAREN): |
| 297 |
level += 1 |
| 298 |
elif tkn.kind in (lx.RBRACKET, lx.RPAREN): |
| 299 |
level -= 1 |
| 300 |
if level == 0: |
| 301 |
break |
| 302 |
tokens.append(tkn) |
| 303 |
self.next() |
| 304 |
if not tokens: |
| 305 |
return None |
| 306 |
return Expression(lx.to_text(tokens).strip()) |
| 307 |
|
| 308 |
# def ops(self) -> list[OpName] | None: |
| 309 |
# if op := self.op(): |
| 310 |
# ops = [op] |
| 311 |
# while self.expect(lx.PLUS): |
| 312 |
# if op := self.op(): |
| 313 |
# ops.append(op) |
| 314 |
# return ops |
| 315 |
|
| 316 |
@contextual |
| 317 |
def op(self) -> OpName | None: |
| 318 |
if tkn := self.expect(lx.IDENTIFIER): |
| 319 |
return OpName(tkn.text) |
| 320 |
return None |
| 321 |
|
| 322 |
@contextual |
| 323 |
def macro_def(self) -> Macro | None: |
| 324 |
if tkn := self.expect(lx.MACRO): |
| 325 |
if self.expect(lx.LPAREN): |
| 326 |
if tkn := self.expect(lx.IDENTIFIER): |
| 327 |
if self.expect(lx.RPAREN): |
| 328 |
if self.expect(lx.EQUALS): |
| 329 |
if uops := self.uops(): |
| 330 |
self.require(lx.SEMI) |
| 331 |
res = Macro(tkn.text, uops) |
| 332 |
return res |
| 333 |
return None |
| 334 |
|
| 335 |
def uops(self) -> list[UOp] | None: |
| 336 |
if uop := self.uop(): |
| 337 |
uop = cast(UOp, uop) |
| 338 |
uops = [uop] |
| 339 |
while self.expect(lx.PLUS): |
| 340 |
if uop := self.uop(): |
| 341 |
uop = cast(UOp, uop) |
| 342 |
uops.append(uop) |
| 343 |
else: |
| 344 |
raise self.make_syntax_error("Expected op name or cache effect") |
| 345 |
return uops |
| 346 |
return None |
| 347 |
|
| 348 |
@contextual |
| 349 |
def uop(self) -> UOp | None: |
| 350 |
if tkn := self.expect(lx.IDENTIFIER): |
| 351 |
if self.expect(lx.DIVIDE): |
| 352 |
if num := self.expect(lx.NUMBER): |
| 353 |
try: |
| 354 |
size = int(num.text) |
| 355 |
except ValueError: |
| 356 |
raise self.make_syntax_error( |
| 357 |
f"Expected integer, got {num.text!r}" |
| 358 |
) |
| 359 |
else: |
| 360 |
return CacheEffect(tkn.text, size) |
| 361 |
raise self.make_syntax_error("Expected integer") |
| 362 |
else: |
| 363 |
return OpName(tkn.text) |
| 364 |
return None |
| 365 |
|
| 366 |
@contextual |
| 367 |
def family_def(self) -> Family | None: |
| 368 |
if (tkn := self.expect(lx.IDENTIFIER)) and tkn.text == "family": |
| 369 |
size = None |
| 370 |
if self.expect(lx.LPAREN): |
| 371 |
if tkn := self.expect(lx.IDENTIFIER): |
| 372 |
if self.expect(lx.COMMA): |
| 373 |
if not (size := self.expect(lx.IDENTIFIER)): |
| 374 |
if not (size := self.expect(lx.NUMBER)): |
| 375 |
raise self.make_syntax_error( |
| 376 |
"Expected identifier or number" |
| 377 |
) |
| 378 |
if self.expect(lx.RPAREN): |
| 379 |
if self.expect(lx.EQUALS): |
| 380 |
if not self.expect(lx.LBRACE): |
| 381 |
raise self.make_syntax_error("Expected {") |
| 382 |
if members := self.members(): |
| 383 |
if self.expect(lx.RBRACE) and self.expect(lx.SEMI): |
| 384 |
return Family( |
| 385 |
tkn.text, size.text if size else "", members |
| 386 |
) |
| 387 |
return None |
| 388 |
|
| 389 |
def flags(self) -> list[str]: |
| 390 |
here = self.getpos() |
| 391 |
if self.expect(lx.LPAREN): |
| 392 |
if tkn := self.expect(lx.IDENTIFIER): |
| 393 |
flags = [tkn.text] |
| 394 |
while self.expect(lx.COMMA): |
| 395 |
if tkn := self.expect(lx.IDENTIFIER): |
| 396 |
flags.append(tkn.text) |
| 397 |
else: |
| 398 |
break |
| 399 |
if not self.expect(lx.RPAREN): |
| 400 |
raise self.make_syntax_error("Expected comma or right paren") |
| 401 |
return flags |
| 402 |
self.setpos(here) |
| 403 |
return [] |
| 404 |
|
| 405 |
@contextual |
| 406 |
def pseudo_def(self) -> Pseudo | None: |
| 407 |
if (tkn := self.expect(lx.IDENTIFIER)) and tkn.text == "pseudo": |
| 408 |
size = None |
| 409 |
if self.expect(lx.LPAREN): |
| 410 |
if tkn := self.expect(lx.IDENTIFIER): |
| 411 |
if self.expect(lx.COMMA): |
| 412 |
flags = self.flags() |
| 413 |
else: |
| 414 |
flags = [] |
| 415 |
if self.expect(lx.RPAREN): |
| 416 |
if self.expect(lx.EQUALS): |
| 417 |
if not self.expect(lx.LBRACE): |
| 418 |
raise self.make_syntax_error("Expected {") |
| 419 |
if members := self.members(): |
| 420 |
if self.expect(lx.RBRACE) and self.expect(lx.SEMI): |
| 421 |
return Pseudo(tkn.text, flags, members) |
| 422 |
return None |
| 423 |
|
| 424 |
def members(self) -> list[str] | None: |
| 425 |
here = self.getpos() |
| 426 |
if tkn := self.expect(lx.IDENTIFIER): |
| 427 |
members = [tkn.text] |
| 428 |
while self.expect(lx.COMMA): |
| 429 |
if tkn := self.expect(lx.IDENTIFIER): |
| 430 |
members.append(tkn.text) |
| 431 |
else: |
| 432 |
break |
| 433 |
peek = self.peek() |
| 434 |
if not peek or peek.kind != lx.RBRACE: |
| 435 |
raise self.make_syntax_error("Expected comma or right paren") |
| 436 |
return members |
| 437 |
self.setpos(here) |
| 438 |
return None |
| 439 |
|
| 440 |
@contextual |
| 441 |
def block(self) -> Block | None: |
| 442 |
if self.c_blob(): |
| 443 |
return Block() |
| 444 |
return None |
| 445 |
|
| 446 |
def c_blob(self) -> list[lx.Token]: |
| 447 |
tokens: list[lx.Token] = [] |
| 448 |
level = 0 |
| 449 |
while tkn := self.next(raw=True): |
| 450 |
tokens.append(tkn) |
| 451 |
if tkn.kind in (lx.LBRACE, lx.LPAREN, lx.LBRACKET): |
| 452 |
level += 1 |
| 453 |
elif tkn.kind in (lx.RBRACE, lx.RPAREN, lx.RBRACKET): |
| 454 |
level -= 1 |
| 455 |
if level <= 0: |
| 456 |
break |
| 457 |
return tokens |
| 458 |
|
| 459 |
|
| 460 |
if __name__ == "__main__": |
| 461 |
import sys |
| 462 |
|
| 463 |
if sys.argv[1:]: |
| 464 |
filename = sys.argv[1] |
| 465 |
if filename == "-c" and sys.argv[2:]: |
| 466 |
src = sys.argv[2] |
| 467 |
filename = "<string>" |
| 468 |
else: |
| 469 |
with open(filename, "r") as f: |
| 470 |
src = f.read() |
| 471 |
srclines = src.splitlines() |
| 472 |
begin = srclines.index("// BEGIN BYTECODES //") |
| 473 |
end = srclines.index("// END BYTECODES //") |
| 474 |
src = "\n".join(srclines[begin + 1 : end]) |
| 475 |
else: |
| 476 |
filename = "<default>" |
| 477 |
src = "if (x) { x.foo; // comment\n}" |
| 478 |
parser = Parser(src, filename) |
| 479 |
x = parser.definition() |
| 480 |
print(x) |