Exemplo n.º 1
0
    def find_available(self, loaded_modules, remove=False):
        avail, groups = OrderedDict(), []
        for directory in self.modulepath(join=0):
            for (dirname, dirs, files) in os.walk(directory):
                this_group = []
                d = dirname.replace(directory, '')
                for filename in files:
                    filepath = op.join(dirname, filename)
                    modulename = op.join(d, filename).lstrip(op.sep)
                    loaded = modulename in loaded_modules
                    try:
                        module = m2.Module(filepath, name=modulename,
                                           loaded=loaded,
                                           on_load=self.on_module_load,
                                           on_unload=self.on_module_unload)
                    except (m2.NotAModuleError, m2.NoTCLModuleCommandError):
                        continue
                    if module.name not in avail:
                        # Precedence to modules earlier in path
                        avail[module.name] = module
                    this_group.append(module.name)
                groups.append((dirname, this_group))
        loaded = [avail[m] for m in loaded_modules]

        if remove:
            # tjfulle: should be logic for unloading modules that are 
            # already loaded but no longer on the path
            pass

        return avail, loaded, groups
Exemplo n.º 2
0
Arquivo: data.py Projeto: nellyv/mojo
def ImportFromData(module, data):
    """Adds to the pool of available kinds in the current module, the list of
  kinds provided by the imported module. Also creates a dict describing
  the imported module."""
    import_module = data['module']

    import_item = {}
    import_item['module_name'] = import_module.name
    import_item['namespace'] = import_module.namespace

    # Create a new module that contains only the needed values to prevent
    # accidentally introducing dependencies on currently-unneeded data.
    new_imported_module = mojom.Module(import_module.name,
                                       import_module.namespace,
                                       import_module.attributes)
    new_imported_module.path = import_module.path
    import_item['module'] = new_imported_module

    # Copy the struct kinds from our imports into the current module.
    importable_kinds = (mojom.Struct, mojom.Union, mojom.Enum, mojom.Interface)
    for kind in import_module.kinds.itervalues():
        if (isinstance(kind, importable_kinds) and kind.imported_from is None):
            kind = KindFromImport(kind, import_item)
            module.kinds[kind.spec] = kind
    # Ditto for values.
    for value in import_module.values.itervalues():
        if value.imported_from is None:
            # Values don't have shared definitions (since they're not nullable), so no
            # need to do anything special.
            value = copy.copy(value)
            value.imported_from = import_item
            module.values[value.GetSpec()] = value

    return import_item
Exemplo n.º 3
0
def update_blacklist():
    cnx = mysql.connector.connect(**db_config)
    cursor = cnx.cursor(buffered=True)
    qry = ("SELECT SmObjId FROM blacklist")
    cursor.execute(qry)
    for row in cursor:
        cursor2 = cnx.cursor()
        mod = m.Module(row[0])
        if mod.update():
            qry2 = "UPDATE blacklist SET PiqYear=%(PiqYear)s, PiqSession=%(PiqSession)s, held_in=%(held_in)s, title=%(title)s WHERE SmObjId=%(SmObjId)s;"
            val = {
                'SmObjId': mod.SmObjId,
                'PiqYear': mod.PiqYear,
                'PiqSession': mod.PiqSession,
                'held_in': mod.held_in,
                'title': mod.title
            }
        else:
            qry2 = "DELETE FROM blacklist WHERE SmObjId=%(SmObjId)s"
            val = {'SmObjId': mod.SmObjId}

        try:
            cursor2.execute(qry2, val)
        except mysql.connector.Error as err:
            print("Error: {}".format(err))
            return False
        cursor2.close()

    cnx.commit()
    cnx.close()
    return True
