code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def compile_ast_fragment_to_ir(
tree: qlast.Base,
schema: s_schema.Schema,
*,
options: Optional[CompilerOptions] = None,
) -> irast.Statement:
"""Compile given EdgeQL AST fragment into Gel IR.
Unlike :func:`~compile_ast_to_ir` above, this does not assume
that the AST *tree* is a complete statement. The expression
doesn't even have to resolve to a specific type.
Args:
tree:
EdgeQL AST fragment.
schema:
Schema instance. Must contain definitions for objects
referenced by the AST *tree*.
options:
An optional :class:`edgeql.compiler.options.CompilerOptions`
instance specifying compilation options.
Returns:
An instance of :class:`ir.ast.Statement`.
"""
if options is None:
options = CompilerOptions()
ctx = stmtctx_mod.init_context(schema=schema, options=options)
ir_set = dispatch_mod.compile(tree, ctx=ctx)
result_type = ctx.env.set_types[ir_set]
return irast.Statement(
expr=ir_set,
schema=ctx.env.schema,
stype=result_type,
dml_exprs=ctx.env.dml_exprs,
views={},
params=[],
globals=[],
# These values are nonsensical, but ideally the caller does not care
cardinality=qltypes.Cardinality.UNKNOWN,
multiplicity=qltypes.Multiplicity.EMPTY,
volatility=qltypes.Volatility.Volatile,
view_shapes={},
view_shapes_metadata={},
schema_refs=frozenset(),
schema_ref_exprs=None,
scope_tree=ctx.path_scope,
type_rewrites={},
singletons=[],
triggers=(),
warnings=tuple(ctx.env.warnings),
) | Compile given EdgeQL AST fragment into Gel IR.
Unlike :func:`~compile_ast_to_ir` above, this does not assume
that the AST *tree* is a complete statement. The expression
doesn't even have to resolve to a specific type.
Args:
tree:
EdgeQL AST fragment.
schema:
Schema instance. Must contain definitions for objects
referenced by the AST *tree*.
options:
An optional :class:`edgeql.compiler.options.CompilerOptions`
instance specifying compilation options.
Returns:
An instance of :class:`ir.ast.Statement`. | compile_ast_fragment_to_ir | python | geldata/gel | edb/edgeql/compiler/__init__.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/__init__.py | Apache-2.0 |
def evaluate_to_python_val(
expr: str,
schema: s_schema.Schema,
*,
modaliases: Optional[Mapping[Optional[str], str]] = None,
) -> Any:
"""Evaluate the given EdgeQL string as a constant expression.
Args:
expr:
EdgeQL expression as a string.
schema:
Schema instance. Must contain definitions for objects
referenced by *expr*.
modaliases:
Module name resolution table. Useful when this EdgeQL
expression is part of some other construct, such as a
DDL statement.
Returns:
The result of the evaluation as a Python value.
Raises:
If the expression is not constant, or is otherwise not supported by
the const evaluator, the function will raise
:exc:`ir.staeval.UnsupportedExpressionError`.
"""
tree = qlparser.parse_fragment(expr)
return evaluate_ast_to_python_val(tree, schema, modaliases=modaliases) | Evaluate the given EdgeQL string as a constant expression.
Args:
expr:
EdgeQL expression as a string.
schema:
Schema instance. Must contain definitions for objects
referenced by *expr*.
modaliases:
Module name resolution table. Useful when this EdgeQL
expression is part of some other construct, such as a
DDL statement.
Returns:
The result of the evaluation as a Python value.
Raises:
If the expression is not constant, or is otherwise not supported by
the const evaluator, the function will raise
:exc:`ir.staeval.UnsupportedExpressionError`. | evaluate_to_python_val | python | geldata/gel | edb/edgeql/compiler/__init__.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/__init__.py | Apache-2.0 |
def evaluate_ir_statement_to_python_val(
ir: irast.Statement,
) -> Any:
"""Evaluate the given EdgeQL IR AST as a constant expression.
Args:
ir:
EdgeQL IR Statement AST.
Returns:
The result of the evaluation as a Python value and the associated IR.
Raises:
If the expression is not constant, or is otherwise not supported by
the const evaluator, the function will raise
:exc:`ir.staeval.UnsupportedExpressionError`.
"""
return ireval.evaluate_to_python_val(ir.expr, schema=ir.schema) | Evaluate the given EdgeQL IR AST as a constant expression.
Args:
ir:
EdgeQL IR Statement AST.
Returns:
The result of the evaluation as a Python value and the associated IR.
Raises:
If the expression is not constant, or is otherwise not supported by
the const evaluator, the function will raise
:exc:`ir.staeval.UnsupportedExpressionError`. | evaluate_ir_statement_to_python_val | python | geldata/gel | edb/edgeql/compiler/__init__.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/__init__.py | Apache-2.0 |
def evaluate_ast_to_python_val_and_ir(
tree: qlast.Base,
schema: s_schema.Schema,
*,
modaliases: Optional[Mapping[Optional[str], str]] = None,
) -> Tuple[Any, irast.Statement]:
"""Evaluate the given EdgeQL AST as a constant expression.
Args:
tree:
EdgeQL AST.
schema:
Schema instance. Must contain definitions for objects
referenced by AST *tree*.
modaliases:
Module name resolution table. Useful when this EdgeQL
expression is part of some other construct, such as a
DDL statement.
Returns:
The result of the evaluation as a Python value and the associated IR.
Raises:
If the expression is not constant, or is otherwise not supported by
the const evaluator, the function will raise
:exc:`ir.staeval.UnsupportedExpressionError`.
"""
if modaliases is None:
modaliases = {}
ir = compile_ast_fragment_to_ir(
tree,
schema,
options=CompilerOptions(
modaliases=modaliases,
),
)
return ireval.evaluate_to_python_val(ir.expr, schema=ir.schema), ir | Evaluate the given EdgeQL AST as a constant expression.
Args:
tree:
EdgeQL AST.
schema:
Schema instance. Must contain definitions for objects
referenced by AST *tree*.
modaliases:
Module name resolution table. Useful when this EdgeQL
expression is part of some other construct, such as a
DDL statement.
Returns:
The result of the evaluation as a Python value and the associated IR.
Raises:
If the expression is not constant, or is otherwise not supported by
the const evaluator, the function will raise
:exc:`ir.staeval.UnsupportedExpressionError`. | evaluate_ast_to_python_val_and_ir | python | geldata/gel | edb/edgeql/compiler/__init__.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/__init__.py | Apache-2.0 |
def evaluate_ast_to_python_val(
tree: qlast.Base,
schema: s_schema.Schema,
*,
modaliases: Optional[Mapping[Optional[str], str]] = None,
) -> Any:
"""Evaluate the given EdgeQL AST as a constant expression.
Args:
tree:
EdgeQL AST.
schema:
Schema instance. Must contain definitions for objects
referenced by AST *tree*.
modaliases:
Module name resolution table. Useful when this EdgeQL
expression is part of some other construct, such as a
DDL statement.
Returns:
The result of the evaluation as a Python value.
Raises:
If the expression is not constant, or is otherwise not supported by
the const evaluator, the function will raise
:exc:`ir.staeval.UnsupportedExpressionError`.
"""
return evaluate_ast_to_python_val_and_ir(
tree, schema, modaliases=modaliases
)[0] | Evaluate the given EdgeQL AST as a constant expression.
Args:
tree:
EdgeQL AST.
schema:
Schema instance. Must contain definitions for objects
referenced by AST *tree*.
modaliases:
Module name resolution table. Useful when this EdgeQL
expression is part of some other construct, such as a
DDL statement.
Returns:
The result of the evaluation as a Python value.
Raises:
If the expression is not constant, or is otherwise not supported by
the const evaluator, the function will raise
:exc:`ir.staeval.UnsupportedExpressionError`. | evaluate_ast_to_python_val | python | geldata/gel | edb/edgeql/compiler/__init__.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/__init__.py | Apache-2.0 |
def compile_constant_tree_to_ir(
const: qlast.BaseConstant,
schema: s_schema.Schema,
*,
styperef: Optional[irast.TypeRef] = None,
) -> irast.Expr:
"""Compile an EdgeQL constant into an IR ConstExpr.
Args:
const:
An EdgeQL AST representing a constant.
schema:
A schema instance. Must contain the definition of the
constant type.
styperef:
Optionally overrides an IR type descriptor for the returned
ConstExpr. If not specified, the inferred type of the constant
is used.
Returns:
An instance of :class:`ir.ast.ConstExpr` representing the
constant.
"""
ctx = stmtctx_mod.init_context(schema=schema, options=CompilerOptions())
if not isinstance(const, qlast.BaseConstant):
raise ValueError(f'unexpected input: {const!r} is not a constant')
ir_set = dispatch_mod.compile(const, ctx=ctx)
assert isinstance(ir_set, irast.Set)
result = ir_set.expr
assert isinstance(result, irast.BaseConstant)
if styperef is not None and result.typeref.id != styperef.id:
result = type(result)(value=result.value, typeref=styperef)
return result | Compile an EdgeQL constant into an IR ConstExpr.
Args:
const:
An EdgeQL AST representing a constant.
schema:
A schema instance. Must contain the definition of the
constant type.
styperef:
Optionally overrides an IR type descriptor for the returned
ConstExpr. If not specified, the inferred type of the constant
is used.
Returns:
An instance of :class:`ir.ast.ConstExpr` representing the
constant. | compile_constant_tree_to_ir | python | geldata/gel | edb/edgeql/compiler/__init__.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/__init__.py | Apache-2.0 |
def normalize(
tree: qlast.Base,
*,
schema: s_schema.Schema,
modaliases: Mapping[Optional[str], str],
localnames: AbstractSet[str] = frozenset(),
) -> None:
"""Normalize the given AST *tree* by explicitly qualifying identifiers.
This helper takes an arbitrary EdgeQL AST tree together with the current
module alias mapping and produces an equivalent expression, in which
all identifiers representing schema object references are properly
qualified with the module name.
NOTE: the tree is mutated *in-place*.
"""
return norm_mod.normalize(
tree,
schema=schema,
modaliases=modaliases,
localnames=localnames,
) | Normalize the given AST *tree* by explicitly qualifying identifiers.
This helper takes an arbitrary EdgeQL AST tree together with the current
module alias mapping and produces an equivalent expression, in which
all identifiers representing schema object references are properly
qualified with the module name.
NOTE: the tree is mutated *in-place*. | normalize | python | geldata/gel | edb/edgeql/compiler/__init__.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/__init__.py | Apache-2.0 |
def renormalize_compat(
tree: qlast.Base_T,
orig_text: str,
*,
schema: s_schema.Schema,
localnames: AbstractSet[str] = frozenset(),
) -> qlast.Base_T:
"""Renormalize an expression normalized with imprint_expr_context().
This helper takes the original, unmangled expression, an EdgeQL AST
tree of the same expression mangled with `imprint_expr_context()`
(which injects extra WITH MODULE clauses), and produces a normalized
expression with explicitly qualified identifiers instead. Old dumps
are the main user of this facility.
"""
return norm_mod.renormalize_compat(
tree,
orig_text,
schema=schema,
localnames=localnames,
) | Renormalize an expression normalized with imprint_expr_context().
This helper takes the original, unmangled expression, an EdgeQL AST
tree of the same expression mangled with `imprint_expr_context()`
(which injects extra WITH MODULE clauses), and produces a normalized
expression with explicitly qualified identifiers instead. Old dumps
are the main user of this facility. | renormalize_compat | python | geldata/gel | edb/edgeql/compiler/__init__.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/__init__.py | Apache-2.0 |
def _load() -> None:
"""Load the compiler modules. This is done once per process."""
global _LOADED
global dispatch_mod, inference_mod, irast, ireval, norm_mod, stmtctx_mod
from edb.ir import ast as _irast
from edb.ir import staeval as _ireval
from . import expr as _expr_compiler # NOQA
from . import config as _config_compiler # NOQA
from . import stmt as _stmt_compiler # NOQA
from . import dispatch
from . import inference
from . import normalization
from . import stmtctx
dispatch_mod = dispatch
inference_mod = inference
irast = _irast
ireval = _ireval
norm_mod = normalization
stmtctx_mod = stmtctx
_LOADED = True | Load the compiler modules. This is done once per process. | _load | python | geldata/gel | edb/edgeql/compiler/__init__.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/__init__.py | Apache-2.0 |
def get_security_context(self) -> object:
'''Compute an additional compilation cache key.
Return an additional key for any compilation caches that may
vary based on "security contexts" such as whether we are in an
access policy.
'''
# N.B: Whether we are compiling a trigger is not included here
# since we clear cached rewrites when compiling them in the
# *pgsql* compiler.
return bool(self.suppress_rewrites) | Compute an additional compilation cache key.
Return an additional key for any compilation caches that may
vary based on "security contexts" such as whether we are in an
access policy. | get_security_context | python | geldata/gel | edb/edgeql/compiler/context.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/context.py | Apache-2.0 |
def preserve_view_shape(
base: Union[s_types.Type, s_pointers.Pointer],
derived: Union[s_types.Type, s_pointers.Pointer],
*,
derived_name_base: Optional[sn.Name] = None,
ctx: context.ContextLevel,
) -> None:
"""Copy a view shape to a child type, updating the pointers"""
new = []
schema = ctx.env.schema
for ptr, op in ctx.env.view_shapes[base]:
target = ptr.get_target(ctx.env.schema)
assert target
schema, nptr = ptr.get_derived(
schema, cast(s_sources.Source, derived), target,
derived_name_base=derived_name_base)
new.append((nptr, op))
ctx.env.view_shapes[derived] = new
if isinstance(base, s_types.Type) and isinstance(derived, s_types.Type):
ctx.env.view_shapes_metadata[derived] = (
ctx.env.view_shapes_metadata[base]).replace()
# All of the pointers should already exist, so nothing should have
# been created.
assert schema is ctx.env.schema | Copy a view shape to a child type, updating the pointers | preserve_view_shape | python | geldata/gel | edb/edgeql/compiler/schemactx.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/schemactx.py | Apache-2.0 |
def concretify(
t: s_types.TypeT,
*,
ctx: context.ContextLevel,
) -> s_types.TypeT:
"""Produce a version of t with all views removed.
This procedes recursively through unions and intersections,
which can result in major simplifications with intersection types
in particular.
"""
t = get_material_type(t, ctx=ctx)
if els := t.get_union_of(ctx.env.schema):
ts = [concretify(e, ctx=ctx) for e in els.objects(ctx.env.schema)]
return get_union_type(ts, ctx=ctx)
if els := t.get_intersection_of(ctx.env.schema):
ts = [concretify(e, ctx=ctx) for e in els.objects(ctx.env.schema)]
return get_intersection_type(ts, ctx=ctx)
return t | Produce a version of t with all views removed.
This procedes recursively through unions and intersections,
which can result in major simplifications with intersection types
in particular. | concretify | python | geldata/gel | edb/edgeql/compiler/schemactx.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/schemactx.py | Apache-2.0 |
def apply_intersection(
left: s_types.Type, right: s_types.Type, *, ctx: context.ContextLevel
) -> TypeIntersectionResult:
"""Compute an intersection of two types: *left* and *right*.
Returns:
A :class:`~TypeIntersectionResult` named tuple containing the
result intersection type, whether the type system considers
the intersection empty and whether *left* is related to *right*
(i.e either is a subtype of another).
"""
if left.issubclass(ctx.env.schema, right):
# The intersection type is a proper *superclass*
# of the argument, then this is, effectively, a NOP.
return TypeIntersectionResult(stype=left)
if right.issubclass(ctx.env.schema, left):
# The intersection type is a proper *subclass* and can be directly
# narrowed.
return TypeIntersectionResult(
stype=right,
is_empty=False,
is_subtype=True,
)
if (
left.get_is_opaque_union(ctx.env.schema)
and (left_union := left.get_union_of(ctx.env.schema))
):
# Expose any opaque union types before continuing with the intersection.
# The schema does not yet fully implement type intersections since there
# is no `IntersectionTypeShell`. As a result, some intersections
# produced while compiling the standard library cannot be resolved.
left = get_union_type(left_union.objects(ctx.env.schema), ctx=ctx)
int_type: s_types.Type = get_intersection_type([left, right], ctx=ctx)
is_empty: bool = (
not s_utils.expand_type_expr_descendants(int_type, ctx.env.schema)
)
is_subtype: bool = int_type.issubclass(ctx.env.schema, left)
return TypeIntersectionResult(
stype=int_type,
is_empty=is_empty,
is_subtype=is_subtype,
) | Compute an intersection of two types: *left* and *right*.
Returns:
A :class:`~TypeIntersectionResult` named tuple containing the
result intersection type, whether the type system considers
the intersection empty and whether *left* is related to *right*
(i.e either is a subtype of another). | apply_intersection | python | geldata/gel | edb/edgeql/compiler/schemactx.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/schemactx.py | Apache-2.0 |
def _shape_el_ql_to_shape_el_desc(
shape_el: qlast.ShapeElement,
*,
source: s_sources.Source,
s_ctx: ShapeContext,
ctx: context.ContextLevel,
) -> ShapeElementDesc:
"""Look at ShapeElement AST and annotate it for more convenient handing."""
steps = shape_el.expr.steps
is_linkprop = False
is_polymorphic = False
plen = len(steps)
target_typexpr = None
source_intersection = []
if plen >= 2 and isinstance(steps[-1], qlast.TypeIntersection):
# Target type intersection: foo: Type
target_typexpr = steps[-1].type
plen -= 1
steps = steps[:-1]
if plen == 1:
# regular shape
lexpr = steps[0]
assert isinstance(lexpr, qlast.Ptr)
is_linkprop = lexpr.type == 'property'
if is_linkprop:
view_rptr = s_ctx.view_rptr
if view_rptr is None or view_rptr.ptrcls is None:
raise errors.QueryError(
'invalid reference to link property '
'in top level shape', span=lexpr.span)
assert isinstance(view_rptr.ptrcls, s_links.Link)
source = view_rptr.ptrcls
elif plen == 2 and isinstance(steps[0], qlast.TypeIntersection):
# Source type intersection: [IS Type].foo
source_intersection = [steps[0]]
lexpr = steps[1]
ptype = steps[0].type
source_spec = typegen.ql_typeexpr_to_type(ptype, ctx=ctx)
if not isinstance(source_spec, s_objtypes.ObjectType):
raise errors.QueryError(
f"expected object type, got "
f"{source_spec.get_verbosename(ctx.env.schema)}",
span=ptype.span,
)
source = source_spec
is_polymorphic = True
else: # pragma: no cover
raise RuntimeError(
f'unexpected path length in view shape: {len(steps)}')
assert isinstance(lexpr, qlast.Ptr)
ptrname = lexpr.name
if target_typexpr is None:
path_ql = qlast.Path(
steps=[
*source_intersection,
lexpr,
],
partial=True,
)
else:
path_ql = qlast.Path(
steps=[
*source_intersection,
lexpr,
qlast.TypeIntersection(type=target_typexpr),
],
partial=True,
)
return ShapeElementDesc(
ql=shape_el,
path_ql=path_ql,
ptr_ql=lexpr,
ptr_name=ptrname,
source=source,
target_typexpr=target_typexpr,
is_polymorphic=is_polymorphic,
is_linkprop=is_linkprop,
) | Look at ShapeElement AST and annotate it for more convenient handing. | _shape_el_ql_to_shape_el_desc | python | geldata/gel | edb/edgeql/compiler/viewgen.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/viewgen.py | Apache-2.0 |
def _expand_splat(
stype: s_objtypes.ObjectType,
*,
depth: int,
skip_ptrs: AbstractSet[str] = frozenset(),
skip_lprops: AbstractSet[str] = frozenset(),
rlink: Optional[s_links.Link] = None,
intersection: Optional[qlast.TypeIntersection] = None,
ctx: context.ContextLevel,
) -> List[qlast.ShapeElement]:
"""Expand a splat (possibly recursively) into a list of ShapeElements"""
elements = []
pointers = stype.get_pointers(ctx.env.schema)
path: list[qlast.PathElement] = []
if intersection is not None:
path.append(intersection)
for ptr in pointers.objects(ctx.env.schema):
if not isinstance(ptr, s_props.Property):
continue
if ptr.get_secret(ctx.env.schema):
continue
sname = ptr.get_shortname(ctx.env.schema)
if sname.name in skip_ptrs:
continue
step = qlast.Ptr(name=sname.name)
# Make sure not to overwrite the id property.
if not ptr.is_id_pointer(ctx.env.schema):
steps = path + [step]
else:
steps = [step]
elements.append(qlast.ShapeElement(
expr=qlast.Path(steps=steps),
origin=qlast.ShapeOrigin.SPLAT_EXPANSION,
))
if rlink is not None:
for prop in rlink.get_pointers(ctx.env.schema).objects(ctx.env.schema):
if prop.is_endpoint_pointer(ctx.env.schema):
continue
assert isinstance(prop, s_props.Property), \
"non-property pointer on link?"
sname = prop.get_shortname(ctx.env.schema)
if sname.name in skip_lprops:
continue
elements.append(
qlast.ShapeElement(
expr=qlast.Path(
steps=[qlast.Ptr(
name=sname.name,
type='property',
)]
),
origin=qlast.ShapeOrigin.SPLAT_EXPANSION,
)
)
if depth > 1:
for ptr in pointers.objects(ctx.env.schema):
if not isinstance(ptr, s_links.Link):
continue
pn = ptr.get_shortname(ctx.env.schema)
if pn.name == '__type__' or pn.name in skip_ptrs:
continue
elements.append(
qlast.ShapeElement(
expr=qlast.Path(steps=path + [qlast.Ptr(name=pn.name)]),
elements=_expand_splat(
ptr.get_target(ctx.env.schema),
rlink=ptr,
depth=depth - 1,
ctx=ctx,
),
origin=qlast.ShapeOrigin.SPLAT_EXPANSION,
)
)
return elements | Expand a splat (possibly recursively) into a list of ShapeElements | _expand_splat | python | geldata/gel | edb/edgeql/compiler/viewgen.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/viewgen.py | Apache-2.0 |
def _get_early_shape_configuration(
ir_set: irast.Set,
in_shape_ptrs: List[ShapePtr],
*,
rptrcls: Optional[s_pointers.Pointer],
parent_view_type: Optional[s_types.ExprType]=None,
ctx: context.ContextLevel
) -> List[ShapePtr]:
"""Return a list of (source_set, ptrcls) pairs as a shape for a given set.
"""
stype = setgen.get_set_type(ir_set, ctx=ctx)
# HACK: For some reason, all the link properties need to go last or
# things choke in native output mode?
shape_ptrs = sorted(
in_shape_ptrs,
key=lambda arg: arg.ptrcls.is_link_property(ctx.env.schema),
)
_get_shape_configuration_inner(
ir_set, shape_ptrs, stype, parent_view_type=parent_view_type, ctx=ctx)
return shape_ptrs | Return a list of (source_set, ptrcls) pairs as a shape for a given set. | _get_early_shape_configuration | python | geldata/gel | edb/edgeql/compiler/viewgen.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/viewgen.py | Apache-2.0 |
def _get_late_shape_configuration(
ir_set: irast.Set,
*,
rptr: Optional[irast.Pointer]=None,
parent_view_type: Optional[s_types.ExprType]=None,
ctx: context.ContextLevel
) -> List[ShapePtr]:
"""Return a list of (source_set, ptrcls) pairs as a shape for a given set.
"""
stype = setgen.get_set_type(ir_set, ctx=ctx)
sources: List[Union[s_types.Type, s_pointers.PointerLike]] = []
link_view = False
is_objtype = ir_set.path_id.is_objtype_path()
if rptr is None:
if isinstance(ir_set.expr, irast.Pointer):
rptr = ir_set.expr
elif ir_set.expr and not isinstance(ir_set.expr, irast.Pointer):
# If we have a specified rptr but set is not a pointer itself,
# construct a version of the set that is pointer so it can be used
# as the path tip for applying pointers. This ensures that
# we can find link properties on late shapes.
ir_set = setgen.new_set_from_set(
ir_set, expr=rptr.replace(expr=ir_set.expr, is_phony=True), ctx=ctx
)
rptrcls: Optional[s_pointers.PointerLike]
if rptr is not None:
rptrcls = typegen.ptrcls_from_ptrref(rptr.ptrref, ctx=ctx)
else:
rptrcls = None
link_view = (
rptrcls is not None and
not rptrcls.is_link_property(ctx.env.schema) and
_link_has_shape(rptrcls, ctx=ctx)
)
if is_objtype or not link_view:
sources.append(stype)
if link_view:
assert rptrcls is not None
sources.append(rptrcls)
shape_ptrs: List[ShapePtr] = []
for source in sources:
for ptr, shape_op in ctx.env.view_shapes[source]:
shape_ptrs.append(ShapePtr(ir_set, ptr, shape_op, None))
_get_shape_configuration_inner(
ir_set, shape_ptrs, stype, parent_view_type=parent_view_type, ctx=ctx)
return shape_ptrs | Return a list of (source_set, ptrcls) pairs as a shape for a given set. | _get_late_shape_configuration | python | geldata/gel | edb/edgeql/compiler/viewgen.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/viewgen.py | Apache-2.0 |
def late_compile_view_shapes(
expr: irast.Base,
*,
rptr: Optional[irast.Pointer] = None,
parent_view_type: Optional[s_types.ExprType] = None,
ctx: context.ContextLevel,
) -> None:
"""Do a late insertion of any unprocessed shapes.
We mainly compile shapes in process_view, but late_compile_view_shapes
is responsible for compiling implicit exposed shapes (containing
only id) and in cases like accessing a semi-joined shape.
"""
pass | Do a late insertion of any unprocessed shapes.
We mainly compile shapes in process_view, but late_compile_view_shapes
is responsible for compiling implicit exposed shapes (containing
only id) and in cases like accessing a semi-joined shape. | late_compile_view_shapes | python | geldata/gel | edb/edgeql/compiler/viewgen.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/viewgen.py | Apache-2.0 |
def _record_created_collection_types(
type: s_types.Type, ctx: context.ContextLevel
) -> None:
"""
Record references to implicitly defined collection types,
so that the alias delta machinery can pick them up.
"""
if isinstance(
type, s_types.Collection
) and not ctx.env.orig_schema.get_by_id(type.id, default=None):
for sub_type in type.get_subtypes(ctx.env.schema):
_record_created_collection_types(sub_type, ctx) | Record references to implicitly defined collection types,
so that the alias delta machinery can pick them up. | _record_created_collection_types | python | geldata/gel | edb/edgeql/compiler/viewgen.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/viewgen.py | Apache-2.0 |
def cartesian_cardinality(
args: Iterable[qltypes.Cardinality],
) -> qltypes.Cardinality:
'''Cardinality of Cartesian product of multiple args.'''
lower, upper = _card_unzip(args)
return _bounds_to_card(product(lower), product(upper)) | Cardinality of Cartesian product of multiple args. | cartesian_cardinality | python | geldata/gel | edb/edgeql/compiler/inference/cardinality.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/inference/cardinality.py | Apache-2.0 |
def max_cardinality(
args: Iterable[qltypes.Cardinality],
) -> qltypes.Cardinality:
'''Maximum lower and upper bound of specified cardinalities.'''
lower, upper = _card_unzip(args)
assert lower, "cannot take max cardinality of no elements"
return _bounds_to_card(max(lower), max(upper)) | Maximum lower and upper bound of specified cardinalities. | max_cardinality | python | geldata/gel | edb/edgeql/compiler/inference/cardinality.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/inference/cardinality.py | Apache-2.0 |
def min_cardinality(
args: Iterable[qltypes.Cardinality],
) -> qltypes.Cardinality:
'''Minimum lower and upper bound of specified cardinalities.'''
lower, upper = _card_unzip(args)
assert lower, "cannot take min cardinality of no elements"
return _bounds_to_card(min(lower), min(upper)) | Minimum lower and upper bound of specified cardinalities. | min_cardinality | python | geldata/gel | edb/edgeql/compiler/inference/cardinality.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/inference/cardinality.py | Apache-2.0 |
def _union_cardinality(
args: Iterable[qltypes.Cardinality],
) -> qltypes.Cardinality:
'''Cardinality of UNION of multiple args.'''
lower, upper = _card_unzip(args)
return _bounds_to_card(
sum(lower, start=CB_ZERO), sum(upper, start=CB_ZERO)) | Cardinality of UNION of multiple args. | _union_cardinality | python | geldata/gel | edb/edgeql/compiler/inference/cardinality.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/inference/cardinality.py | Apache-2.0 |
def get_object_exclusive_constraints(
typ: s_types.Type,
ptr_set: Set[s_pointers.Pointer],
env: context.Environment,
) -> Dict[s_constraints.Constraint, FrozenSet[s_pointers.Pointer]]:
"""Collect any exclusive object constraints that apply.
An object constraint applies if all of the pointers referenced
in it are filtered on in the query.
"""
if not isinstance(typ, s_objtypes.ObjectType):
return {}
schema = env.schema
exclusive = schema.get('std::exclusive', type=s_constraints.Constraint)
cnstrs = {}
typ = typ.get_nearest_non_derived_parent(schema)
for constr in typ.get_constraints(schema).objects(schema):
if (
constr.issubclass(schema, exclusive)
and (subjectexpr := constr.get_subjectexpr(schema))
# We ignore constraints with except expressions, because
# they can't actually ensure cardinality
and not constr.get_except_expr(schema)
# And delegated constraints can't either
and not constr.get_delegated(schema)
):
if subjectexpr.refs is None:
continue
pointer_refs = frozenset({
x for x in subjectexpr.refs.objects(schema)
if isinstance(x, s_pointers.Pointer)
})
# If all of the referenced pointers are filtered on,
# we match.
if pointer_refs.issubset(ptr_set):
cnstrs[constr] = pointer_refs
return cnstrs | Collect any exclusive object constraints that apply.
An object constraint applies if all of the pointers referenced
in it are filtered on in the query. | get_object_exclusive_constraints | python | geldata/gel | edb/edgeql/compiler/inference/cardinality.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/inference/cardinality.py | Apache-2.0 |
def is_subset_cardinality(
card0: qltypes.Cardinality, card1: qltypes.Cardinality
) -> bool:
'''Determine if card0 is a subset of card1.'''
l0, u0 = _card_to_bounds(card0)
l1, u1 = _card_to_bounds(card1)
return l0 >= l1 and u0 <= u1 | Determine if card0 is a subset of card1. | is_subset_cardinality | python | geldata/gel | edb/edgeql/compiler/inference/cardinality.py | https://github.com/geldata/gel/blob/master/edb/edgeql/compiler/inference/cardinality.py | Apache-2.0 |
def flatten(self) -> tuple[typing.Any, ...]:
"""Flatten out the trans type into a tuple representation.
The idea here is to produce something that our inner loop in cython
can consume efficiently.
"""
raise NotImplementedError | Flatten out the trans type into a tuple representation.
The idea here is to produce something that our inner loop in cython
can consume efficiently. | flatten | python | geldata/gel | edb/ir/ast.py | https://github.com/geldata/gel/blob/master/edb/ir/ast.py | Apache-2.0 |
def material_type(self) -> TypeRef:
"""The proper material type being operated on.
This should have all views stripped out.
"""
raise NotImplementedError | The proper material type being operated on.
This should have all views stripped out. | material_type | python | geldata/gel | edb/ir/ast.py | https://github.com/geldata/gel/blob/master/edb/ir/ast.py | Apache-2.0 |
def from_type(
cls,
schema: s_schema.Schema,
t: s_types.Type,
*,
env: Optional[qlcompiler_ctx.Environment],
namespace: AbstractSet[Namespace] = frozenset(),
typename: Optional[s_name.QualName] = None,
) -> PathId:
"""Return a ``PathId`` instance for a given :class:`schema.types.Type`
The returned ``PathId`` instance describes a set variable of type *t*.
The name of the passed type is used as the name for the variable,
unless *typename* is specified, in which case it is used instead.
Args:
schema:
A schema instance where the type *t* is defined.
t:
The type of the variable being defined.
env:
Optional EdgeQL compiler environment, used for caching.
namespace:
Optional namespace in which the variable is defined.
typename:
If specified, used as the name for the variable instead
of the name of the type *t*.
Returns:
A ``PathId`` instance of type *t*.
"""
if not isinstance(t, s_types.Type):
raise ValueError(
f'invalid PathId: bad source: {t!r}')
cache = env.type_ref_cache if env is not None else None
typeref = typeutils.type_to_typeref(
schema, t, cache=cache, typename=typename
)
return cls.from_typeref(typeref, namespace=namespace,
typename=typename) | Return a ``PathId`` instance for a given :class:`schema.types.Type`
The returned ``PathId`` instance describes a set variable of type *t*.
The name of the passed type is used as the name for the variable,
unless *typename* is specified, in which case it is used instead.
Args:
schema:
A schema instance where the type *t* is defined.
t:
The type of the variable being defined.
env:
Optional EdgeQL compiler environment, used for caching.
namespace:
Optional namespace in which the variable is defined.
typename:
If specified, used as the name for the variable instead
of the name of the type *t*.
Returns:
A ``PathId`` instance of type *t*. | from_type | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def from_pointer(
cls,
schema: s_schema.Schema,
pointer: s_pointers.Pointer,
*,
namespace: AbstractSet[Namespace] = frozenset(),
env: Optional[qlcompiler_ctx.Environment],
) -> PathId:
"""Return a ``PathId`` instance for a given link or property.
The specified *pointer* argument must be a concrete link or property.
The returned ``PathId`` instance describes a set variable of all
objects represented by the pointer (i.e, for a link, a set of all
link targets).
Args:
schema:
A schema instance where the type *t* is defined.
pointer:
An instance of a concrete link or property.
namespace:
Optional namespace in which the variable is defined.
Returns:
A ``PathId`` instance.
"""
if pointer.is_non_concrete(schema):
raise ValueError(f'invalid PathId: {pointer} is not concrete')
source = pointer.get_source(schema)
if isinstance(source, s_pointers.Pointer):
prefix = cls.from_pointer(
schema, source, namespace=namespace, env=env
)
prefix = prefix.ptr_path()
elif isinstance(source, s_types.Type):
prefix = cls.from_type(schema, source, namespace=namespace, env=env)
else:
raise AssertionError(f'unexpected pointer source: {source!r}')
typeref_cache = env.type_ref_cache if env is not None else None
ptrref_cache = env.ptr_ref_cache if env is not None else None
ptrref = typeutils.ptrref_from_ptrcls(
schema=schema, ptrcls=pointer,
cache=ptrref_cache, typeref_cache=typeref_cache,
)
return prefix.extend(ptrref=ptrref) | Return a ``PathId`` instance for a given link or property.
The specified *pointer* argument must be a concrete link or property.
The returned ``PathId`` instance describes a set variable of all
objects represented by the pointer (i.e, for a link, a set of all
link targets).
Args:
schema:
A schema instance where the type *t* is defined.
pointer:
An instance of a concrete link or property.
namespace:
Optional namespace in which the variable is defined.
Returns:
A ``PathId`` instance. | from_pointer | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def from_typeref(
cls,
typeref: irast.TypeRef,
*,
namespace: AbstractSet[Namespace] = frozenset(),
typename: Optional[Union[s_name.Name, uuid.UUID]] = None,
) -> PathId:
"""Return a ``PathId`` instance for a given :class:`ir.ast.TypeRef`
The returned ``PathId`` instance describes a set variable of type
described by *typeref*. The name of the passed type is used as
the name for the variable, unless *typename* is specified, in
which case it is used instead.
Args:
typeref:
The descriptor of a type of the variable being defined.
namespace:
Optional namespace in which the variable is defined.
typename:
If specified, used as the name for the variable instead
of the name of the type *t*.
Returns:
A ``PathId`` instance of type described by *typeref*.
"""
pid = cls()
pid._path = (typeref,)
if typename is None:
typename = typeref.id
pid._norm_path = (typename,)
pid._namespace = frozenset(namespace)
return pid | Return a ``PathId`` instance for a given :class:`ir.ast.TypeRef`
The returned ``PathId`` instance describes a set variable of type
described by *typeref*. The name of the passed type is used as
the name for the variable, unless *typename* is specified, in
which case it is used instead.
Args:
typeref:
The descriptor of a type of the variable being defined.
namespace:
Optional namespace in which the variable is defined.
typename:
If specified, used as the name for the variable instead
of the name of the type *t*.
Returns:
A ``PathId`` instance of type described by *typeref*. | from_typeref | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def from_ptrref(
cls,
ptrref: irast.PointerRef,
*,
namespace: AbstractSet[Namespace] = frozenset(),
) -> PathId:
"""Return a ``PathId`` instance for a given :class:`ir.ast.PointerRef`
Args:
ptrref:
The descriptor of a ptr of the variable being defined.
namespace:
Optional namespace in which the variable is defined.
Returns:
A ``PathId`` instance of type described by *ptrref*.
"""
pid = cls.from_typeref(ptrref.out_source, namespace=namespace)
pid = pid.extend(ptrref=ptrref)
return pid | Return a ``PathId`` instance for a given :class:`ir.ast.PointerRef`
Args:
ptrref:
The descriptor of a ptr of the variable being defined.
namespace:
Optional namespace in which the variable is defined.
Returns:
A ``PathId`` instance of type described by *ptrref*. | from_ptrref | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def extend(
self,
*,
ptrref: irast.BasePointerRef,
direction: s_pointers.PointerDirection = (
s_pointers.PointerDirection.Outbound),
ns: AbstractSet[Namespace] = frozenset(),
) -> PathId:
"""Return a new ``PathId`` that is a *path step* from this ``PathId``.
For example, if you have a ``PathId`` that describes a variable ``A``,
and you want to obtain a ``PathId`` for ``A.b``, you should call
``path_id_for_A.extend(ptrcls=pointer_object_b, schema=schema)``.
Args:
ptrref:
A ``ir.ast.BasePointerRef`` instance that corresponds
to the path step. This may be a regular link or property
object, or a pseudo-pointer, like a tuple or type intersection
step.
direction:
The direction of the *ptrcls* pointer. This makes sense
only for reverse link traversal, all other path steps are
always forward.
namespace:
Optional namespace in which the path extension is defined.
If not specified, the namespace of the current PathId is
used.
schema:
A schema instance.
Returns:
A new ``PathId`` instance representing a step extension of
this ``PathId``.
"""
if not self:
raise ValueError('cannot extend empty PathId')
if direction is s_pointers.PointerDirection.Outbound:
target_ref = ptrref.out_target
else:
target_ref = ptrref.out_source
is_linkprop = ptrref.source_ptr is not None
if is_linkprop and not self._is_ptr:
raise ValueError(
'link property path extension on a non-link path')
result = self.__class__()
result._path = self._path + ((ptrref, direction), target_ref)
link_name = ptrref.name
lnk = (link_name, direction, is_linkprop)
result._is_linkprop = is_linkprop
if target_ref.material_type is not None:
material_type = target_ref.material_type
else:
material_type = target_ref
result._norm_path = (self._norm_path + (lnk, material_type.id))
if ns:
if self._namespace:
result._namespace = self._namespace | frozenset(ns)
else:
result._namespace = frozenset(ns)
else:
result._namespace = self._namespace
if self._namespace != result._namespace:
result._prefix = self
else:
result._prefix = self._prefix
return result | Return a new ``PathId`` that is a *path step* from this ``PathId``.
For example, if you have a ``PathId`` that describes a variable ``A``,
and you want to obtain a ``PathId`` for ``A.b``, you should call
``path_id_for_A.extend(ptrcls=pointer_object_b, schema=schema)``.
Args:
ptrref:
A ``ir.ast.BasePointerRef`` instance that corresponds
to the path step. This may be a regular link or property
object, or a pseudo-pointer, like a tuple or type intersection
step.
direction:
The direction of the *ptrcls* pointer. This makes sense
only for reverse link traversal, all other path steps are
always forward.
namespace:
Optional namespace in which the path extension is defined.
If not specified, the namespace of the current PathId is
used.
schema:
A schema instance.
Returns:
A new ``PathId`` instance representing a step extension of
this ``PathId``. | extend | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def replace_namespace(
self,
namespace: AbstractSet[Namespace],
) -> PathId:
"""Return a copy of this ``PathId`` with namespace set to *namespace*.
"""
result = self.__class__(self)
result._namespace = frozenset(namespace)
if result._prefix is not None:
result._prefix = result._get_minimal_prefix(
result._prefix.replace_namespace(namespace))
return result | Return a copy of this ``PathId`` with namespace set to *namespace*. | replace_namespace | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def merge_namespace(
self,
namespace: AbstractSet[Namespace],
*,
deep: bool=False,
) -> PathId:
"""Return a copy of this ``PathId`` that has *namespace* added to its
namespace.
"""
new_namespace = self._namespace | frozenset(namespace)
if new_namespace != self._namespace or deep:
result = self.__class__(self)
result._namespace = new_namespace
if deep and result._prefix is not None:
result._prefix = result._prefix.merge_namespace(new_namespace)
if result._prefix is not None:
result._prefix = result._get_minimal_prefix(result._prefix)
return result
else:
return self | Return a copy of this ``PathId`` that has *namespace* added to its
namespace. | merge_namespace | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def strip_namespace(self, namespace: AbstractSet[Namespace]) -> PathId:
"""Return a copy of this ``PathId`` with a given portion of the
namespace id removed."""
if self._namespace and namespace:
stripped_ns = self._namespace - set(namespace)
result = self.replace_namespace(stripped_ns)
if result._prefix is not None:
result._prefix = result._get_minimal_prefix(
result._prefix.strip_namespace(namespace))
return result
else:
return self | Return a copy of this ``PathId`` with a given portion of the
namespace id removed. | strip_namespace | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def pformat_internal(self, debug: bool = False) -> str:
"""Verbose format for debugging purposes."""
result = ''
if not self._path:
return ''
if self._namespace:
result += f'{"@".join(sorted(self._namespace))}@@'
path = self._path
result += f'({path[0].name_hint})' # type: ignore
for i in range(1, len(path) - 1, 2):
ptrspec = cast(
Tuple[irast.BasePointerRef, s_pointers.PointerDirection],
path[i],
)
tgtspec = cast(
irast.TypeRef,
path[i + 1],
)
if debug:
link_name = str(ptrspec[0].name)
ptr = f'({link_name})'
else:
ptr = ptrspec[0].shortname.name
ptrdir = ptrspec[1]
is_lprop = ptrspec[0].source_ptr is not None
if tgtspec.material_type is not None:
mat_tgt = tgtspec.material_type
else:
mat_tgt = tgtspec
tgt = mat_tgt.name_hint
if tgt:
lexpr = f'{ptr}[IS {tgt}]'
else:
lexpr = f'{ptr}'
if is_lprop:
step = '@'
else:
step = f'.{ptrdir}'
result += f'{step}{lexpr}'
if self._is_ptr:
result += '@'
return result | Verbose format for debugging purposes. | pformat_internal | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def pformat(self) -> str:
"""Pretty PathId format for user-visible messages."""
result = ''
if not self._path:
return ''
path = self._path
start_name = s_name.shortname_from_fullname(
path[0].name_hint) # type: ignore
result += f'{start_name.name}'
for i in range(1, len(path) - 1, 2):
ptrspec = cast(
Tuple[irast.BasePointerRef, s_pointers.PointerDirection],
path[i],
)
ptr_name = ptrspec[0].shortname
ptrdir = ptrspec[1]
is_lprop = ptrspec[0].source_ptr is not None
if is_lprop:
step = '@'
else:
step = '.'
if ptrdir == s_pointers.PointerDirection.Inbound:
step += ptrdir
result += f'{step}{ptr_name.name}'
if self._is_ptr:
result += '@'
return result | Pretty PathId format for user-visible messages. | pformat | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def rptr(self) -> Optional[irast.BasePointerRef]:
"""Return the descriptor of a pointer for the last path step, if any.
If this PathId represents a non-path expression, ``rptr()``
will return ``None``.
"""
if len(self._path) > 1:
return self._path[-2][0] # type: ignore
else:
return None | Return the descriptor of a pointer for the last path step, if any.
If this PathId represents a non-path expression, ``rptr()``
will return ``None``. | rptr | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def rptr_dir(self) -> Optional[s_pointers.PointerDirection]:
"""Return the direction of a pointer for the last path step, if any.
If this PathId represents a non-path expression, ``rptr_dir()``
will return ``None``.
"""
if len(self._path) > 1:
return self._path[-2][1] # type: ignore
else:
return None | Return the direction of a pointer for the last path step, if any.
If this PathId represents a non-path expression, ``rptr_dir()``
will return ``None``. | rptr_dir | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def rptr_name(self) -> Optional[s_name.QualName]:
"""Return the name of a pointer for the last path step, if any.
If this PathId represents a non-path expression, ``rptr_name()``
will return ``None``.
"""
rptr = self.rptr()
if rptr is not None:
return rptr.shortname
else:
return None | Return the name of a pointer for the last path step, if any.
If this PathId represents a non-path expression, ``rptr_name()``
will return ``None``. | rptr_name | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def src_path(self) -> Optional[PathId]:
"""Return a ``PathId`` instance representing an immediate path prefix
of this ``PathId``, i.e
``PathId('Foo.bar.baz').src_path() == PathId('Foo.bar')``.
If this PathId represents a non-path expression, ``src_path()``
will return ``None``.
"""
if len(self._path) > 1:
return self._get_prefix(-2)
else:
return None | Return a ``PathId`` instance representing an immediate path prefix
of this ``PathId``, i.e
``PathId('Foo.bar.baz').src_path() == PathId('Foo.bar')``.
If this PathId represents a non-path expression, ``src_path()``
will return ``None``. | src_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def ptr_path(self) -> PathId:
"""Return a new ``PathId`` instance that is a "pointer prefix" of this
``PathId``.
A pointer prefix is the common path prefix shared by paths to
link properties of the same link, i.e
common_path_id(Foo.bar@prop1, Foo.bar@prop2)
== PathId(Foo.bar).ptr_path()
"""
if self._is_ptr:
return self
else:
result = self.__class__(self)
result._is_ptr = True
return result | Return a new ``PathId`` instance that is a "pointer prefix" of this
``PathId``.
A pointer prefix is the common path prefix shared by paths to
link properties of the same link, i.e
common_path_id(Foo.bar@prop1, Foo.bar@prop2)
== PathId(Foo.bar).ptr_path() | ptr_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def tgt_path(self) -> PathId:
"""If this is a pointer prefix, return the ``PathId`` representing
the path to the target of the pointer.
This is the inverse of :meth:`~PathId.ptr_path`.
"""
if not self._is_ptr:
return self
else:
result = self.__class__(self)
result._is_ptr = False
return result | If this is a pointer prefix, return the ``PathId`` representing
the path to the target of the pointer.
This is the inverse of :meth:`~PathId.ptr_path`. | tgt_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def iter_prefixes(self, include_ptr: bool = False) -> Iterator[PathId]:
"""Return an iterator over all prefixes of this ``PathId``.
The order of prefixes is from longest to shortest, i.e
``PathId(A.b.c.d).iter_prefixes()`` will yield
[PathId(A.b.c.d), PathId(A.b.c), PathId(A.b), PathId(A)].
If *include_ptr* is ``True``, then pointer prefixes for each
step are also included.
"""
if self._prefix is not None:
yield from self._prefix.iter_prefixes(include_ptr=include_ptr)
start = len(self._prefix)
else:
yield self._get_prefix(1)
start = 1
for i in range(start, len(self._path) - 1, 2):
path_id = self._get_prefix(i + 2)
if path_id.is_ptr_path():
yield path_id.tgt_path()
if include_ptr:
yield path_id
else:
yield path_id | Return an iterator over all prefixes of this ``PathId``.
The order of prefixes is from longest to shortest, i.e
``PathId(A.b.c.d).iter_prefixes()`` will yield
[PathId(A.b.c.d), PathId(A.b.c), PathId(A.b), PathId(A)].
If *include_ptr* is ``True``, then pointer prefixes for each
step are also included. | iter_prefixes | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def startswith(
self, path_id: PathId, permissive_ptr_path: bool = False
) -> bool:
"""Return true if this ``PathId`` has *path_id* as a prefix."""
base = self._get_prefix(len(path_id))
return base == path_id or (
permissive_ptr_path and base.tgt_path() == path_id) | Return true if this ``PathId`` has *path_id* as a prefix. | startswith | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def target(self) -> irast.TypeRef:
"""Return the type descriptor for this PathId."""
return self._path[-1] # type: ignore | Return the type descriptor for this PathId. | target | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def target_name_hint(self) -> s_name.Name:
"""Return the name of the type for this PathId."""
if self.target.material_type is not None:
material_type = self.target.material_type
else:
material_type = self.target
return material_type.name_hint | Return the name of the type for this PathId. | target_name_hint | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_objtype_path(self) -> bool:
"""Return True if this PathId represents an expression of object
type.
"""
return not self.is_ptr_path() and typeutils.is_object(self.target) | Return True if this PathId represents an expression of object
type. | is_objtype_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_scalar_path(self) -> bool:
"""Return True if this PathId represents an expression of scalar
type.
"""
return not self.is_ptr_path() and typeutils.is_scalar(self.target) | Return True if this PathId represents an expression of scalar
type. | is_scalar_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_view_path(self) -> bool:
"""Return True if this PathId represents an expression that is a view.
"""
return not self.is_ptr_path() and typeutils.is_view(self.target) | Return True if this PathId represents an expression that is a view. | is_view_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_tuple_path(self) -> bool:
"""Return True if this PathId represents an expression of an tuple
type.
"""
return not self.is_ptr_path() and typeutils.is_tuple(self.target) | Return True if this PathId represents an expression of an tuple
type. | is_tuple_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_tuple_indirection_path(self) -> bool:
"""Return True if this PathId represents a tuple element indirection
expression.
"""
src_path = self.src_path()
return src_path is not None and src_path.is_tuple_path() | Return True if this PathId represents a tuple element indirection
expression. | is_tuple_indirection_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_array_path(self) -> bool:
"""Return True if this PathId represents an expression of an array
type.
"""
return not self.is_ptr_path() and typeutils.is_array(self.target) | Return True if this PathId represents an expression of an array
type. | is_array_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_range_path(self) -> bool:
"""Return True if this PathId represents an expression of a range
type.
"""
return not self.is_ptr_path() and typeutils.is_range(self.target) | Return True if this PathId represents an expression of a range
type. | is_range_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_collection_path(self) -> bool:
"""Return True if this PathId represents an expression of a collection
type.
"""
return not self.is_ptr_path() and typeutils.is_collection(self.target) | Return True if this PathId represents an expression of a collection
type. | is_collection_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_ptr_path(self) -> bool:
"""Return True if this PathId represents a link prefix of the path.
Immediate prefix of a link property ``PathId`` will return True here.
"""
return self._is_ptr | Return True if this PathId represents a link prefix of the path.
Immediate prefix of a link property ``PathId`` will return True here. | is_ptr_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_linkprop_path(self) -> bool:
"""Return True if this PathId represents a link property path
expression, i.e ``Foo.bar@prop``."""
return self._is_linkprop | Return True if this PathId represents a link property path
expression, i.e ``Foo.bar@prop``. | is_linkprop_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def is_type_intersection_path(self) -> bool:
"""Return True if this PathId represents a type intersection
expression, i.e ``Foo[IS Bar]``."""
rptr_name = self.rptr_name()
if rptr_name is None:
return False
else:
return str(rptr_name) in (
'__type__::indirection',
'__type__::optindirection',
) | Return True if this PathId represents a type intersection
expression, i.e ``Foo[IS Bar]``. | is_type_intersection_path | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def namespace(self) -> FrozenSet[str]:
"""The namespace of this ``PathId``"""
return self._namespace | The namespace of this ``PathId`` | namespace | python | geldata/gel | edb/ir/pathid.py | https://github.com/geldata/gel/blob/master/edb/ir/pathid.py | Apache-2.0 |
def get_edgeql_type(cls) -> s_name.QualName:
"""Return fully-qualified name of the scalar type for this setting."""
assert cls._eql_type is not None
return cls._eql_type | Return fully-qualified name of the scalar type for this setting. | get_edgeql_type | python | geldata/gel | edb/ir/statypes.py | https://github.com/geldata/gel/blob/master/edb/ir/statypes.py | Apache-2.0 |
def to_backend_str(self) -> str:
"""Convert static frontend config value to backend config value."""
return self.get_translation_map()[self._val] | Convert static frontend config value to backend config value. | to_backend_str | python | geldata/gel | edb/ir/statypes.py | https://github.com/geldata/gel/blob/master/edb/ir/statypes.py | Apache-2.0 |
def to_backend_expr(cls, expr: str) -> str:
"""Convert dynamic backend config value to frontend config value."""
cases_list = []
for fe_val, be_val in cls.get_translation_map().items():
cases_list.append(f"WHEN lower('{fe_val}') THEN '{be_val}'")
cases = "\n".join(cases_list)
errmsg = f"unexpected frontend value for {cls.__name__}: %s"
err = f"edgedb_VER.raise(NULL::text, msg => format('{errmsg}', v))"
return (
f"(SELECT CASE v\n{cases}\nELSE\n{err}\nEND "
f"FROM lower(({expr})) AS f(v))"
) | Convert dynamic backend config value to frontend config value. | to_backend_expr | python | geldata/gel | edb/ir/statypes.py | https://github.com/geldata/gel/blob/master/edb/ir/statypes.py | Apache-2.0 |
def to_frontend_expr(cls, expr: str) -> Optional[str]:
"""Convert dynamic frontend config value to backend config value."""
cases_list = []
for fe_val, be_val in cls.get_translation_map().items():
cases_list.append(f"WHEN lower('{be_val}') THEN '{fe_val}'")
cases = "\n".join(cases_list)
errmsg = f"unexpected backend value for {cls.__name__}: %s"
err = f"edgedb_VER.raise(NULL::text, msg => format('{errmsg}', v))"
return (
f"(SELECT CASE v\n{cases}\nELSE\n{err}\nEND "
f"FROM lower(({expr})) AS f(v))"
) | Convert dynamic frontend config value to backend config value. | to_frontend_expr | python | geldata/gel | edb/ir/statypes.py | https://github.com/geldata/gel/blob/master/edb/ir/statypes.py | Apache-2.0 |
def get_longest_paths(ir: irast.Base) -> Set[irast.Set]:
"""Return a distinct set of longest paths found in an expression.
For example in SELECT (A.B.C, D.E.F, A.B, D.E) the result would
be {A.B.C, D.E.F}.
"""
result = set()
parents = set()
ir_sets = ast.find_children(
ir,
irast.Set,
lambda n: sub_expr(n) is None or isinstance(n.expr, irast.TypeRoot),
)
for ir_set in ir_sets:
result.add(ir_set)
if isinstance(ir_set.expr, irast.Pointer):
parents.add(ir_set.expr.source)
return result - parents | Return a distinct set of longest paths found in an expression.
For example in SELECT (A.B.C, D.E.F, A.B, D.E) the result would
be {A.B.C, D.E.F}. | get_longest_paths | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def get_parameters(ir: irast.Base) -> Set[irast.Parameter]:
"""Return all parameters found in *ir*."""
return set(ast.find_children(ir, irast.Parameter)) | Return all parameters found in *ir*. | get_parameters | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def is_const(ir: irast.Base) -> bool:
"""Return True if the given *ir* expression is constant."""
roots = ast.find_children(ir, irast.TypeRoot)
variables = get_parameters(ir)
return not roots and not variables | Return True if the given *ir* expression is constant. | is_const | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def is_union_expr(ir: irast.Base) -> bool:
"""Return True if the given *ir* expression is a UNION expression."""
return (
isinstance(ir, irast.OperatorCall) and
ir.operator_kind is ft.OperatorKind.Infix and
str(ir.func_shortname) == 'std::UNION'
) | Return True if the given *ir* expression is a UNION expression. | is_union_expr | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def is_empty_array_expr(ir: Optional[irast.Base]) -> TypeGuard[irast.Array]:
"""Return True if the given *ir* expression is an empty array expression.
"""
return (
isinstance(ir, irast.Array)
and not ir.elements
) | Return True if the given *ir* expression is an empty array expression. | is_empty_array_expr | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def is_untyped_empty_array_expr(
ir: Optional[irast.Base],
) -> TypeGuard[irast.Array]:
"""Return True if the given *ir* expression is an empty
array expression of an uknown type.
"""
return (
is_empty_array_expr(ir)
and (ir.typeref is None
or typeutils.is_generic(ir.typeref))
) | Return True if the given *ir* expression is an empty
array expression of an uknown type. | is_untyped_empty_array_expr | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def is_empty(ir: irast.Base) -> bool:
"""Return True if the given *ir* expression is an empty set
or an empty array.
"""
return (
isinstance(ir, irast.EmptySet) or
(isinstance(ir, irast.Array) and not ir.elements) or
(
isinstance(ir, irast.Set)
and is_empty(ir.expr)
)
) | Return True if the given *ir* expression is an empty set
or an empty array. | is_empty | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def is_subquery_set(ir_expr: irast.Base) -> bool:
"""Return True if the given *ir_expr* expression is a subquery."""
return (
isinstance(ir_expr, irast.Set)
and (
isinstance(ir_expr.expr, irast.Stmt)
or (
isinstance(ir_expr.expr, irast.Pointer)
and ir_expr.expr.expr is not None
)
)
) | Return True if the given *ir_expr* expression is a subquery. | is_subquery_set | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def is_implicit_wrapper(
ir_expr: Optional[irast.Base],
) -> TypeGuard[irast.SelectStmt]:
"""Return True if the given *ir_expr* expression is an implicit
SELECT wrapper.
"""
return (
isinstance(ir_expr, irast.SelectStmt) and
ir_expr.implicit_wrapper
) | Return True if the given *ir_expr* expression is an implicit
SELECT wrapper. | is_implicit_wrapper | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def is_trivial_select(ir_expr: irast.Base) -> TypeGuard[irast.SelectStmt]:
"""Return True if the given *ir_expr* expression is a trivial
SELECT expression, i.e `SELECT <expr>`.
"""
if not isinstance(ir_expr, irast.SelectStmt):
return False
return (
not ir_expr.orderby
and ir_expr.iterator_stmt is None
and ir_expr.where is None
and ir_expr.limit is None
and ir_expr.offset is None
and ir_expr.card_inference_override is None
) | Return True if the given *ir_expr* expression is a trivial
SELECT expression, i.e `SELECT <expr>`. | is_trivial_select | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def unwrap_set(ir_set: irast.Set) -> irast.Set:
"""If the given *ir_set* is an implicit SELECT wrapper, return the
wrapped set.
"""
if is_implicit_wrapper(ir_set.expr):
return ir_set.expr.result
else:
return ir_set | If the given *ir_set* is an implicit SELECT wrapper, return the
wrapped set. | unwrap_set | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def is_type_intersection_reference(ir_expr: irast.Base) -> bool:
"""Return True if the given *ir_expr* is a type intersection, i.e
``Foo[IS Type]``.
"""
if not isinstance(ir_expr, irast.Set):
return False
if not isinstance(ir_expr.expr, irast.Pointer):
return False
rptr = ir_expr.expr
ir_source = rptr.source
if ir_source.path_id.is_type_intersection_path():
source_is_type_intersection = True
else:
source_is_type_intersection = False
return source_is_type_intersection | Return True if the given *ir_expr* is a type intersection, i.e
``Foo[IS Type]``. | is_type_intersection_reference | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def get_dml_sources(ir_set: irast.Set) -> Sequence[irast.MutatingLikeStmt]:
"""Find the DML expressions that can contribute to the value of a set
This is used to compute which overlays to use during SQL compilation.
"""
# TODO: Make this caching.
visitor = CollectDMLSourceVisitor()
visitor.visit(ir_set)
# Deduplicate, but preserve order. It shouldn't matter for
# *correctness* but it helps keep the nondeterminism in the output
# SQL down.
return tuple(ordered.OrderedSet(visitor.dml)) | Find the DML expressions that can contribute to the value of a set
This is used to compute which overlays to use during SQL compilation. | get_dml_sources | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def contains_dml(
stmt: irast.Base,
*,
skip_bindings: bool = False,
skip_nodes: Iterable[irast.Base] = (),
) -> bool:
"""Check whether a statement contains any DML in a subtree."""
# TODO: Make this caching.
visitor = ContainsDMLVisitor(skip_bindings=skip_bindings)
for node in skip_nodes:
visitor._memo[node] = False
res = visitor.visit(stmt) is True
return res | Check whether a statement contains any DML in a subtree. | contains_dml | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def find_potentially_visible(
stmt: irast.Base,
scope: irast.ScopeTreeNode,
scope_tree_nodes: Mapping[int, irast.ScopeTreeNode],
to_skip: AbstractSet[irast.PathId]=frozenset()
) -> Set[Tuple[irast.PathId, irast.Set]]:
"""Find all "potentially visible" sets referenced."""
# TODO: Make this caching.
visitor = FindPotentiallyVisibleVisitor(
to_skip=to_skip, scope=scope, scope_tree_nodes=scope_tree_nodes)
visible_sets = cast(Set[irast.Set], visitor.visit(stmt))
visible_paths = set()
for ir in visible_sets:
path_id = ir.path_id
# Collect any namespaces between where the set is referred to
# and the binding point we are looking from, and strip those off.
# We need to do this because visibility *from the binding point*
# needs to not include namespaces defined below it.
# (See test_edgeql_scope_ref_side_02 for an example where this
# matters.)
if (set_scope_id := visitor.scopes.get(ir)) is not None:
set_scope = scope_tree_nodes[set_scope_id]
for anc, ns in set_scope.ancestors_and_namespaces:
if anc is scope:
path_id = path_id.strip_namespace(ns)
break
visible_paths.add((path_id, ir))
return visible_paths | Find all "potentially visible" sets referenced. | find_potentially_visible | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def sub_expr(ir: irast.Set) -> Optional[irast.Expr]:
"""Fetch the "sub-expression" of a set.
For a non-pointer Set, it's just the expr, but for a Pointer
it is the optional computed expression.
"""
if isinstance(ir.expr, irast.Pointer):
return ir.expr.expr
else:
return ir.expr | Fetch the "sub-expression" of a set.
For a non-pointer Set, it's just the expr, but for a Pointer
it is the optional computed expression. | sub_expr | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def collect_schema_types(stmt: irast.Base) -> Set[uuid.UUID]:
"""Collect ids of all types referenced in the statement."""
visitor = CollectSchemaTypesVisitor()
visitor.visit(stmt)
return visitor.types | Collect ids of all types referenced in the statement. | collect_schema_types | python | geldata/gel | edb/ir/utils.py | https://github.com/geldata/gel/blob/master/edb/ir/utils.py | Apache-2.0 |
def is_scalar(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes a scalar type."""
return typeref.is_scalar | Return True if *typeref* describes a scalar type. | is_scalar | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_object(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes an object type."""
return (
not is_scalar(typeref)
and not is_collection(typeref)
and not is_generic(typeref)
) | Return True if *typeref* describes an object type. | is_object | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_view(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes a view."""
return typeref.is_view | Return True if *typeref* describes a view. | is_view | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_collection(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes an collection type."""
return bool(typeref.collection) | Return True if *typeref* describes an collection type. | is_collection | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_array(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes an array type."""
return typeref.collection == s_types.Array.get_schema_name() | Return True if *typeref* describes an array type. | is_array | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_tuple(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes a tuple type."""
return typeref.collection == s_types.Tuple.get_schema_name() | Return True if *typeref* describes a tuple type. | is_tuple | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_range(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes a range type."""
return typeref.collection == s_types.Range.get_schema_name() | Return True if *typeref* describes a range type. | is_range | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_multirange(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes a multirange type."""
return typeref.collection == s_types.MultiRange.get_schema_name() | Return True if *typeref* describes a multirange type. | is_multirange | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_any(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes the ``anytype`` generic type."""
return isinstance(typeref, irast.AnyTypeRef) | Return True if *typeref* describes the ``anytype`` generic type. | is_any | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_anytuple(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes the ``anytuple`` generic type."""
return isinstance(typeref, irast.AnyTupleRef) | Return True if *typeref* describes the ``anytuple`` generic type. | is_anytuple | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_anyobject(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes the ``anyobject`` generic type."""
return isinstance(typeref, irast.AnyObjectRef) | Return True if *typeref* describes the ``anyobject`` generic type. | is_anyobject | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_generic(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes a generic type."""
if is_collection(typeref):
return any(is_generic(st) for st in typeref.subtypes)
else:
return is_any(typeref) or is_anytuple(typeref) or is_anyobject(typeref) | Return True if *typeref* describes a generic type. | is_generic | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_abstract(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes an abstract type."""
return typeref.is_abstract | Return True if *typeref* describes an abstract type. | is_abstract | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_json(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes the json type."""
return typeref.real_base_type.id == s_obj.get_known_type_id('std::json') | Return True if *typeref* describes the json type. | is_json | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_bytes(typeref: irast.TypeRef) -> bool:
"""Return True if *typeref* describes the bytes type."""
return typeref.real_base_type.id == s_obj.get_known_type_id('std::bytes') | Return True if *typeref* describes the bytes type. | is_bytes | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def type_to_typeref(
schema: s_schema.Schema,
t: s_types.Type,
*,
cache: Optional[Dict[TypeRefCacheKey, irast.TypeRef]],
typename: Optional[s_name.QualName] = None,
include_children: bool = False,
include_ancestors: bool = False,
_name: Optional[str] = None,
) -> irast.TypeRef:
"""Return an instance of :class:`ir.ast.TypeRef` for a given type.
An IR TypeRef is an object that fully describes a schema type for
the purposes of query compilation.
Args:
schema:
A schema instance, in which the type *t* is defined.
t:
A schema type instance.
cache:
Optional mapping from (type UUID, typename) to cached IR TypeRefs.
typename:
Optional name hint to use for the type in the returned
TypeRef. If ``None``, the type name is used.
include_children:
Whether to include the description of all material type children
of *t*.
include_ancestors:
Whether to include the description of all material type ancestors
of *t*.
_name:
Optional subtype element name if this type is a collection within
a Tuple,
Returns:
A ``TypeRef`` instance corresponding to the given schema type.
"""
if cache is not None and typename is None:
key = (t.id, include_children, include_ancestors)
cached_result = cache.get(key)
if cached_result is not None:
# If the schema changed due to an ongoing compilation, the name
# hint might be outdated.
if cached_result.name_hint == t.get_name(schema):
return cached_result
# We separate the uncached version into another function because
# it makes it easy to tell in a profiler when the cache isn't
# operating, and because if the cache *is* operating it is no
# great loss.
return _type_to_typeref(
schema,
t,
cache=cache,
typename=typename,
include_children=include_children,
include_ancestors=include_ancestors,
_name=_name,
) | Return an instance of :class:`ir.ast.TypeRef` for a given type.
An IR TypeRef is an object that fully describes a schema type for
the purposes of query compilation.
Args:
schema:
A schema instance, in which the type *t* is defined.
t:
A schema type instance.
cache:
Optional mapping from (type UUID, typename) to cached IR TypeRefs.
typename:
Optional name hint to use for the type in the returned
TypeRef. If ``None``, the type name is used.
include_children:
Whether to include the description of all material type children
of *t*.
include_ancestors:
Whether to include the description of all material type ancestors
of *t*.
_name:
Optional subtype element name if this type is a collection within
a Tuple,
Returns:
A ``TypeRef`` instance corresponding to the given schema type. | type_to_typeref | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def ir_typeref_to_type(
schema: s_schema.Schema,
typeref: irast.TypeRef,
) -> Tuple[s_schema.Schema, s_types.Type]:
"""Return a schema type for a given IR TypeRef.
This is the reverse of :func:`~type_to_typeref`.
Args:
schema:
A schema instance. The result type must exist in it.
typeref:
A :class:`ir.ast.TypeRef` instance for which to return
the corresponding schema type.
Returns:
A tuple containing the possibly modified schema and
a :class:`schema.types.Type` instance corresponding to the
given *typeref*.
"""
# Optimistically try to lookup the type by id. Sometimes for
# arrays and tuples this will fail, and we'll need to create it.
t = schema.get_by_id(typeref.id, default=None, type=s_types.Type)
if t:
return schema, t
elif is_tuple(typeref):
named = False
tuple_subtypes = {}
for si, st in enumerate(typeref.subtypes):
if st.element_name:
named = True
type_name = st.element_name
else:
type_name = str(si)
schema, st_t = ir_typeref_to_type(schema, st)
tuple_subtypes[type_name] = st_t
return s_types.Tuple.from_subtypes(
schema, tuple_subtypes, {'named': named})
elif is_array(typeref):
array_subtypes = []
for st in typeref.subtypes:
schema, st_t = ir_typeref_to_type(schema, st)
array_subtypes.append(st_t)
return s_types.Array.from_subtypes(schema, array_subtypes)
else:
raise AssertionError("couldn't find type from typeref") | Return a schema type for a given IR TypeRef.
This is the reverse of :func:`~type_to_typeref`.
Args:
schema:
A schema instance. The result type must exist in it.
typeref:
A :class:`ir.ast.TypeRef` instance for which to return
the corresponding schema type.
Returns:
A tuple containing the possibly modified schema and
a :class:`schema.types.Type` instance corresponding to the
given *typeref*. | ir_typeref_to_type | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def ptrref_from_ptrcls(
*,
schema: s_schema.Schema,
ptrcls: s_pointers.PointerLike,
cache: Optional[PtrRefCache],
typeref_cache: Optional[TypeRefCache],
) -> irast.BasePointerRef:
"""Return an IR pointer descriptor for a given schema pointer.
An IR PointerRef is an object that fully describes a schema pointer for
the purposes of query compilation.
Args:
schema:
A schema instance, in which the type *t* is defined.
ptrcls:
A :class:`schema.pointers.Pointer` instance for which to
return the PointerRef.
direction:
The direction of the pointer in the path expression.
Returns:
An instance of a subclass of :class:`ir.ast.BasePointerRef`
corresponding to the given schema pointer.
"""
if cache is not None:
cached = cache.get(ptrcls)
if cached is not None:
return cached
kwargs: Dict[str, Any] = {}
ircls: Type[irast.BasePointerRef]
source_ref: Optional[irast.TypeRef]
target_ref: Optional[irast.TypeRef]
out_source: Optional[irast.TypeRef]
if isinstance(ptrcls, irast.TupleIndirectionLink):
ircls = irast.TupleIndirectionPointerRef
elif isinstance(ptrcls, irast.TypeIntersectionLink):
ircls = irast.TypeIntersectionPointerRef
kwargs['optional'] = ptrcls.is_optional()
kwargs['is_empty'] = ptrcls.is_empty()
kwargs['is_subtype'] = ptrcls.is_subtype()
kwargs['rptr_specialization'] = ptrcls.get_rptr_specialization()
elif isinstance(ptrcls, s_pointers.Pointer):
ircls = irast.PointerRef
kwargs['id'] = ptrcls.id
kwargs['defined_here'] = ptrcls.get_defined_here(schema)
if backlink := ptrcls.get_computed_link_alias(schema):
assert isinstance(backlink, s_pointers.Pointer)
kwargs['computed_link_alias'] = ptrref_from_ptrcls(
ptrcls=backlink, schema=schema,
cache=cache, typeref_cache=typeref_cache,
)
kwargs['computed_link_alias_is_backward'] = (
ptrcls.get_computed_link_alias_is_backward(schema))
else:
raise AssertionError(f'unexpected pointer class: {ptrcls}')
target = ptrcls.get_target(schema)
if target is not None and not isinstance(target, irast.TypeRef):
assert isinstance(target, s_types.Type)
target_ref = type_to_typeref(
schema, target, include_children=True, cache=typeref_cache)
else:
target_ref = target
source = ptrcls.get_source(schema)
source_ptr: Optional[irast.BasePointerRef]
if (isinstance(ptrcls, s_props.Property)
and isinstance(source, s_links.Link)):
source_ptr = ptrref_from_ptrcls(
ptrcls=source,
schema=schema,
cache=cache,
typeref_cache=typeref_cache,
)
source_ref = None
else:
if source is not None and not isinstance(source, irast.TypeRef):
assert isinstance(source, s_types.Type)
source_ref = type_to_typeref(schema,
source,
include_ancestors=True,
cache=typeref_cache)
else:
source_ref = source
source_ptr = None
out_source = source_ref
out_target = target_ref
out_cardinality, in_cardinality = cardinality_from_ptrcls(
schema, ptrcls)
schema, material_ptrcls = ptrcls.material_type(schema)
material_ptr: Optional[irast.BasePointerRef]
if material_ptrcls is not None and material_ptrcls != ptrcls:
material_ptr = ptrref_from_ptrcls(
ptrcls=material_ptrcls,
schema=schema,
cache=cache,
typeref_cache=typeref_cache,
)
else:
material_ptr = None
union_components: Optional[Set[irast.BasePointerRef]] = None
union_of = ptrcls.get_union_of(schema)
union_is_exhaustive = False
if union_of:
union_ptrs = set()
for component in union_of.objects(schema):
assert isinstance(component, s_pointers.Pointer)
schema, material_comp = component.material_type(schema)
union_ptrs.add(material_comp)
non_overlapping, union_is_exhaustive = (
s_utils.get_non_overlapping_union(
schema,
union_ptrs,
)
)
union_components = {
ptrref_from_ptrcls(
ptrcls=p,
schema=schema,
cache=cache,
typeref_cache=typeref_cache,
) for p in non_overlapping
}
intersection_components: Optional[Set[irast.BasePointerRef]] = None
intersection_of = ptrcls.get_intersection_of(schema)
if intersection_of:
intersection_ptrs = set()
for component in intersection_of.objects(schema):
assert isinstance(component, s_pointers.Pointer)
schema, material_comp = component.material_type(schema)
intersection_ptrs.add(material_comp)
intersection_components = {
ptrref_from_ptrcls(
ptrcls=p,
schema=schema,
cache=cache,
typeref_cache=typeref_cache,
) for p in intersection_ptrs
}
std_parent_name = None
for ancestor in ptrcls.get_ancestors(schema).objects(schema):
ancestor_name = ancestor.get_name(schema)
if ancestor_name.module == 'std' and ancestor.is_non_concrete(schema):
std_parent_name = ancestor_name
break
is_derived = ptrcls.get_is_derived(schema)
base_ptr: Optional[irast.BasePointerRef]
if is_derived:
base_ptrcls = ptrcls.get_bases(schema).first(schema)
top_ptr_name = type(base_ptrcls).get_default_base_name()
if base_ptrcls.get_name(schema) != top_ptr_name:
base_ptr = ptrref_from_ptrcls(
ptrcls=base_ptrcls,
schema=schema,
cache=cache,
typeref_cache=typeref_cache,
)
else:
base_ptr = None
else:
base_ptr = None
if (
material_ptr is None
and isinstance(ptrcls, s_pointers.Pointer)
):
children = frozenset(
ptrref_from_ptrcls(
ptrcls=child,
schema=schema,
cache=cache,
typeref_cache=typeref_cache,
)
for child in ptrcls.children(schema)
if not child.get_is_derived(schema)
)
else:
children = frozenset()
kwargs.update(
dict(
out_source=out_source,
out_target=out_target,
name=ptrcls.get_name(schema),
shortname=ptrcls.get_shortname(schema),
std_parent_name=std_parent_name,
source_ptr=source_ptr,
base_ptr=base_ptr,
material_ptr=material_ptr,
children=children,
is_derived=ptrcls.get_is_derived(schema),
is_computable=ptrcls.get_computable(schema),
union_components=union_components,
intersection_components=intersection_components,
union_is_exhaustive=union_is_exhaustive,
has_properties=ptrcls.has_user_defined_properties(schema),
in_cardinality=in_cardinality,
out_cardinality=out_cardinality,
)
)
ptrref = ircls(**kwargs)
if cache is not None:
cache[ptrcls] = ptrref
# This is kind of unfortunate, but if we are caching, update the
# base_ptr with this child
if base_ptr and not material_ptr and ptrref not in base_ptr.children:
base_ptr.children = base_ptr.children | frozenset([ptrref])
return ptrref | Return an IR pointer descriptor for a given schema pointer.
An IR PointerRef is an object that fully describes a schema pointer for
the purposes of query compilation.
Args:
schema:
A schema instance, in which the type *t* is defined.
ptrcls:
A :class:`schema.pointers.Pointer` instance for which to
return the PointerRef.
direction:
The direction of the pointer in the path expression.
Returns:
An instance of a subclass of :class:`ir.ast.BasePointerRef`
corresponding to the given schema pointer. | ptrref_from_ptrcls | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def ptrcls_from_ptrref(
ptrref: irast.BasePointerRef,
*,
schema: s_schema.Schema,
) -> Tuple[s_schema.Schema, s_pointers.PointerLike]:
"""Return a schema pointer for a given IR PointerRef.
This is the reverse of :func:`~type_to_typeref`.
Args:
schema:
A schema instance. The result type must exist in it.
ptrref:
A :class:`ir.ast.BasePointerRef` instance for which to return
the corresponding schema pointer.
Returns:
A tuple containing the possibly modifed schema and
a :class:`schema.pointers.PointerLike` instance corresponding to the
given *ptrref*.
"""
ptrcls: s_pointers.PointerLike
if isinstance(ptrref, irast.TupleIndirectionPointerRef):
schema, src_t = ir_typeref_to_type(schema, ptrref.out_source)
schema, tgt_t = ir_typeref_to_type(schema, ptrref.out_target)
ptrcls = irast.TupleIndirectionLink(
source=src_t,
target=tgt_t,
element_name=ptrref.name.name,
)
elif isinstance(ptrref, irast.TypeIntersectionPointerRef):
target = schema.get_by_id(ptrref.out_target.id)
assert isinstance(target, s_types.Type)
ptrcls = irast.TypeIntersectionLink(
source=schema.get_by_id(ptrref.out_source.id),
target=target,
optional=ptrref.optional,
is_empty=ptrref.is_empty,
is_subtype=ptrref.is_subtype,
cardinality=ptrref.out_cardinality.to_schema_value()[1],
)
elif isinstance(ptrref, irast.PointerRef):
ptr = schema.get_by_id(ptrref.id)
assert isinstance(ptr, s_pointers.Pointer)
ptrcls = ptr
else:
raise TypeError(f'unexpected pointer ref type: {ptrref!r}')
return schema, ptrcls | Return a schema pointer for a given IR PointerRef.
This is the reverse of :func:`~type_to_typeref`.
Args:
schema:
A schema instance. The result type must exist in it.
ptrref:
A :class:`ir.ast.BasePointerRef` instance for which to return
the corresponding schema pointer.
Returns:
A tuple containing the possibly modifed schema and
a :class:`schema.pointers.PointerLike` instance corresponding to the
given *ptrref*. | ptrcls_from_ptrref | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
def is_id_ptrref(ptrref: irast.BasePointerRef) -> bool:
"""Return True if *ptrref* describes the id property."""
return (
str(ptrref.std_parent_name) == 'std::id'
) and not ptrref.source_ptr | Return True if *ptrref* describes the id property. | is_id_ptrref | python | geldata/gel | edb/ir/typeutils.py | https://github.com/geldata/gel/blob/master/edb/ir/typeutils.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.