micro_asm.py revision 4603:a120ca8d8fe8
1# Copyright (c) 2003-2005 The Regents of The University of Michigan 2# All rights reserved. 3# 4# Redistribution and use in source and binary forms, with or without 5# modification, are permitted provided that the following conditions are 6# met: redistributions of source code must retain the above copyright 7# notice, this list of conditions and the following disclaimer; 8# redistributions in binary form must reproduce the above copyright 9# notice, this list of conditions and the following disclaimer in the 10# documentation and/or other materials provided with the distribution; 11# neither the name of the copyright holders nor the names of its 12# contributors may be used to endorse or promote products derived from 13# this software without specific prior written permission. 14# 15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26# 27# Authors: Gabe Black 28 29import os 30import sys 31import re 32import string 33import traceback 34# get type names 35from types import * 36 37# Prepend the directory where the PLY lex & yacc modules are found 38# to the search path. 39sys.path[0:0] = [os.environ['M5_PLY']] 40 41from ply import lex 42from ply import yacc 43 44########################################################################## 45# 46# Base classes for use outside of the assembler 47# 48########################################################################## 49 50class Micro_Container(object): 51 def __init__(self, name): 52 self.microops = [] 53 self.name = name 54 self.directives = {} 55 self.micro_classes = {} 56 self.labels = {} 57 58 def add_microop(self, microop): 59 self.microops.append(microop) 60 61 def __str__(self): 62 string = "%s:\n" % self.name 63 for microop in self.microops: 64 string += " %s\n" % microop 65 return string 66 67class Combinational_Macroop(Micro_Container): 68 pass 69 70class Rom_Macroop(object): 71 def __init__(self, name, target): 72 self.name = name 73 self.target = target 74 75 def __str__(self): 76 return "%s: %s\n" % (self.name, self.target) 77 78class Rom(Micro_Container): 79 def __init__(self, name): 80 super(Rom, self).__init__(name) 81 self.externs = {} 82 83########################################################################## 84# 85# Support classes 86# 87########################################################################## 88 89class Label(object): 90 def __init__(self): 91 self.extern = False 92 self.name = "" 93 94class Block(object): 95 def __init__(self): 96 self.statements = [] 97 98class Statement(object): 99 def __init__(self): 100 self.is_microop = False 101 self.is_directive = False 102 self.params = "" 103 104class Microop(Statement): 105 def __init__(self): 106 super(Microop, self).__init__() 107 self.mnemonic = "" 108 self.labels = [] 109 self.is_microop = True 110 111class Directive(Statement): 112 def __init__(self): 113 super(Directive, self).__init__() 114 self.name = "" 115 self.is_directive = True 116 117########################################################################## 118# 119# Functions that handle common tasks 120# 121########################################################################## 122 123def print_error(message): 124 print 125 print "*** %s" % message 126 print 127 128def handle_statement(parser, container, statement): 129 if statement.is_microop: 130 try: 131 microop = eval('parser.microops[statement.mnemonic](%s)' % 132 statement.params) 133 except: 134 print_error("Error creating microop object with mnemonic %s." % \ 135 statement.mnemonic) 136 raise 137 try: 138 for label in statement.labels: 139 container.labels[label.name] = microop 140 if label.extern: 141 container.externs[label.name] = microop 142 container.add_microop(microop) 143 except: 144 print_error("Error adding microop.") 145 raise 146 elif statement.is_directive: 147 try: 148 eval('container.directives[statement.name](%s)' % statement.params) 149 except: 150 print_error("Error executing directive.") 151 print container.directives 152 raise 153 else: 154 raise Exception, "Didn't recognize the type of statement", statement 155 156########################################################################## 157# 158# Lexer specification 159# 160########################################################################## 161 162# Error handler. Just call exit. Output formatted to work under 163# Emacs compile-mode. Optional 'print_traceback' arg, if set to True, 164# prints a Python stack backtrace too (can be handy when trying to 165# debug the parser itself). 166def error(lineno, string, print_traceback = False): 167 # Print a Python stack backtrace if requested. 168 if (print_traceback): 169 traceback.print_exc() 170 if lineno != 0: 171 line_str = "%d:" % lineno 172 else: 173 line_str = "" 174 sys.exit("%s %s" % (line_str, string)) 175 176reserved = ('DEF', 'MACROOP', 'ROM', 'EXTERN') 177 178tokens = reserved + ( 179 # identifier 180 'ID', 181 # arguments for microops and directives 182 'PARAMS', 183 184 'LPAREN', 'RPAREN', 185 'LBRACE', 'RBRACE', 186 'COLON', 'SEMI', 'DOT', 187 'NEWLINE' 188 ) 189 190# New lines are ignored at the top level, but they end statements in the 191# assembler 192states = ( 193 ('asm', 'exclusive'), 194 ('params', 'exclusive'), 195) 196 197reserved_map = { } 198for r in reserved: 199 reserved_map[r.lower()] = r 200 201# Ignore comments 202def t_ANY_COMMENT(t): 203 r'\#[^\n]*(?=\n)' 204 205def t_ANY_MULTILINECOMMENT(t): 206 r'/\*([^/]|((?<!\*)/))*\*/' 207 208# A colon marks the end of a label. It should follow an ID which will 209# put the lexer in the "params" state. Seeing the colon will put it back 210# in the "asm" state since it knows it saw a label and not a mnemonic. 211def t_params_COLON(t): 212 r':' 213 t.lexer.begin('asm') 214 return t 215 216# An "ID" in the micro assembler is either a label, directive, or mnemonic 217# If it's either a directive or a mnemonic, it will be optionally followed by 218# parameters. If it's a label, the following colon will make the lexer stop 219# looking for parameters. 220def t_asm_ID(t): 221 r'[A-Za-z_]\w*' 222 t.type = reserved_map.get(t.value, 'ID') 223 t.lexer.begin('params') 224 return t 225 226# If there is a label and you're -not- in the assember (which would be caught 227# above), don't start looking for parameters. 228def t_ANY_ID(t): 229 r'[A-Za-z_]\w*' 230 t.type = reserved_map.get(t.value, 'ID') 231 return t 232 233# Parameters are a string of text which don't contain an unescaped statement 234# statement terminator, ie a newline or semi colon. 235def t_params_PARAMS(t): 236 r'([^\n;\\]|(\\[\n;\\]))+' 237 t.lineno += t.value.count('\n') 238 unescapeParamsRE = re.compile(r'(\\[\n;\\])') 239 def unescapeParams(mo): 240 val = mo.group(0) 241 return val[1] 242 t.value = unescapeParamsRE.sub(unescapeParams, t.value) 243 t.lexer.begin('asm') 244 return t 245 246# Braces enter and exit micro assembly 247def t_INITIAL_LBRACE(t): 248 r'\{' 249 t.lexer.begin('asm') 250 return t 251 252def t_asm_RBRACE(t): 253 r'\}' 254 t.lexer.begin('INITIAL') 255 return t 256 257# At the top level, keep track of newlines only for line counting. 258def t_INITIAL_NEWLINE(t): 259 r'\n+' 260 t.lineno += t.value.count('\n') 261 262# In the micro assembler, do line counting but also return a token. The 263# token is needed by the parser to detect the end of a statement. 264def t_asm_NEWLINE(t): 265 r'\n+' 266 t.lineno += t.value.count('\n') 267 return t 268 269# A newline or semi colon when looking for params signals that the statement 270# is over and the lexer should go back to looking for regular assembly. 271def t_params_NEWLINE(t): 272 r'\n+' 273 t.lineno += t.value.count('\n') 274 t.lexer.begin('asm') 275 return t 276 277def t_params_SEMI(t): 278 r';' 279 t.lexer.begin('asm') 280 return t 281 282# Basic regular expressions to pick out simple tokens 283t_ANY_LPAREN = r'\(' 284t_ANY_RPAREN = r'\)' 285t_ANY_SEMI = r';' 286t_ANY_DOT = r'\.' 287 288t_ANY_ignore = ' \t\x0c' 289 290def t_ANY_error(t): 291 error(t.lineno, "illegal character '%s'" % t.value[0]) 292 t.skip(1) 293 294########################################################################## 295# 296# Parser specification 297# 298########################################################################## 299 300# Start symbol for a file which may have more than one macroop or rom 301# specification. 302def p_file(t): 303 'file : opt_rom_or_macros' 304 305def p_opt_rom_or_macros_0(t): 306 'opt_rom_or_macros : ' 307 308def p_opt_rom_or_macros_1(t): 309 'opt_rom_or_macros : rom_or_macros' 310 311def p_rom_or_macros_0(t): 312 'rom_or_macros : rom_or_macro' 313 314def p_rom_or_macros_1(t): 315 'rom_or_macros : rom_or_macros rom_or_macro' 316 317def p_rom_or_macro_0(t): 318 '''rom_or_macro : rom_block 319 | macroop_def''' 320 321# Defines a section of microcode that should go in the current ROM 322def p_rom_block(t): 323 'rom_block : DEF ROM block SEMI' 324 if not t.parser.rom: 325 print_error("Rom block found, but no Rom object specified.") 326 raise TypeError, "Rom block found, but no Rom object was specified." 327 for statement in t[3].statements: 328 handle_statement(t.parser, t.parser.rom, statement) 329 t[0] = t.parser.rom 330 331# Defines a macroop that jumps to an external label in the ROM 332def p_macroop_def_0(t): 333 'macroop_def : DEF MACROOP ID LPAREN ID RPAREN SEMI' 334 if not t.parser.rom_macroop_type: 335 print_error("ROM based macroop found, but no ROM macroop class was specified.") 336 raise TypeError, "ROM based macroop found, but no ROM macroop class was specified." 337 macroop = t.parser.rom_macroop_type(t[3], t[5]) 338 t.parser.macroops[t[3]] = macroop 339 340 341# Defines a macroop that is combinationally generated 342def p_macroop_def_1(t): 343 'macroop_def : DEF MACROOP ID block SEMI' 344 try: 345 curop = t.parser.macro_type(t[3]) 346 except TypeError: 347 print_error("Error creating macroop object.") 348 raise 349 for statement in t[4].statements: 350 handle_statement(t.parser, curop, statement) 351 t.parser.macroops[t[3]] = curop 352 353# A block of statements 354def p_block(t): 355 'block : LBRACE statements RBRACE' 356 block = Block() 357 block.statements = t[2] 358 t[0] = block 359 360def p_statements_0(t): 361 'statements : statement' 362 if t[1]: 363 t[0] = [t[1]] 364 else: 365 t[0] = [] 366 367def p_statements_1(t): 368 'statements : statements statement' 369 if t[2]: 370 t[1].append(t[2]) 371 t[0] = t[1] 372 373def p_statement(t): 374 'statement : content_of_statement end_of_statement' 375 t[0] = t[1] 376 377# A statement can be a microop or an assembler directive 378def p_content_of_statement_0(t): 379 '''content_of_statement : microop 380 | directive''' 381 t[0] = t[1] 382 383# Ignore empty statements 384def p_content_of_statement_1(t): 385 'content_of_statement : ' 386 pass 387 388# Statements are ended by newlines or a semi colon 389def p_end_of_statement(t): 390 '''end_of_statement : NEWLINE 391 | SEMI''' 392 pass 393 394# Different flavors of microop to avoid shift/reduce errors 395def p_microop_0(t): 396 'microop : labels ID' 397 microop = Microop() 398 microop.labels = t[1] 399 microop.mnemonic = t[2] 400 t[0] = microop 401 402def p_microop_1(t): 403 'microop : ID' 404 microop = Microop() 405 microop.mnemonic = t[1] 406 t[0] = microop 407 408def p_microop_2(t): 409 'microop : labels ID PARAMS' 410 microop = Microop() 411 microop.labels = t[1] 412 microop.mnemonic = t[2] 413 microop.params = t[3] 414 t[0] = microop 415 416def p_microop_3(t): 417 'microop : ID PARAMS' 418 microop = Microop() 419 microop.mnemonic = t[1] 420 microop.params = t[2] 421 t[0] = microop 422 423# Labels in the microcode 424def p_labels_0(t): 425 'labels : label' 426 t[0] = [t[1]] 427 428def p_labels_1(t): 429 'labels : labels label' 430 t[1].append(t[2]) 431 t[0] = t[1] 432 433def p_label_0(t): 434 'label : ID COLON' 435 label = Label() 436 label.is_extern = False 437 label.text = t[1] 438 t[0] = label 439 440def p_label_1(t): 441 'label : EXTERN ID COLON' 442 label = Label() 443 label.is_extern = True 444 label.text = t[2] 445 t[0] = label 446 447# Directives for the macroop 448def p_directive_0(t): 449 'directive : DOT ID' 450 directive = Directive() 451 directive.name = t[2] 452 t[0] = directive 453 454def p_directive_1(t): 455 'directive : DOT ID PARAMS' 456 directive = Directive() 457 directive.name = t[2] 458 directive.params = t[3] 459 t[0] = directive 460 461# Parse error handler. Note that the argument here is the offending 462# *token*, not a grammar symbol (hence the need to use t.value) 463def p_error(t): 464 if t: 465 error(t.lineno, "syntax error at '%s'" % t.value) 466 else: 467 error(0, "unknown syntax error", True) 468 469class MicroAssembler(object): 470 471 def __init__(self, macro_type, microops, 472 rom = None, rom_macroop_type = None): 473 self.lexer = lex.lex() 474 self.parser = yacc.yacc() 475 self.parser.macro_type = macro_type 476 self.parser.macroops = {} 477 self.parser.microops = microops 478 self.parser.rom = rom 479 self.parser.rom_macroop_type = rom_macroop_type 480 481 def assemble(self, asm): 482 self.parser.parse(asm, lexer=self.lexer) 483 # Begin debug printing 484 #for macroop in self.parser.macroops.values(): 485 # print macroop 486 #print self.parser.rom 487 # End debug printing 488 macroops = self.parser.macroops 489 self.parser.macroops = {} 490 return macroops 491