Exemplo n.º 4
0
    def __init__(self, arg=None, load=True):
        """ Initialize with a single filename or a list of them,
            a ConfigParser, or nothing for an empty pipeline"""
        if arg is None:
            arg = list()

        if isinstance(arg, config.Inifile):
            self.options = arg
        else:
            self.options = config.Inifile(arg)

        #This will be set later
        self.root_directory = self.options.get("runtime", "root", "cosmosis_none_signifier")
        if self.root_directory=="cosmosis_none_signifier":
            self.root_directory=None

        self.quiet = self.options.getboolean(PIPELINE_INI_SECTION, "quiet", True)
        self.debug = self.options.getboolean(PIPELINE_INI_SECTION, "debug", False)
        self.timing = self.options.getboolean(PIPELINE_INI_SECTION, "timing", False)
        shortcut = self.options.get(PIPELINE_INI_SECTION, "shortcut", "")
        if shortcut=="": shortcut=None

        # initialize modules
        self.modules = []
        if load and PIPELINE_INI_SECTION in self.options.sections():
            module_list = self.options.get(PIPELINE_INI_SECTION,
                                           "modules", "").split()

            for module_name in module_list:
                # identify module file

                filename = self.find_module_file(
                    self.options.get(module_name, "file"))

                # identify relevant functions
                setup_function = self.options.get(module_name,
                                                  "setup", "setup")
                exec_function = self.options.get(module_name,
                                                 "function", "execute")
                cleanup_function = self.options.get(module_name,
                                                    "cleanup", "cleanup")

                self.modules.append(module.Module(module_name,
                                                  filename,
                                                  setup_function,
                                                  exec_function,
                                                  cleanup_function,
                                                  self.root_directory))
            self.shortcut_module=0
            self.shortcut_data=None
            if shortcut is not None:
                try:
                    index = module_list.index(shortcut)
                except ValueError:
                    raise ValueError("You tried to set a shortcut in "
                        "the pipeline but I do not know module %s"%shortcut)
                if index == 0:
                    print "You set a shortcut in the pipeline but it was the first module."
                    print "It will make no difference."
                self.shortcut_module = index
Exemplo n.º 5
0
	def readRequirements(self,filename):
		tutorList = list()
		moduleList = list()
		with open(filename) as f:
			modules = False
			for line in f:
				#tutors are listed first, up until the breaker character, '==='
				if "===" in line:
					modules = True
				else:
					line = line.replace("\n","")
					line = line.split(",")
					#dealing with a tutor, their name is the first element in the list and the rest
					#are expertises of the tutor
					if not modules:
						expertise = list()
						for i in range(1,len(line)):
							expertise.append(line[i])
						tut = tutor.Tutor(name=line[0], expertise=expertise)
						tutorList.append(tut)
					else:
						#with modules, the code is the first element of the list, and the topics the rest
						topics = list()
						for i in range(1,len(line)):
							topics.append(line[i])
						mod = module.Module(name=line[0], topics=topics)
						moduleList.append(mod)
						if len(moduleList) == 25:
  							break

		#returns a list of tutor and module objects
		return [tutorList, moduleList]
Exemplo n.º 6
0
def add_blacklist(module_id):
    cnx = mysql.connector.connect(**db_config)
    qry = "INSERT IGNORE INTO blacklist (SmObjId, PiqYear, PiqSession, title, held_in) VALUES (%(SmObjId)s, %(PiqYear)s, %(PiqSession)s, %(title)s, %(held_in)s)"
    qry2 = "DELETE FROM whitelist WHERE SmObjId = %(SmObjId)s"
    module = m.Module(module_id)
    module.update()
    val = module.get_module()
    if val:
        try:
            cursor = cnx.cursor()
            cursor.execute(qry2, val)
            cnx.commit()
            cursor.close()
        except mysql.connector.Error as err:
            pass

        try:
            cursor = cnx.cursor()
            cursor.execute(qry, val)
            cnx.commit()
            cursor.close()
            cnx.close()
            return jsonify(val), 200
        except mysql.connector.Error as err:
            return "Error: {}".format(err), 409
    else:
        return 'No Module found', 404
Exemplo n.º 7
0
def test_product_metrics():
    full_path = '../test-data/curr/comment_test.java'
    prev_filename = '../test-data/prev/comment_test.java'
    mod = m.Module(full_path)
    mod = pdm.getProcuctMetrics(mod)
    # mod = psm.getProcessMetrics(mod, prev_filename)
    printModules(mod)
