|
| 1 | +# |
| 2 | +# The implementation of annotation parser |
| 3 | +# |
| 4 | + |
| 5 | +import re, sys |
| 6 | +from orio.main.util.globals import * |
| 7 | + |
| 8 | +#---------------------------------------------------------------- |
| 9 | + |
| 10 | +class AnnParser: |
| 11 | + '''The class definition for the annotation parser''' |
| 12 | + |
| 13 | + def __init__(self, perf_params): |
| 14 | + '''To instantiate the annotation parser''' |
| 15 | + |
| 16 | + self.perf_params = perf_params |
| 17 | + |
| 18 | + def parse(self, text): |
| 19 | + '''Parse the annotation text to get variable-value pairs''' |
| 20 | + |
| 21 | + # remember the given code text |
| 22 | + orig_text = text |
| 23 | + |
| 24 | + # regular expressions |
| 25 | + __python_exp_re = r'\s*((.|\n)*?);\s*' |
| 26 | + __var_re = r'\s*([A-Za-z_]\w*)\s*' |
| 27 | + __semi_re = r'\s*;\s*' |
| 28 | + __equal_re = r'\s*=\s*' |
| 29 | + |
| 30 | + # initialize the data structure to store all variable-value pairs |
| 31 | + var_val_pairs = [] |
| 32 | + |
| 33 | + # get all variable-value pairs |
| 34 | + while True: |
| 35 | + if (not text) or text.isspace(): |
| 36 | + break |
| 37 | + m = re.match(__var_re, text) |
| 38 | + if not m: |
| 39 | + err('orio.module.chill.ann_parser: Pluto: annotation syntax error: "%s"' % orig_text) |
| 40 | + text = text[m.end():] |
| 41 | + var = m.group(1) |
| 42 | + m = re.match(__equal_re, text) |
| 43 | + if not m: |
| 44 | + err('orio.module.chill.ann_parser: Pluto: annotation syntax error: "%s"' % orig_text) |
| 45 | + text = text[m.end():] |
| 46 | + if text.count(';') == 0: |
| 47 | + err('orio.module.chill.ann_parser: Pluto: annotation syntax error: "%s"' % orig_text) |
| 48 | + m = re.match(__python_exp_re, text) |
| 49 | + if not m: |
| 50 | + err('orio.module.pluto.ann_parser: Pluto: annotation syntax error: "%s"' % orig_text) |
| 51 | + text = text[m.end():] |
| 52 | + val = m.group(1) |
| 53 | + var_val_pairs.append((var, val)) |
| 54 | + |
| 55 | + # evaluate all values and check their semantics |
| 56 | + n_var_val_pairs = [] |
| 57 | + for var, val in var_val_pairs: |
| 58 | + val = self.__evalExp(val) |
| 59 | + n_var_val_pairs.append((var, val)) |
| 60 | + var_val_pairs = n_var_val_pairs |
| 61 | + |
| 62 | + # return all variable value pairs |
| 63 | + return var_val_pairs |
| 64 | + |
| 65 | + |
| 66 | + #------------------------------------------------------------ |
| 67 | + # Private |
| 68 | + |
| 69 | + def __evalExp(self, text): |
| 70 | + '''Evaluate the given expression text''' |
| 71 | + |
| 72 | + try: |
| 73 | + val = eval(text, self.perf_params) |
| 74 | + except Exception, e: |
| 75 | + err('orio.module.pluto.ann_parser: failed to evaluate expression: "%s"\n --> %s: %s' % (text, e.__class__.__name__, e)) |
| 76 | + return val |
| 77 | + |
| 78 | + |
0 commit comments