Пример #1
0
    def type_cast_expression(expr_node, target_type):
        """
        Type casts the given expr_node to the target_type.
        This is done by creating a new AST for the expr_node with an
        `as_operator`.

        Args:
            expr_node: Tree node representing an expression. This is the
                expression for which this function will generate a new
                expression node which also contains an `as_operator` to
                represent the type cast.
            target_type: The type to type cast given expression (expr_node)
                into. Must be a `types` node.

        Note: This does not perform any checks around feasibility of performing
        the type cast operation and depends upon the caller to have had
        performed these checks before making the call.
        """
        assert expr_node.data == 'expression'
        assert isinstance(target_type, BaseType)
        cast_type = SymbolExpressionVisitor.type_to_tree(
            expr_node,
            target_type
        )
        element = Tree('expression', [
            expr_node,
            Tree('as_operator', [
                Tree('types', [
                    cast_type
                ])
            ])
        ])
        element.kind = 'as_expression'
        return element
Пример #2
0
 def implicit_cast(self, tree, val, values):
     """
     Creates an AST with the cast.
     This boils down to
     - finding the right level to insert the new pow_expression with
       its respective as_operator
     - building a correct tree cascade in pow_expression to the old value
     """
     if val == AnyType.instance():
         return
     for i, v in enumerate(values):
         if i > 0:
             # ignore the arith_operator tree child
             i += 1
         # check whether a tree child needs casting
         if v != val:
             element = tree.children[i]
             casted_type = self.type_to_tree(element, val)
             element = Tree('expression', [
                 element,
                 Tree('as_operator', [
                     Tree('types', [
                         casted_type
                     ])
                 ])
             ])
             element.kind = 'as_expression'
             tree.children[i] = element