Exemplo n.º 8
0
 def __init__(self):
     self.uart = machine.UART(1, tx=17, rx=16)
     self.uart.init(9600, bits=8, parity=None, stop=1)
     self.callback = None
     if self._reset() == 1:
         raise module.Module('Module lorawan not connect')
     self._timer = None
     self.uartString = ''
     time.sleep(2)
Exemplo n.º 9
0
def fild_all_files(directory):
    list = []
    for root, dirs, files in os.walk(directory):
        for file_ in files:
            full_path = os.path.join(root, file_)
            # isJava = re.search(full_path, r'(\.java)$')
            isJava = re.search("\.JAVA$", full_path.upper())
            if isJava is not None:
                list.append(m.Module(full_path))
    return list
Exemplo n.º 10
0
    def add_module(self, filename):
        base = self.module_name(filename)

        # Check if module already exists
        if base in self._modules:
            return

        # Create new 'empty' module
        self._modules[base] = module.Module(base, os.path.dirname(filename))

        return True
Exemplo n.º 11
0
def BuildTestModule():
    module = mojom.Module('test', 'testspace')
    struct = module.AddStruct('teststruct')
    struct.AddField('testfield1', mojom.INT32)
    struct.AddField('testfield2', mojom.Array(mojom.INT32), 42)

    interface = module.AddInterface('Server')
    method = interface.AddMethod('Foo', 42)
    method.AddParameter('foo', mojom.INT32)
    method.AddParameter('bar', mojom.Array(struct))

    return module
Exemplo n.º 12
0
    def __init__(self, source, nvcc='nvcc', options=[], keep=False,
                 no_extern_c=False, arch=None, code=None, cache_dir=None,
                 include_dirs=[]):
        self._check_arch(arch)

        cubin = compile(source, nvcc, options, keep, no_extern_c, 
                        arch, code, cache_dir, include_dirs)

        import module
        self.module = module.Module(cubin)

        self.get_global = self.module.get_global
Exemplo n.º 13
0
def generate_stub():
    source_str = 'abcdefghijklmnopqrstuvwxyz'
    full_path = "".join([random.choice(source_str) for x in xrange(10)])
    mod = module.Module(full_path)
    mod.LOC = random.randint(1,100)
    mod.TChar = random.randint(1,100)
    mod.churnMetrics = random.randint(1,100)
    mod.relativeChrun = random.randint(1,100)
    mod.deletredChurn = random.randint(1,100)
    mod.ncdChurn = random.randint(1,100)
    mod.isNew = random.randint(1,100)

    return mod
Exemplo n.º 14
0
    def testGetUnionsAddsOrdinals(self):
        module = mojom.Module()
        union = module.AddUnion('a')
        union.AddField('a', mojom.BOOL)
        union.AddField('b', mojom.BOOL)
        union.AddField('c', mojom.BOOL, ordinal=10)
        union.AddField('d', mojom.BOOL)

        gen = generator.Generator(module)
        union = gen.GetUnions()[0]
        ordinals = [field.ordinal for field in union.fields]

        self.assertEquals([0, 1, 10, 11], ordinals)
Exemplo n.º 15
0
 def get_module(self, modulename):
     if op.isfile(op.realpath(modulename)):
         # Precedent to actual files
         try:
             loaded = self.is_loaded(modulename)
             modulepath = op.realpath(modulename)
             module = m2.Module(modulepath, name=modulename, loaded=loaded,
                                on_load=self.on_module_load,
                                on_unload=self.on_module_unload)
         except (m2.NotAModuleError, m2.NoTCLModuleCommandError):
             module = None
     elif op.isfile(op.join(os.getcwd(), modulename)):
         try:
             loaded = self.is_loaded(modulename)
             modulepath = op.join(os.getcwd(), modulename)
             module = m2.Module(modulepath, name=modulename, loaded=loaded,
                                on_load=self.on_module_load,
                                on_unload=self.on_module_unload)
         except:
             module = None
     else:
         module = self.avail.get(modulename)
     return module
