Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 83 lines (57 sloc) 2.125 kb
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
from misc import ManoCollapserError
from objs import *


NAMES_COUNT = 0


def genId():
  global NAMES_COUNT
  NAMES_COUNT += 1
  return 'q%05d' % NAMES_COUNT


def collapse_program(functionset):
  global NAMES_COUNT

  if not (isinstance(functionset, dict)):
    raise ManoCollapserError('Input program is not a dictionary of functions.')

  NAMES_COUNT = 0

  # Construct lookup table.
  global_lookup = {'main': 'main', 'null': 'null'}
  for funcname in functionset:
    if funcname != 'main':
      global_lookup[funcname] = genId()

  for func in functionset.values():
    lookup = {}
    lookup.update(global_lookup)

    varnames = func.vars.keys()
    for varname in varnames:
      lookup[varname] = genId()
      func.vars[lookup[varname]] = func.vars[varname]
      del func.vars[varname]

    for i in range(len(func.params)):
      func.params[i] = lookup[func.params[i]]

    for line in func.code:
      attrs = ['label', 'condition', 'target', 'index']

      for attr in attrs:
        if hasattr(line, attr) and getattr(line, attr):
          name = getattr(line, attr)

          if name not in lookup:
            lookup[name] = genId()

          setattr(line, attr, lookup[name])

      if hasattr(line, 'expression'):
        exp = line.expression
        attrs = ['function', 'name', 'index', 'operand', 'left', 'right']

        for attr in attrs:
          if hasattr(exp, attr) and getattr(exp, attr):
            name = getattr(exp, attr)

            if name not in lookup:
              lookup[name] = genId()

            setattr(exp, attr, lookup[name])

        if hasattr(exp, 'arguments'):
          for i in range(len(exp.arguments)):
            name = exp.arguments[i]

            if name not in lookup:
              lookup[name] = genId()

            exp.arguments[i] = lookup[name]

  # Rename functions.
  funcs = functionset.keys()
  for funcname in funcs:
    if funcname != 'main':
      functionset[lookup[funcname]] = functionset[funcname]
      del functionset[funcname]

  return functionset
Something went wrong with that request. Please try again.