def _cast_expr(ql_type: qlast.TypeName, ir_expr: irast.Base, *, source_context: parsing.ParserContext, ctx: context.ContextLevel) -> irast.Base: try: orig_type = irutils.infer_type(ir_expr, ctx.schema) except errors.EdgeQLError: # It is possible that the source expression is unresolved # if the expr is an empty set (or a coalesce of empty sets). orig_type = None if isinstance(orig_type, s_types.Tuple): # For tuple-to-tuple casts we generate a new tuple # to simplify things on sqlgen side. new_type = typegen.ql_typeref_to_type(ql_type, ctx=ctx) if not isinstance(new_type, s_types.Tuple): raise errors.EdgeQLError(f'cannot cast tuple to {new_type.name}', context=source_context) if len(orig_type.element_types) != len(new_type.element_types): raise errors.EdgeQLError( f'cannot cast to {new_type.name}: ' f'number of elements is not the same', context=source_context) new_names = list(new_type.element_types) elements = [] for i, n in enumerate(orig_type.element_types): val = setgen.generated_set(irast.TupleIndirection(expr=ir_expr, name=n), ctx=ctx) val.path_id = irutils.tuple_indirection_path_id( ir_expr.path_id, n, orig_type.element_types[n]) val_type = irutils.infer_type(val, ctx.schema) new_el_name = new_names[i] if val_type != new_type.element_types[new_el_name]: # Element cast val = _cast_expr(ql_type.subtypes[i], val, ctx=ctx, source_context=source_context) elements.append(irast.TupleElement(name=new_el_name, val=val)) return irast.Tuple(named=new_type.named, elements=elements) elif isinstance(ir_expr, irast.EmptySet): # For the common case of casting an empty set, we simply # generate a new EmptySet node of the requested type. scls = typegen.ql_typeref_to_type(ql_type, ctx=ctx) return irutils.new_empty_set(ctx.schema, scls=scls, alias=ir_expr.path_id.target.name.name) else: typ = typegen.ql_typeref_to_ir_typeref(ql_type, ctx=ctx) return setgen.ensure_set(irast.TypeCast(expr=ir_expr, type=typ), ctx=ctx)
def make_tuple( elements: typing.List[irast.TupleElement], *, named: bool, ctx: context.ContextLevel) -> irast.Tuple: tup = irast.Tuple(elements=elements, named=named) tup.stype = inference.infer_type(tup, env=ctx.env) return tup
def compile_Tuple(expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: elements = [] for i, el in enumerate(expr.elements): element = irast.TupleElement(name=str(i), val=dispatch.compile(el, ctx=ctx)) elements.append(element) return setgen.generated_set(irast.Tuple(elements=elements), ctx=ctx)
def compile_NamedTuple(expr: qlast.Base, *, ctx: context.ContextLevel) -> irast.Base: elements = [dispatch.compile(e, ctx=ctx) for e in expr.elements] return setgen.generated_set(irast.Tuple(elements=elements, named=True), ctx=ctx)