Exemplo n.º 16
0
    def add_module(self, filename):
        base = self.module_name(filename)

        # Check if module already exists
        if base in self._modules:
            return

        # Create new 'empty' module
        mod = module.Module(base, os.path.dirname(filename))
        bisect.insort_right(self._modules, mod)

        # Reload the module
        self.reload_module(mod)
        return True
Exemplo n.º 17
0
def ModuleFromData(data):
    module = mojom.Module()
    module.kinds = {}
    for kind in mojom.PRIMITIVES:
        module.kinds[kind.spec] = kind

    module.values = {}

    module.name = data['name']
    module.namespace = data['namespace']
    # Imports must come first, because they add to module.kinds which is used
    # by by the others.
    module.imports = map(
        lambda import_data: ImportFromData(module, import_data),
        data['imports'])
    module.attributes = data.get('attributes')

    # First pass collects kinds.
    module.enums = map(lambda enum: EnumFromData(module, enum, None),
                       data['enums'])
    module.structs = map(lambda struct: StructFromData(module, struct),
                         data['structs'])
    module.unions = map(lambda union: UnionFromData(module, union),
                        data.get('unions', []))
    module.interfaces = map(
        lambda interface: InterfaceFromData(module, interface),
        data['interfaces'])
    module.constants = map(
        lambda constant: ConstantFromData(module, constant, None),
        data['constants'])

    # Second pass expands fields and methods. This allows fields and parameters
    # to refer to kinds defined anywhere in the mojom.
    for struct in module.structs:
        struct.fields = map(
            lambda field: StructFieldFromData(module, field, struct),
            struct.fields_data)
        del struct.fields_data
    for union in module.unions:
        union.fields = map(
            lambda field: UnionFieldFromData(module, field, union),
            union.fields_data)
        del union.fields_data
    for interface in module.interfaces:
        interface.methods = map(
            lambda method: MethodFromData(module, method, interface),
            interface.methods_data)
        del interface.methods_data

    return module
Exemplo n.º 18
0
    def __init__(self, graph, file_name):
        """Initializes a FileTranslator.

    Args:
      graph: {fidl_files_fidl.FidlFileGraph} containing the file to be
          translated.
      file_name: {str} key to the file to be translated in graph.files.
    """
        assert isinstance(graph, fidl_files_fidl.FidlFileGraph)
        self._type_cache = {}
        self._value_cache = {}
        self._constant_cache = {}
        self._graph = graph
        self._file_name = file_name
        self._types = {}
        self._module = module.Module()
        self._transitive_imports = {}
Exemplo n.º 19
0
 def __init__(self):
     self.VP = verilog_parser.ClassVerilogParser()
     self.module_lt = []
     self.wrap_module_lt = None
     # self.proc_inst = None
     self.inst_lt = []
     self.jinja_tmpl = Template(" ")
     self.jinja_tmpl.environment.variable_start_string = "[{["
     self.jinja_tmpl.environment.variable_end_string = "]}]"
     # self.proc_wrapper = None
     self.update = False
     self.genVerilogCodeTxt = ''
     self.CreateEmptyWrapper("new_wrapper")
     self.src_lt = []
     self.dest_lt = []
     self.proc_inst = module.Instance(module.Module("init"), 'init')
     pass
Exemplo n.º 20
0
    def ImportFromMojom(self, import_name):
        """Builds a dict representing an import.

    Args:
      import_name: {str} key to the imported file in graph.files.

    Returns:
      {dict} representing the imported file.
    """
        import_file = self._graph.files[import_name]
        import_module = module.Module()
        self.PopulateModuleMetadata(import_module, import_file)

        import_item = {
            'module_name': import_module.name,
            'namespace': import_module.namespace,
            'module': import_module,
        }
        return import_item
