micro_asm.py revision 4591:f275f155962a
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        print "About to sub %s for %s" % (val[1], val)
242        return val[1]
243    print "Looking for matches in %s" % t.value
244    t.value = unescapeParamsRE.sub(unescapeParams, t.value)
245    t.lexer.begin('asm')
246    return t
247
248# Braces enter and exit micro assembly
249def t_INITIAL_LBRACE(t):
250    r'\{'
251    t.lexer.begin('asm')
252    return t
253
254def t_asm_RBRACE(t):
255    r'\}'
256    t.lexer.begin('INITIAL')
257    return t
258
259# At the top level, keep track of newlines only for line counting.
260def t_INITIAL_NEWLINE(t):
261    r'\n+'
262    t.lineno += t.value.count('\n')
263
264# In the micro assembler, do line counting but also return a token. The
265# token is needed by the parser to detect the end of a statement.
266def t_asm_NEWLINE(t):
267    r'\n+'
268    t.lineno += t.value.count('\n')
269    return t
270
271# A newline or semi colon when looking for params signals that the statement
272# is over and the lexer should go back to looking for regular assembly.
273def t_params_NEWLINE(t):
274    r'\n+'
275    t.lineno += t.value.count('\n')
276    t.lexer.begin('asm')
277    return t
278
279def t_params_SEMI(t):
280    r';'
281    t.lexer.begin('asm')
282    return t
283
284# Basic regular expressions to pick out simple tokens
285t_ANY_LPAREN = r'\('
286t_ANY_RPAREN = r'\)'
287t_ANY_SEMI   = r';'
288t_ANY_DOT    = r'\.'
289
290t_ANY_ignore = ' \t\x0c'
291
292def t_ANY_error(t):
293    error(t.lineno, "illegal character '%s'" % t.value[0])
294    t.skip(1)
295
296##########################################################################
297#
298# Parser specification
299#
300##########################################################################
301
302# Start symbol for a file which may have more than one macroop or rom
303# specification.
304def p_file(t):
305    'file : opt_rom_or_macros'
306
307def p_opt_rom_or_macros_0(t):
308    'opt_rom_or_macros : '
309
310def p_opt_rom_or_macros_1(t):
311    'opt_rom_or_macros : rom_or_macros'
312
313def p_rom_or_macros_0(t):
314    'rom_or_macros : rom_or_macro'
315
316def p_rom_or_macros_1(t):
317    'rom_or_macros : rom_or_macros rom_or_macro'
318
319def p_rom_or_macro_0(t):
320    '''rom_or_macro : rom_block
321                    | macroop_def'''
322
323# Defines a section of microcode that should go in the current ROM
324def p_rom_block(t):
325    'rom_block : DEF ROM block SEMI'
326    if not t.parser.rom:
327        print_error("Rom block found, but no Rom object specified.")
328        raise TypeError, "Rom block found, but no Rom object was specified."
329    for statement in t[3].statements:
330        handle_statement(t.parser, t.parser.rom, statement)
331    t[0] = t.parser.rom
332
333# Defines a macroop that jumps to an external label in the ROM
334def p_macroop_def_0(t):
335    'macroop_def : DEF MACROOP ID LPAREN ID RPAREN SEMI'
336    if not t.parser.rom_macroop_type:
337        print_error("ROM based macroop found, but no ROM macroop class was specified.")
338        raise TypeError, "ROM based macroop found, but no ROM macroop class was specified."
339    macroop = t.parser.rom_macroop_type(t[3], t[5])
340    t.parser.macroops[t[3]] = macroop
341
342
343# Defines a macroop that is combinationally generated
344def p_macroop_def_1(t):
345    'macroop_def : DEF MACROOP ID block SEMI'
346    try:
347        curop = t.parser.macro_type(t[3])
348    except TypeError:
349        print_error("Error creating macroop object.")
350        raise
351    for statement in t[4].statements:
352        handle_statement(t.parser, curop, statement)
353    t.parser.macroops[t[3]] = curop
354
355# A block of statements
356def p_block(t):
357    'block : LBRACE statements RBRACE'
358    block = Block()
359    block.statements = t[2]
360    t[0] = block
361
362def p_statements_0(t):
363    'statements : statement'
364    if t[1]:
365        t[0] = [t[1]]
366    else:
367        t[0] = []
368
369def p_statements_1(t):
370    'statements : statements statement'
371    if t[2]:
372        t[1].append(t[2])
373    t[0] = t[1]
374
375def p_statement(t):
376    'statement : content_of_statement end_of_statement'
377    t[0] = t[1]
378
379# A statement can be a microop or an assembler directive
380def p_content_of_statement_0(t):
381    '''content_of_statement : microop
382                            | directive'''
383    t[0] = t[1]
384
385# Ignore empty statements
386def p_content_of_statement_1(t):
387    'content_of_statement : '
388    pass
389
390# Statements are ended by newlines or a semi colon
391def p_end_of_statement(t):
392    '''end_of_statement : NEWLINE
393                        | SEMI'''
394    pass
395
396# Different flavors of microop to avoid shift/reduce errors
397def p_microop_0(t):
398    'microop : labels ID'
399    microop = Microop()
400    microop.labels = t[1]
401    microop.mnemonic = t[2]
402    t[0] = microop
403
404def p_microop_1(t):
405    'microop : ID'
406    microop = Microop()
407    microop.mnemonic = t[1]
408    t[0] = microop
409
410def p_microop_2(t):
411    'microop : labels ID PARAMS'
412    microop = Microop()
413    microop.labels = t[1]
414    microop.mnemonic = t[2]
415    microop.params = t[3]
416    t[0] = microop
417
418def p_microop_3(t):
419    'microop : ID PARAMS'
420    microop = Microop()
421    microop.mnemonic = t[1]
422    microop.params = t[2]
423    t[0] = microop
424
425# Labels in the microcode
426def p_labels_0(t):
427    'labels : label'
428    t[0] = [t[1]]
429
430def p_labels_1(t):
431    'labels : labels label'
432    t[1].append(t[2])
433    t[0] = t[1]
434
435def p_label_0(t):
436    'label : ID COLON'
437    label = Label()
438    label.is_extern = False
439    label.text = t[1]
440    t[0] = label
441
442def p_label_1(t):
443    'label : EXTERN ID COLON'
444    label = Label()
445    label.is_extern = True
446    label.text = t[2]
447    t[0] = label
448
449# Directives for the macroop
450def p_directive_0(t):
451    'directive : DOT ID'
452    directive = Directive()
453    directive.name = t[2]
454    t[0] = directive
455
456def p_directive_1(t):
457    'directive : DOT ID PARAMS'
458    directive = Directive()
459    directive.name = t[2]
460    directive.params = t[3]
461    t[0] = directive
462
463# Parse error handler.  Note that the argument here is the offending
464# *token*, not a grammar symbol (hence the need to use t.value)
465def p_error(t):
466    if t:
467        error(t.lineno, "syntax error at '%s'" % t.value)
468    else:
469        error(0, "unknown syntax error", True)
470
471class MicroAssembler(object):
472
473    def __init__(self, macro_type, microops,
474            rom = None, rom_macroop_type = None):
475        self.lexer = lex.lex()
476        self.parser = yacc.yacc()
477        self.parser.macro_type = macro_type
478        self.parser.macroops = {}
479        self.parser.microops = microops
480        self.parser.rom = rom
481        self.parser.rom_macroop_type = rom_macroop_type
482
483    def assemble(self, asm):
484        self.parser.parse(asm, lexer=self.lexer)
485        # Begin debug printing
486        for macroop in self.parser.macroops.values():
487            print macroop
488        print self.parser.rom
489        # End debug printing
490        macroops = self.parser.macroops
491        self.parser.macroops = {}
492        return macroops
493