def resume(self, requires: Dict[object, ResultVariable], resolver: Resolver, queue_scheduler: QueueScheduler, target: ResultVariable) -> None: """ Instance is ready to execute, do it and see if the attribute is already present """ # get the Instance obj = self.instance.execute(requires, resolver, queue_scheduler) if isinstance(obj, list): raise RuntimeException( self, "can not get a attribute %s, %s is a list" % (self.attribute, obj)) if not isinstance(obj, Instance): raise RuntimeException( self, "can not get a attribute %s, %s not an entity" % (self.attribute, obj)) # get the attribute result variable attr = obj.get_attribute(self.attribute) # Cache it self.attr = attr if attr.is_ready(): # go ahead # i.e. back to the AttributeReference itself self.target.set_value(attr.get_value(), self.location) else: # reschedule on the attribute, XU will assign it to the target variable if self.resultcollector is not None: attr.listener(self.resultcollector, self.location) ExecutionUnit(queue_scheduler, resolver, self.target, {"x": attr}, self)
def call_direct(self, args: List[object], kwargs: Dict[str, object]) -> object: if len(kwargs) > 0: raise RuntimeException(self.ast_node, "Only positional arguments allowed in type cast") if len(args) != 1: raise RuntimeException( self.ast_node, "Illegal arguments %s: type cast expects exactly 1 argument" % ",".join(map(repr, args)) ) return self.type.cast(*args)
def __init__(self, msg, instance: Optional["Instance"] = None, attribute: Optional["Attribute"] = None) -> None: RuntimeException.__init__(self, None, msg) self.instance: Optional[Instance] = instance self.attribute: Optional[Attribute] = attribute self.msg = msg
def set_value(self, value, location, recur=True): if self.hasValue: if value in self.value: return else: raise RuntimeException(None, "List modified after freeze") if isinstance(value, list): if len(value) == 0: # the values of empty lists need no processing, # but a set_value from an empty list may fulfill a promise, allowing this object to be queued if self.can_get(): self.queue() else: for v in value: self.set_value(v, recur, location) return if self.type is not None: self.type.validate(value) if value in self.value: # any set_value may fulfill a promise, allowing this object to be queued if self.can_get(): self.queue() return self.value.append(value) for l in self.listeners: l.receive_result(value, location) # set counterpart if self.attribute.end and recur: value.set_attribute(self.attribute.end.name, self.myself, location, False) if self.attribute.high is not None: if self.attribute.high > len(self.value): raise RuntimeException( None, "List over full: max nr of items is %d, content is %s" % (self.attribute.high, self.value)) if self.attribute.high > len(self.value): self.freeze() if self.can_get(): self.queue()
def __init__( self, entity_name: LocatableString, implementations: List[LocatableString], select: ExpressionStatement, inherit: bool = False, comment: LocatableString = None, ) -> None: DefinitionStatement.__init__(self) self.entity = entity_name self.entity_location = entity_name.get_location() self.implementations = implementations self.anchors = [ TypeReferenceAnchor(x.namespace, x) for x in implementations ] self.anchors.append( TypeReferenceAnchor(entity_name.namespace, entity_name)) self.anchors.extend(select.get_anchors()) self.location = entity_name.get_location() if inherit and (not isinstance(select, Literal) or select.value is not True): raise RuntimeException( self, "Conditional implementation with parents not allowed") self.select = select self.inherit: bool = inherit if comment is not None: self.comment = str(comment) else: self.comment = None
def recurse_dict_item(key_value: Tuple[object, object]) -> Tuple[object, object]: (key, value) = key_value if not isinstance(key, str): raise RuntimeException( None, "dict keys should be strings, got %s of type %s with dict value %s" % (key, type(key), value) ) return (key, cls.unwrap(value))
def resume(self, requires: Dict[object, ResultVariable], resolver: Resolver, queue: QueueScheduler) -> None: if self.condition_value is None: condition_value: object = self.expression.condition.execute( {k: v.get_value() for k, v in requires.items()}, resolver, queue) if isinstance(condition_value, Unknown): self.result.set_value(Unknown(self), self.location) return if not isinstance(condition_value, bool): raise RuntimeException( self, "Invalid value `%s`: the condition for a conditional expression must be a boolean expression" ) self.condition_value = condition_value # Schedule execution of appropriate subexpression subexpression: ExpressionStatement = ( self.expression.if_expression if self.condition_value else self.expression.else_expression) RawUnit( queue, resolver, subexpression.requires_emit(resolver, queue), self, ) else: value: object = ( self.expression.if_expression if self.condition_value else self.expression.else_expression).execute( {k: v.get_value() for k, v in requires.items()}, resolver, queue) self.result.set_value(value, self.location)
def resume(self, requires: Dict[object, ResultVariable], resolver: Resolver, queue_scheduler: QueueScheduler) -> None: """ Instance is ready to execute, do it and see if the attribute is already present """ try: # get the Instance obj = self.instance.execute( {k: v.get_value() for k, v in requires.items()}, resolver, queue_scheduler) if isinstance(obj, list): raise RuntimeException( self, "can not get a attribute %s, %s is a list" % (self.attribute, obj)) # get the attribute result variable attr = obj.get_attribute(self.attribute) # Cache it self.attr = attr if attr.is_ready(): # go ahead # i.e. back to the AttributeReference itself attr.get_value() self.target.set_value(True, self.location) else: requires["x"] = attr # reschedule on the attribute, XU will assign it to the target variable RawUnit(queue_scheduler, resolver, requires, self) except RuntimeException: self.target.set_value(False, self.location)
def validate(self, value: Optional[object]) -> bool: if not super().validate(value): return False if not isinstance(value, numbers.Integral): raise RuntimeException( None, "Invalid value '%s', expected %s" % (value, self.type_string())) return True
def __getitem__(self, key): instance = self._get_instance() if isinstance(key, str): raise RuntimeException( self, "can not get a attribute %s, %s is a list" % (key, self._get_instance())) return DynamicProxy.return_value(instance[key])
def validate(self, value: object) -> bool: for typ in self.types: try: if typ.validate(value): return True except RuntimeException: pass raise RuntimeException(None, "Invalid value '%s', expected %s" % (value, self))
def __getitem__(self, key): instance = self._get_instance() if not isinstance(key, str): raise RuntimeException( self, "Expected string key, but got %s, %s is a dict" % (key, self._get_instance())) return DynamicProxy.return_value(instance[key])
def set_value(self, value: ListValue, location: Location, recur: bool = True) -> None: if isinstance(value, NoneValue): if len(self.value) > 0: exception: CompilerException = RuntimeException( None, "Trying to set relation attribute `%s` of instance `%s` to null but it has values `%s` assigned already" % (self.attribute.name, self.myself, ", ".join( str(v) for v in self.value)), ) exception.set_location(location) raise exception self.freeze() return try: if not self._set_value(value, location, recur): return except ModifiedAfterFreezeException as e: if len(self.value) == self.attribute.high: new_exception: CompilerException = RuntimeException( None, "Exceeded relation arity on attribute '%s' of instance '%s'" % (self.attribute.name, self.myself)) new_exception.set_location(location) raise new_exception raise e # set counterpart if self.attribute.end is not None and recur: value.set_attribute(self.attribute.end.name, self.myself, location, False) if self.attribute.high is not None: if len(self.value) > self.attribute.high: raise RuntimeException( None, "List over full: max nr of items is %d, content is %s" % (self.attribute.high, self.value)) if self.attribute.high == len(self.value): self.freeze() if self.can_get(): self.queue()
def validate(cls, value): """ Validate the given value to check if it satisfies the constraints associated with this type """ if isinstance(value, AnyType): return True try: float(value) except TypeError: raise RuntimeException(None, "Invalid value '%s'expected Number" % value) except ValueError: raise RuntimeException(None, "Invalid value '%s'expected Number" % value) return True # allow this function to be called from a lambda function
def add_attribute(self, name: str, value: object): """ Add an attribute to this constructor call """ if name not in self.__attributes: self.__attributes[name] = value else: raise RuntimeException(self, "The attribute %s in the constructor call of %s is already set." % (name, self.class_type))
def execute_direct(self, requires): function = self.function arguments = [a.execute_direct(requires) for a in self.arguments] no_unknows = function.check_args(arguments) if not no_unknows: raise RuntimeException("Received unknown value during direct execution") if function._context is not -1: raise RuntimeException("Context Aware functions are not allowed in direct execution") if function.opts["emits_statements"]: raise RuntimeException("emits_statements functions are not allowed in direct execution") else: try: return function(*arguments) except Exception as e: raise WrappingRuntimeException(self, "Exception in direct execution for plugin %s" % self.name, e)
def view(self) -> None: try: self.digraph.view() except graphviz.ExecutableNotFound: raise RuntimeException( None, "Graphically visualizing the data flow graph requires the fdp command" " from your distribution's graphviz package.", )
def normalize(self) -> None: ReferenceStatement.normalize(self) func = self.namespace.get_type(self.name) if isinstance(func, InmantaType.Primitive): self.function = Cast(self, func) elif isinstance(func, plugins.Plugin): self.function = PluginFunction(self, func) else: raise RuntimeException(self, "Can not call '%s', can only call plugin or primitive type cast" % self.name)
def execute_direct(self, requires): arguments = [a.execute_direct(requires) for a in self.arguments] kwargs = {k: v.execute_direct(requires) for k, v in self.kwargs.items()} for wrapped_kwarg_expr in self.wrapped_kwargs: for k, v in wrapped_kwarg_expr.execute_direct(requires): if k in kwargs: raise RuntimeException(self, "Keyword argument %s repeated in function call" % k) kwargs[k] = v return self.function.call_direct(arguments, kwargs)
def validate(self, value: Optional[object]) -> bool: """ Validate the given value to check if it satisfies the constraints associated with this type """ if isinstance(value, AnyType): return True if isinstance(value, bool): return True raise RuntimeException(None, "Invalid value '%s', expected Bool" % value)
def fetch_variable( self, requires: Dict[object, ResultVariable], resolver: Resolver, queue_scheduler: QueueScheduler ) -> ResultVariable: """ Fetches the referred variable """ if self.instance: # get the Instance obj = self.instance.execute({k: v.get_value() for k, v in requires.items()}, resolver, queue_scheduler) if isinstance(obj, list): raise RuntimeException(self, "can not get a attribute %s, %s is a list" % (self.attribute, obj)) if not isinstance(obj, Instance): raise RuntimeException(self, "can not get a attribute %s, %s not an entity" % (self.attribute, obj)) # get the attribute result variable return obj.get_attribute(self.attribute) else: return resolver.lookup(self.attribute)
def validate(self, value: Optional[object]) -> bool: if value is None: return True if isinstance(value, AnyType): return True if not isinstance(value, list): raise RuntimeException(None, "Invalid value '%s', expected %s" % (value, self.type_string())) return True
def execute_direct(self, requires: Dict[object, object]) -> object: condition_value: object = self.condition.execute_direct(requires) if isinstance(condition_value, Unknown): return Unknown(self) if not isinstance(condition_value, bool): raise RuntimeException( self, "Invalid value `%s`: the condition for a conditional expression must be a boolean expression" ) return (self.if_expression if condition_value else self.else_expression).execute_direct(requires)
def validate(self, value: object) -> bool: """ Validate the given value """ if isinstance(value, AnyType): return True if not isinstance(value, Instance): raise RuntimeException( None, "Invalid type for value '%s', should be type %s" % (value, self)) value_definition = value.type if not (value_definition is self or self.is_subclass(value_definition)): raise RuntimeException( None, "Invalid class type for %s, should be %s" % (value, self)) return True
def validate(self, value: Optional[object]) -> bool: """ Validate the given value to check if it satisfies the constraints associated with this type """ if isinstance(value, AnyType): return True if not isinstance(value, numbers.Number): raise RuntimeException(None, "Invalid value '%s', expected Number" % value) return True # allow this function to be called from a lambda function
def validate(cls, value): """ Validate the given value to check if it satisfies the constraints associated with this type """ if isinstance(value, AnyType): return True if not isinstance(value, str): raise RuntimeException( None, "Invalid value '%s', expected String" % value) return True
def resume(self, requires, resolver, queue, result): """ Evaluate this statement. """ arguments = [a.execute(requires, resolver, queue) for a in self.arguments] kwargs = {k: v.execute(requires, resolver, queue) for k, v in self.kwargs.items()} for wrapped_kwarg_expr in self.wrapped_kwargs: for k, v in wrapped_kwarg_expr.execute(requires, resolver, queue): if k in kwargs: raise RuntimeException(self, "Keyword argument %s repeated in function call" % k) kwargs[k] = v self.function.call_in_context(arguments, kwargs, resolver, queue, result)
def cast(self, value: Optional[object]) -> object: """ Cast a value to this type. If the value can not be cast, raises a :py:class:`inmanta.ast.RuntimeException`. """ exception: RuntimeException = RuntimeException(None, "Failed to cast '%s' to %s" % (value, self)) for cast in self.try_cast_functions: try: return cast(value) except ValueError: continue except TypeError: raise exception raise exception
def call_direct(self, args: List[object], kwargs: Dict[str, object]) -> object: no_unknows = self.plugin.check_args(args, kwargs) if not no_unknows and not self.plugin.opts["allow_unknown"]: raise RuntimeException(self.ast_node, "Received unknown value during direct execution") if self.plugin._context != -1: raise RuntimeException(self.ast_node, "Context Aware functions are not allowed in direct execution") if self.plugin.opts["emits_statements"]: raise RuntimeException(self.ast_node, "emits_statements functions are not allowed in direct execution") else: try: return self.plugin(*args, **kwargs) except RuntimeException as e: raise WrappingRuntimeException( self.ast_node, "Exception in direct execution for plugin %s" % self.ast_node.name, e ) except plugins.PluginException as e: raise ExplicitPluginException( self.ast_node, "PluginException in direct execution for plugin %s" % self.ast_node.name, e ) except Exception as e: raise ExternalException(self.ast_node, "Exception in direct execution for plugin %s" % self.ast_node.name, e)
def validate(self, value): """ Validate the given value to check if it satisfies the constraint and the basetype. """ if isinstance(value, AnyType): return True self.basetype.validate(value) if not self._constraint(value): raise RuntimeException( None, "Invalid value '%s', constraint does not match" % value) return True