Exemplo n.º 21
0
    def ParseTxt(self):
        self.module_lt = []
        self.src_txt_all_orig = self.src_txt_all
        self.src_txt_all = re.sub(r"/\*[\s\w\S\W]+?\*/", "", self.src_txt_all)
        self.src_txt_all = re.sub(r"//.+", "", self.src_txt_all)
        self.src_txt_module_lt = re.findall(r"module[\w\s\W\S]+?endmodule",
                                            self.src_txt_all)
        self.src_num_module = len(self.src_txt_module_lt)
        print("Found moudule:", self.src_num_module)
        for src_moduleAll in self.src_txt_module_lt:
            self.ClearAllModuleInfo()
            re_res2_lt = []
            re_res2_lt = re.findall(
                r"(module [\s\w\S\W]+?);([\s\w\S\W]+?)endmodule",
                src_moduleAll)

            if (len(re_res2_lt) > 0):

                self.proc_module = module.Module('new')
                self.parse_succ = True
                self.src_module_title = re_res2_lt[0][0]
                self.src_body = re_res2_lt[0][1]

                self.__ParseModuleTitle()

                self.proc_module.SetModuleName(self.module_name)

                self.__ParseModuleBody_param()
                self.__ParseModuleBody_IO_scan()

                if (self.parse_succ == True):
                    print('Module parse success:%s' % (self.proc_module.name))
                    self.module_lt.append(self.proc_module)

            else:
                print("Module format error")
            pass
        pass
Exemplo n.º 22
0
    def __init__(self):
        """
        terminal command that using for convert .ui -> .py
        pyuic5 gui_files/mainwindow.ui -o python_gui_files/mainwindow.py
        """
        super().__init__()
        self._translate = QtCore.QCoreApplication.translate
        self.setupUi(self)
        self.module: module.Module = module.Module()

        self.PARAMSLABEL = []
        self.LINEEDIT = []
        # -- Module settings --
        self.moduleSettingsLineEdits = []
        self.done_module_settings = False
        self.__show_module_settings()

        # -- Fileset settings
        self.QSLineEdits = []
        self.__show_fileset()

        # -- Parameters settings

        self.parameters = {}
        self.__show_parameters()

        # buttons connection
        self.newProjectButton.clicked.connect(self.__newProject)
        self.loadProjectButton.clicked.connect(self.__loadProject)
        self.saveProjectButton.clicked.connect(self.__saveProject)
        self.saveModuleSettingsButton.clicked.connect(self.__save_module_settings)
        self.SaveFilesetButton.clicked.connect(self.__save_fileset)
        self.AddFileToFilesetButton.clicked.connect(self.__add_file_to_fileset)
        self.addParameterButton.clicked.connect(self.__add_parameter)

        self.show()
Exemplo n.º 23
0
 def _available(self):
     if self.i2c.is_ready(self.addr) or self.i2c.is_ready(self.addr):
         pass
     else:
         raise module.Module("Module Step motor maybe not connect")
Exemplo n.º 24
0
 def __newProject(self):
     self.module = module.Module()
     self.__show_module_settings()
     self.__show_fileset()
     self.__show_parameters()
Exemplo n.º 25
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import config
import module

####Lade das Configfile
cfg = config.Config()
cfg.readConfig()

modul = module.Module()

if cfg.rocketStops=="true" and cfg.lureModule=="true":
  print("Rocketstops und Lockmodule ausgew\U000000e4hlt")
  modul.full(cfg)
elif cfg.rocketStops =="false" and cfg.lureModule=="true":
  print("Nur Lockmodule ausgew\U000000e4hlt")
  modul.LockModulOnly(cfg)
elif cfg.rocketStops =="true" and cfg.lureModule=="false":
  print("Nur Rocketstops ausgew\U000000e4hlt")
  modul.rocketStopsOnly(cfg)
else:
	print("Es wurde nichts aktiviert. Pr\U000000fcfe im Configfile das die Attribute 'rocketStops' oder 'lureModule' auf 'true' gesetzt sind")
Exemplo n.º 26
0
 def _available(self):
     if self.i2c.is_ready(_addr) or self.i2c.is_ready(_addr):
         pass
     else:
         raise module.Module('module Servo maybe not connect')
