def find_element(self, by): # TODO: this method has to be modified! Add very basic design. if typecheck.is_string(by): for element in self.get_elements(): if element.get_designator() == by: return element return None
def set_memory_model(self, model): """Set memory model (not case sensetive). Available models: ======= ================================================================ Model Description ======= ================================================================ cog Generate code for COG model. In this model the code is placed in cog internal memory (which has only 2K). Data is placed in hub memory. This is the native execution mode, but is very restricted because of the small code size available. lmm Generate code for LMM (Large Memory Model). In this model both code and data are placed in hub. A small kernel runs in cog memory to fetch code and execute it. This is the default. xmm Generate code for XMM (eXternal Memory Model). In this model both code and data are placed in external memory (flash or RAM); only the stack remains in the hub memory. A kernel is run in cog memory to fetch instructions and data from the external memory. xmmc Generate code for XMMC (eXternal Memory Model - Code). In this model code is placed in external memory (flash or RAM) and data is placed in the hub. A kernel is run in cog memory to fetch instructions from the external memory. ======= ================================================================ :param model: A string that represents model type. :raises: TypeError """ if not typecheck.is_string(model): raise TypeError("Must be string.") self._memory_model = model.lower()
def __init__(self, name, size=0): if not typecheck.is_string(name): raise TypeError('Field name has to be a string') self._name = name self._size = 0 if size: self.size = size
def add_include_dir(self, path): """Add `path` to the list of directories that will be searched for header files. The compiler is instructed to search directories in the order in which they are supplied by successive calls to :func:`add_include_dir()`. """ if not typecheck.is_string(path): raise TypeError() self._include_dirs.append(path)
def set_name(self, name): """Set application name. :param name: A string. """ if not typecheck.is_string(name): raise TypeError() self._name = name
def has_property(self, name): """Returns whether or not the primitive has a property `property_`. The `property_` can be defined as a string or instance of :class:`Property` class. """ if not typecheck.is_string(name): raise TypeError() return name in self._properties
def set_name(self, name): """Set mapping name. :param name: A string that will represent mapping name. """ if not typecheck.is_string(name): raise TypeError("name must be string") self._name = name
def identify_compiler(object_): if typecheck.is_string(object_): return _COMPILER_CLASSES.get(object_, None) elif typecheck.is_class(object_): if _fix_compiler_name(object_.__name__) in _COMPILER_CLASSES: return _COMPILER_CLASSES[_fix_compiler_name(object_.__name__)] elif isinstance(object_, Compiler): return identify_compiler(object_.__class__) return None
def set_label(self, label): """Set message label. :param label: A string that represents message label. :raises: TypeError """ if not typecheck.is_string(label): raise TypeError('`label` has to be a string') self._label = label
def buildpath(self, path, recursive=True): """Path will be created if it doesn't exist.""" if typecheck.is_list(path): path = path_utils.join(*path) elif not typecheck.is_string(path): raise TypeError("path can be only a string or list") path = path_utils.join(self.get_build_dir(), path) if path_utils.exists(path): return path return path_utils.touch(path, recursive=recursive)
def is_home_dir(cls, path): """Returns whether or not a given path is application home directory. :returns: `True` or `False`. :raises: :class:`TypeError`, :class:`IOError` """ if not typecheck.is_string(path): raise TypeError("'path' has to be a string") elif not path_utils.exists(path): raise IOError("'%s' path doesn't exist" % path) return SETTINGS_DIR in os.listdir(path)
def new_compiler(name, args={}): """Returns :class:`Compiler` instance. Returns ``None`` if compiler is not supported. """ if not typecheck.is_string(name): raise Exception("Must be string") name = _fix_compiler_name() class_ = _COMPILER_CLASSES.get(name, None) if not class_: print "Compiler '%s' is not supported" % name return None return class_(**args)
def register_port(self, port, name): """Registers port within this mapping by the given name. :param port: A :class:`Port` derived instance. :param name: A string that represents name to which this port will be associated. :raises: TypeError """ if not typecheck.is_string(name): raise TypeError("name must be a string") if not isinstance(port, Port): raise TypeError("port must be derived from Port") self._ports[name] = port
def add_source(self, source): """The source may have any type, it can be another rule, string, function or an outside object. However, it cannot be None. Returns source, once it has been added. """ if not source: raise TypeError() # The source is an object or another rule. if (isinstance(source, object) and not typecheck.is_function(source) and \ not typecheck.is_string(source)) or \ (typecheck.is_string(source) and source.startswith(":")): # First of all check for attribute "__build__" and call it to resolve # dependencies. if hasattr(source, "__build__"): self._add_callable_source(source.__build__) elif callable(source): self._add_callable_source(source.__call__) rule = parse_address(source) if rule: if source not in self.get_dependencies(): self.add_dependency(rule) source = rule #else: # logger.warning("Cannot find appropriate rule for the source: %s" % # source) # Source is a function or something that we should call. The result is # assumed to be an extra sources that will be added by add_sources(). elif callable(source): self._add_callable_source(source) return elif typecheck.is_string(source): if not os.path.isabs(source): source = os.path.abspath(os.path.join(self._work_dir, source)) # FIXME: can be add not string based sources? if typecheck.is_string(source) or isinstance(source, Rule): self._sources.append(source) return source
def __init__(self, target=None, name=None, execute=None, deps=[]): """Each rule has a name that identifies it within existed context. In case name wasn't provided, it becomes a target and vice-versa. """ if not target and not name: raise Exception("target and/or name have to be provided") if name and not typecheck.is_string(name): raise TypeError("name has to be a string: %s,%s" % (name, target)) self._target = target if not name: if typecheck.is_string(target): name = target elif typecheck.is_class(target) or typecheck.is_function(target): name = target.__name__ else: name = "i%d" % id(target) self._name = name self._description = None self._address = None self._address = self.locate() self._dependencies = [] # TODO: deprecated self._properties = dict() self._build_dir = None # TODO: test on windows and other systems! self.set_build_dir(path_utils.join( bb.config.user_settings.get("b3", "builddir"), os.getcwd()[1:])) if hasattr(self.__class__, "properties"): self.add_properties(self.__class__.properties) register_rule(self) if execute: if not callable(execute): raise TypeError() self.execute = types.MethodType(execute, self) # Defer dependency resolution after parsing the current BUILD file to # allow for forward references self._post_init(self._finalize_deps, deps)
def parse_address(spec): context = Context.locate() address = None if typecheck.is_string(spec): if spec.startswith(':'): # the :[rule] could be in a sibling BUILD - so parse using the canonical # address pathish = "%s:%s" % (context.buildfile.canonical_relpath, spec[1:]) address = get_address(context.buildfile.root_dir, pathish, False) else: address = get_address(context.buildfile.root_dir, spec, False) else: for child_target_class in bb.object.get_all_subclasses(spec): for parent_target_class, rule_classes in _dynamic_rules.items(): if issubclass(child_target_class, parent_target_class): rule = parse_address(":i%s" % id(rule_classes)) if not rule: deps = map(lambda rc: rc(target=spec), rule_classes) rule = Fork(name="i%s" % id(rule_classes), deps=deps) return rule return None if not address else get_rule(address)
def find_home_dir(cls, path): """Finds top directory of an application by a given path and returns home path. Returns `None` if home direcotry cannot be identified. :param path: Path to directory. :returns: Path as string or `None`. """ if not typecheck.is_string(path): raise TypeError("'path' must be a string") elif not len(path): raise TypeError("'path' is empty") path = path_utils.realpath(path) if path_utils.isfile(path): (path, _) = path_utils.split(path) while path is not os.sep: if os.path.exists(path) and os.path.isdir(path): if cls.is_home_dir(path): return path (path, _) = path_utils.split(path) return None
def register_thread(self, thread, name=None): """Registers thread by its name. The name has to be unique within this mapping. If thread doesn't have a name and it wasn't provided, mapping will try to use its name format to generate one. If the thread has a port, this port will be registered by thread's name. .. seealso:: :func:`~bb.app.os.thread.Thread.get_name_format` .. todo:: Improve name generation within a mapping; it has to be unique. :param thread: A :class:`~bb.app.os.thread.Thread` instance. :param name: Another name to register `thread`. :returns: A :class:`~bb.app.os.thread.Thread` instance. :raises: :class:`TypeError` """ if not isinstance(thread, Thread): raise TypeError("Must be derived from bb.app.os.Thread: %s", thread) if name and not typecheck.is_string(name): raise TypeError() if name: thread.set_name(name) else: if thread.get_name() is None: frmt = thread.get_name_format() if not frmt: logger.warning("Thread %s doesn't have a name and the format cannot" "be obtained to generate one." % thread) return thread.set_name(frmt % self.get_num_threads()) name = thread.get_name() if thread.has_port(): self.register_port(thread.get_port(), name) self._threads[name] = thread return thread
def execute(self): print("Build cc binary '%s' with '%s'" % (self.get_name(), self.compiler.__class__.__name__)) buildfile.dependency_graph.resolve_forks() # NOTE: this has to be fixed self.compiler.add_include_dir(self.get_build_dir()) for src in self.get_sources(): if typecheck.is_string(src): self.compiler.add_file(src) elif isinstance(src, Fileset): self.compiler.add_files(src.get_sources()) for dep in self.get_dependencies(): if isinstance(dep, CCLibrary): self.compiler.add_files(dep.get_sources()) self.compiler.add_include_dirs(dep.get_includes()) if not self.compiler.get_files(): print("No source files", file=sys.stderr) exit(0) self.compiler.add_include_dirs(self.get_includes()) self.compiler.set_output_filename(self.get_name()) try: self.compiler.compile() except Exception, e: logger.error(e)
def add_file(self, path): """Adds file to the list of files. The path will be normalized by using :func:`os.path.abspath`. :param path: A string that represents file path. :returns: A normalized string path. :raises: TypeError """ if typecheck.is_string(path): if not path_utils.exists(path): caller_frame = inspect.getouterframes(inspect.currentframe(), 2) filename = inspect.getsourcefile(caller_frame[2][0]) possible_dir = path_utils.dirname(filename) alternative_path = path_utils.join(possible_dir, path) if path_utils.exists(alternative_path): return self.add_file(alternative_path) path = path_utils.abspath(path) if not path_utils.exists(path): raise Exception("Path doesn't exist: %s" % path) if not path in self._files: self._files.append(path) return path elif typecheck.is_callable(path): result = path() if not result: return elif typecheck.is_list(result): self.add_files(result) else: self.add_file(result) elif not path: return None else: raise TypeError("Unknown path type '%s' of '%s'" % (type(path), path))
def set_output_filename(self, path): """Set output file name.""" if not typecheck.is_string(path): raise TypeError("'path' must be a string") self._output_filename = path
def add_edge(self, sender, receiver, key=None, attr_dict=None, **attrs): """Create an edge between sender and receiver. Return an edge represented by :class:`NetworkXEdge` instance which is mainly replacing a tuple (sender, receiver, key, attrs). `sender` and `receiver` can be represented by a tuple of mapping and target communication device. `key` is an optional hashable identifier. By default it has :const:`NetworkXEdge.KEY_FORMAT` format. Note, this key has to be unique in order to distinguish multiedges between a pair of nodes. At the same time edge's label equals to the key. By default label equals to the key value but can be changes by using associated data as follows:: edge = network.add_edge(Mapping("M1"), Mapping("M2"), label="My serial connection") or:: edge = network.add_edge(Mapping("M1"), Mapping("M2")) edge.set_label("My serial connection") Note, the nodes for sender and receiver mappings will be automatically added if they are not already in the graph. """ # Analyse incomming arguments if typecheck.is_tuple(sender): (sender, sending_device) = sender if typecheck.is_tuple(receiver): (receiver, receiving_device) = receiver # Setup dictionary of attributes if attr_dict is None: attr_dict = attrs if not self.has_node(sender): self.add_node(sender) if not self.has_node(receiver): self.add_node(receiver) # Define hashable identifier if not key: key_format = attr_dict.get("key_format", None) or \ NetworkXEdge.KEY_FORMAT if not typecheck.is_string(key_format): raise TypeError("Has to be string") key = key_format % self.number_of_edges(sender, receiver) else: if not typecheck.is_string(key): raise TypeError("Has to be string") if self.has_edge(sender, receiver, key): raise Exception("Edge %s already exists between %s and %s" % (key, sender, receiver)) # Define edge label if not attr_dict.get("label", None): attr_dict["label"] = key else: if not typecheck.is_string(attr_dict.get("label")): raise TypeError("Has to be string") # Use super method networkx.MultiDiGraph.add_edge(self, sender, receiver, key=key, attr_dict=attr_dict) return NetworkXEdge(sender, receiver, key, self.get_edge_data(sender, receiver, key=key))
def set_port(self, port): if not typecheck.is_string(port): raise TypeError() self._port = port
def _fix_compiler_name(name): if not typecheck.is_string(name): raise TypeError("Compiler's name must be a string") return name.lower()
def build_from_json(cls, os_model): if typecheck.is_string(os_model): os_model = json.loads(os_model) os = cls(max_message_size=os_model.get('max_message_size', 0)) for message_model in os_model.get('messages', []): pass
def _set_name(self, name): if not typecheck.is_string(name): raise TypeError() self._name = name
def set_output_dir(self, path): if not typecheck.is_string(path): raise TypeError("'path' must be a string") self._output_dir = path
cmdtuples = [] _build_tuple(directory, cmdtuples) for cmd in cmdtuples: try: cmd[0](cmd[1]) # remove dir from cache if it's already there abspath = abspath(cmd[1]) if abspath in _path_created: del _path_created[abspath] except (IOError, OSError), exc: print exc, "error removing %s: " % directory def touch(name, mode=0777, recursive=False): if typecheck.is_list(name): name = join(*name) if not typecheck.is_string(name): raise TypeError() if not typecheck.is_int(mode): raise TypeError() if not typecheck.is_bool(recursive): raise TypeError() if recursive: mkpath(dirname(name), mode=mode) open(name, "w").close() return name def mkpath(name, mode=0777, verbose=0, dry_run=False): """Creates a file/directory and any missing ancestor directories. If the directory already exists (or if `name` is the empty string, which means the current directory, which of course exists), then do nothing. Raises :class:`OSError` if unable to create some directory along the way (eg. some
def set_output_dir(self, output_dir): """Sets output directory.""" if not output_dir or not typecheck.is_string(output_dir): raise TypeError("'output_dir' must be a string or None") else: self._output_dir = output_dir
def _setup_compile(self, output_dir): if output_dir is None: outputdir = self._output_dir elif not typecheck.is_string(output_dir): raise TypeError("'output_dir' must be a string or None")