예제 #1
0
def parse_code(model_code: str):
    root_ns = Namespace("__root__")
    main_ns = Namespace("__config__")
    main_ns.parent = root_ns
    statements = parse(main_ns, "test", model_code)

    return statements
예제 #2
0
    def _load_plugins(self, plugin_dir, namespace):
        """
            Load all modules in plugin_dir
        """
        if not os.path.exists(os.path.join(plugin_dir, "__init__.py")):
            raise Exception(
                "The plugin directory %s should be a valid python package with a __init__.py file"
                % plugin_dir)

        mod_name = ".".join(namespace.to_path())
        imp.load_package(mod_name, plugin_dir)

        for py_file in glob.glob(os.path.join(plugin_dir, "*.py")):
            if not py_file.endswith("__init__.py"):
                # name of the python module
                sub_mod = mod_name + "." + os.path.basename(py_file).split(
                    ".")[0]

                # create a namespace for the submodule
                new_ns = Namespace(sub_mod.split(".")[-1])
                new_ns.parent = namespace
                self.graph.add_namespace(new_ns, namespace)

                # load the python file
                imp.load_source(sub_mod, py_file)
예제 #3
0
 def __init__(self, namespace: Namespace, name: str) -> None:
     DefinitionStatement.__init__(self)
     self.name = name
     self.namespace = namespace
     self.fullName = namespace.get_full_name() + "::" + str(name)
     self.type = None  # type: NamedType
     self.comment = None
예제 #4
0
def graph() -> Iterator[DataflowGraph]:
    namespace: Namespace = Namespace("dummy_namespace")
    resolver: Resolver = Resolver(namespace, enable_dataflow_graph=True)
    block: BasicBlock = BasicBlock(namespace, [])
    xc: ExecutionContext = ExecutionContext(block, resolver)
    block.namespace.scope = xc

    yield DataflowGraph(resolver)
예제 #5
0
def create_instance(graph: Optional[DataflowGraph] = None,
                    entity: Optional[Entity] = None,
                    statement: Optional[Statement] = None) -> InstanceNode:
    responsible: Statement = statement if statement is not None else Statement(
    )
    instance: InstanceNode = InstanceNode([])
    if graph is None:
        return instance
    return graph.own_instance_node_for_responsible(
        entity if entity is not None else Entity("DummyEntity",
                                                 Namespace("dummy_namespace")),
        responsible,
        lambda: instance,
    )
예제 #6
0
    def to_type(self, arg_type: Optional[object],
                resolver: Namespace) -> Optional[inmanta_type.Type]:
        """
        Convert a string representation of a type to a type
        """
        if arg_type is None:
            return None

        if not isinstance(arg_type, str):
            raise CompilerException(
                "bad annotation in plugin %s::%s, expected str but got %s (%s)"
                % (self.ns, self.__class__.__function_name__, type(arg_type),
                   arg_type))

        if arg_type == "any":
            return None

        if arg_type == "expression":
            return None

        # quickfix issue #1774
        allowed_element_type: inmanta_type.Type = inmanta_type.Type()
        if arg_type == "list":
            return inmanta_type.TypedList(allowed_element_type)
        if arg_type == "dict":
            return inmanta_type.TypedDict(allowed_element_type)

        plugin_line: Range = Range(self.location.file, self.location.lnr, 1,
                                   self.location.lnr + 1, 1)
        locatable_type: LocatableString = LocatableString(
            arg_type, plugin_line, 0, None)

        # stack of transformations to be applied to the base inmanta_type.Type
        # transformations will be applied right to left
        transformation_stack: List[Callable[[inmanta_type.Type],
                                            inmanta_type.Type]] = []

        if locatable_type.value.endswith("?"):
            locatable_type.value = locatable_type.value[0:-1]
            transformation_stack.append(inmanta_type.NullableType)

        if locatable_type.value.endswith("[]"):
            locatable_type.value = locatable_type.value[0:-2]
            transformation_stack.append(inmanta_type.TypedList)

        return reduce(lambda acc, transform: transform(acc),
                      reversed(transformation_stack),
                      resolver.get_type(locatable_type))
예제 #7
0
def test_attribute_validate(multi: bool, nullable: bool) -> None:
    entity: Entity = Entity("DummyEntity", Namespace("dummy_namespace"))
    attribute: Attribute = Attribute(entity, Integer(), "my_attribute",
                                     Location("dummy.cf", 1), multi, nullable)

    def validate(value: object, success: bool) -> None:
        if success:
            attribute.validate(value)
        else:
            with pytest.raises(RuntimeException):
                attribute.validate(value)

    validate(42, not multi)
    validate(NoneValue(), nullable)
    validate([0, 1, 2], multi)
    validate([0, 1, NoneValue()], False)
def test_dataflow_index(graph: DataflowGraph, reverse: bool) -> None:
    entity: Entity = Entity("DummyEntity", Namespace("dummy_namespace"))
    i1: InstanceNode = create_instance(graph, entity)
    i2: InstanceNode = create_instance(graph, entity)

    assert i1.get_self() is i1
    assert i2.get_self() is i2
    assert i1 is not i2

    graph.add_index_match([i.reference() for i in [i1, i2]])
    if reverse:
        # make sure adding them again in another order does not cause issues
        graph.add_index_match([i.reference() for i in [i2, i1]])

    assert i1.get_self() is i1
    assert i2.get_self() is i1
    assert i2.reference().node() is i1
    assert i2.reference().top_node() is i2
    assert i1.get_all_index_nodes() == {i1, i2}
def test_dataflow_index_nodes(graph: DataflowGraph) -> None:
    entity: Entity = Entity("DummyEntity", Namespace("dummy_namespace"))
    i1: InstanceNode = create_instance(graph, entity)
    i2: InstanceNode = create_instance(graph, entity)

    i1.register_attribute("n").assign(
        ValueNode(0).reference(), Statement(), graph)
    i1.register_attribute("n").assign(
        ValueNode(0).reference(), Statement(), graph)

    x: AssignableNodeReference = get_dataflow_node(graph, "x")
    y: AssignableNodeReference = get_dataflow_node(graph, "y")

    x.assign(i1.reference(), Statement(), graph)
    y.assign(i2.reference(), Statement(), graph)

    graph.add_index_match([i.reference() for i in [i1, i2]])

    x_n: AssignableNodeReference = get_dataflow_node(graph, "x.n")
    y_n: AssignableNodeReference = get_dataflow_node(graph, "y.n")

    assert set(x_n.nodes()) == set(y_n.nodes())
예제 #10
0
 def __init__(self, file: BytesIO, namespace: Namespace) -> None:
     super().__init__(file)
     self.namespace = namespace
     self.namespace_name = namespace.get_full_name()
예제 #11
0
 def get_basetype(self, namespace: Namespace) -> Type:
     """
     Returns the base type for this declaration as a Type.
     """
     return namespace.get_type(self.basetype)
예제 #12
0
 def __init__(self, file, namespace: Namespace):
     super().__init__(file)
     self.namespace = namespace
     self.namespace_name = namespace.get_full_name()
예제 #13
0
def entity_instance(entity: str) -> InstanceNode:
    node: InstanceNode = InstanceNode([])
    node.entity = Entity(entity, Namespace("__config__", Namespace("__root_ns__")))
    return node