Exemplo n.º 27
0
def parse(file_name):
    modules = []
    current_module = None
    line_n = 0
    f_line = ""
    variables = None
    try:
        with open(file_name, "r") as f:
            for f_line in f:
                line_n += 1
                f_line = f_line.strip()
                if f_line.find("#") >= 0:
                    line = f_line.split("#")[0].rstrip()
                else:
                    line = f_line
                if len(line) == 0:
                    continue
                words = line.split()
                visiblity = config.DEFAULT_VISIBILITY
                if words[0] in ["main", "public", "private"]:
                    visiblity = words[0]
                    words = words[1:]
                    if len(words) == 0:
                        raise ParserError("What??" % visiblity)
                if words[0] == "module":
                    if not len(words) in [2, 3]:
                        raise ParserError(
                            "%s argument for 'module'" %
                            ("Not enougth" if len(words) < 2 else "Too many"))
                    if words[1].endswith(":"):
                        words[1] = words[1][:-1]
                    rel = os.path.relpath(words[2] if len(words) == 3 else ".")
                    current_module = module.Module(
                        words[1],
                        os.path.abspath(
                            os.path.join(os.path.dirname(file_name), rel)))
                    current_module.is_main = visiblity == "main"
                    variables = module.get_variables(current_module)
                    modules.append(current_module)
                elif visiblity == "main":
                    raise ParserError(
                        "'main' visiblity is for module declaration")
                elif words[0] in MODULE_INSTRUCTIONS:
                    instr = MODULE_INSTRUCTIONS[words[0]]
                    args = [
                        utils.substitute_vars(w, variables) for w in words[1:]
                    ]
                    if instr[0] >= 0 and len(args) < instr[0]:
                        raise ParserError("Not enougth argument for '%s'" %
                                          words[0])
                    if instr[1] >= 0 and len(args) > instr[1]:
                        raise ParserError("Too many argument for '%s'" %
                                          words[0])
                    instr[2](current_module, args, visiblity)
                else:
                    raise ParserError("Unknow instruction '%s'" % words[0])
    except config.BaseError as e:
        raise ParserError("%s at line %d in %s \"%s\"" %
                          (str(e), line_n, os.path.relpath(file_name), f_line))
    except Exception as e:
        raise ParserError("Cannot open %s: %s" % (file_name, str(e)))
    return modules
Exemplo n.º 28
0
def MakePythonComponentLoaderModule(serviceManager, nsIFile):
    import module
    return module.Module( [PythonComponentLoader] )
Exemplo n.º 29
0
    def init_tree_var(self):

        if (len(self.directory) < 1):
            self.init_file_var()

        # Build routines list
        pre_rout_list = pr.parse(
            "subroutine",
            self.directory)  # routine name , definition file path

        # List of objects that are instances of Routine class.
        self.routines_list = [
            rt.Routine(one_routine[0], one_routine[1], pre_rout_list)
            for one_routine in pre_rout_list[1:]
        ]

        # Build modules list
        pre_mod_list = pr.parse(
            "module", self.directory)  # modules name , definition file path
        pre_mod_list_tmp = pre_mod_list[1:]
        pre_mod_list_tmp = np.unique(pre_mod_list_tmp, axis=0)
        pre_mod_list = np.array(["name", "path"], dtype='U200')
        for pre_mod_tmp in pre_mod_list_tmp:
            pre_mod_list = np.vstack([pre_mod_list, [pre_mod_tmp]])

        # List of objects that are instances of Module class.
        self.modules_list = [
            md.Module(one_module[0], one_module[1], pre_mod_list)
            for one_module in pre_mod_list[1:]
        ]

        # Build root

        if (self.fortree_type == "DEF_TREE"
                or self.fortree_type == "DEP_TREE"):
            self.branch_type = "DEF"
        elif (self.fortree_type == "CALL_TREE"):
            self.branch_type = "CALL"

        if self.program:
            self.root = tn.TreeNode(self.program,
                                    self.directory,
                                    self.routines_list,
                                    self.modules_list,
                                    self.branch_type,
                                    keyword="program",
                                    root_path=self.root_path)
        elif (self.module):
            self.root = tn.TreeNode(self.module,
                                    self.directory,
                                    self.routines_list,
                                    self.modules_list,
                                    self.branch_type,
                                    keyword="module",
                                    root_path=self.root_path)
        elif (self.routine):
            self.root = tn.TreeNode(self.routine,
                                    self.directory,
                                    self.routines_list,
                                    self.modules_list,
                                    self.branch_type,
                                    keyword="routine",
                                    root_path=self.root_path)
        else:
            tmp = pr.parse("program", self.directory)
            print(tmp)
            print("Try find program. Not implemented yet.")
            sys.exit()

        # Out-put tree array
        if (self.fortree_type == "CALL_TREE"):
            self.tree_arr = np.array(["caller", "callee", "callee_path"],
                                     dtype='U200')
        elif (self.fortree_type == "DEF_TREE"):
            self.tree_arr = np.array(["parent", "defined", "path"],
                                     dtype='U200')
        elif (self.fortree_type == "DEP_TREE"):
            self.tree_arr = np.array(["module", "user", "path"], dtype='U200')
        else:
            self.tree_arr = np.array(["parent", "child", "path"], dtype='U200')
Exemplo n.º 30
0
def _Module(tree, path, imports):
    """
  Args:
    tree: {ast.Mojom} The parse tree.
    path: {str} The path to the mojom file.
    imports: {Dict[str, mojom.Module]} Mapping from filenames, as they appear in
        the import list, to already processed modules. Used to process imports.

  Returns:
    {mojom.Module} An AST for the mojom.
  """
    module = mojom.Module(path=path)
    module.kinds = {}
    for kind in mojom.PRIMITIVES:
        module.kinds[kind.spec] = kind

    module.values = {}

    module.mojom_namespace = tree.module.mojom_namespace[
        1] if tree.module else ''
    # Imports must come first, because they add to module.kinds which is used
    # by by the others.
    module.imports = [
        _Import(module, imports[imp.import_filename])
        for imp in tree.import_list
    ]
    if tree.module and tree.module.attribute_list:
        assert isinstance(tree.module.attribute_list, ast.AttributeList)
        # TODO(vtl): Check for duplicate keys here.
        module.attributes = dict((attribute.key, attribute.value)
                                 for attribute in tree.module.attribute_list)

    filename = os.path.basename(path)
    # First pass collects kinds.
    module.enums = map(lambda enum: _Enum(module, enum, None),
                       _ElemsOfType(tree.definition_list, ast.Enum, filename))
    module.structs = map(
        lambda struct: _Struct(module, struct),
        _ElemsOfType(tree.definition_list, ast.Struct, filename))
    module.unions = map(
        lambda union: _Union(module, union),
        _ElemsOfType(tree.definition_list, ast.Union, filename))
    module.interfaces = map(
        lambda interface: _Interface(module, interface),
        _ElemsOfType(tree.definition_list, ast.Interface, filename))
    module.constants = map(
        lambda constant: _Constant(module, constant, None),
        _ElemsOfType(tree.definition_list, ast.Const, filename))

    # Second pass expands fields and methods. This allows fields and parameters
    # to refer to kinds defined anywhere in the mojom.
    all_defined_kinds = {}
    for struct in module.structs:
        struct.fields = map(lambda field: _StructField(module, field, struct),
                            struct.fields_data)
        del struct.fields_data
        all_defined_kinds[struct.spec] = struct
        for enum in struct.enums:
            all_defined_kinds[enum.spec] = enum
    for union in module.unions:
        union.fields = map(lambda field: _UnionField(module, field, union),
                           union.fields_data)
        del union.fields_data
        all_defined_kinds[union.spec] = union
    for interface in module.interfaces:
        interface.methods = map(
            lambda method: _Method(module, method, interface),
            interface.methods_data)
        del interface.methods_data
        all_defined_kinds[interface.spec] = interface
        for enum in interface.enums:
            all_defined_kinds[enum.spec] = enum
    for enum in module.enums:
        all_defined_kinds[enum.spec] = enum

    all_referenced_kinds = _CollectReferencedKinds(module,
                                                   all_defined_kinds.values())
    imported_kind_specs = set(all_referenced_kinds.keys()).difference(
        set(all_defined_kinds.keys()))
    module.imported_kinds = dict(
        (spec, all_referenced_kinds[spec]) for spec in imported_kind_specs)

    return module