idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
38,900 | def validate ( self ) : if not isinstance ( self . fold_scope_location , FoldScopeLocation ) : raise TypeError ( u'Expected FoldScopeLocation fold_scope_location, got: {} {}' . format ( type ( self . fold_scope_location ) , self . fold_scope_location ) ) allowed_block_types = ( GremlinFoldedFilter , GremlinFoldedTraverse , Backtrack ) for block in self . folded_ir_blocks : if not isinstance ( block , allowed_block_types ) : raise AssertionError ( u'Found invalid block of type {} in folded_ir_blocks: {} ' u'Allowed types are {}.' . format ( type ( block ) , self . folded_ir_blocks , allowed_block_types ) ) if not isinstance ( self . field_type , GraphQLList ) : raise ValueError ( u'Invalid value of "field_type", expected a list type but got: ' u'{}' . format ( self . field_type ) ) inner_type = strip_non_null_from_type ( self . field_type . of_type ) if isinstance ( inner_type , GraphQLList ) : raise GraphQLCompilationError ( u'Outputting list-valued fields in a @fold context is currently ' u'not supported: {} {}' . format ( self . fold_scope_location , self . field_type . of_type ) ) | Validate that the GremlinFoldedContextField is correctly representable . |
38,901 | def from_traverse ( cls , traverse_block ) : if isinstance ( traverse_block , Traverse ) : return cls ( traverse_block . direction , traverse_block . edge_name ) else : raise AssertionError ( u'Tried to initialize an instance of GremlinFoldedTraverse ' u'with block of type {}' . format ( type ( traverse_block ) ) ) | Create a GremlinFoldedTraverse block as a copy of the given Traverse block . |
38,902 | def _get_referenced_type_equivalences ( graphql_types , type_equivalence_hints ) : referenced_types = set ( ) for graphql_type in graphql_types . values ( ) : if isinstance ( graphql_type , ( GraphQLObjectType , GraphQLInterfaceType ) ) : for _ , field in graphql_type . fields . items ( ) : if isinstance ( field . type , GraphQLList ) : referenced_types . add ( field . type . of_type . name ) return { original : union for original , union in type_equivalence_hints . items ( ) if union . name in referenced_types } | Filter union types with no edges from the type equivalence hints dict . |
38,903 | def _get_inherited_field_types ( class_to_field_type_overrides , schema_graph ) : inherited_field_type_overrides = dict ( ) for superclass_name , field_type_overrides in class_to_field_type_overrides . items ( ) : for subclass_name in schema_graph . get_subclass_set ( superclass_name ) : inherited_field_type_overrides . setdefault ( subclass_name , dict ( ) ) inherited_field_type_overrides [ subclass_name ] . update ( field_type_overrides ) return inherited_field_type_overrides | Return a dictionary describing the field type overrides in subclasses . |
38,904 | def _validate_overriden_fields_are_not_defined_in_superclasses ( class_to_field_type_overrides , schema_graph ) : for class_name , field_type_overrides in six . iteritems ( class_to_field_type_overrides ) : for superclass_name in schema_graph . get_inheritance_set ( class_name ) : if superclass_name != class_name : superclass = schema_graph . get_element_by_class_name ( superclass_name ) for field_name in field_type_overrides : if field_name in superclass . properties : raise AssertionError ( u'Attempting to override field "{}" from class "{}", but the field is ' u'defined in superclass "{}"' . format ( field_name , class_name , superclass_name ) ) | Assert that the fields we want to override are not defined in superclasses . |
38,905 | def _property_descriptor_to_graphql_type ( property_obj ) : property_type = property_obj . type_id scalar_types = { PROPERTY_TYPE_BOOLEAN_ID : GraphQLBoolean , PROPERTY_TYPE_DATE_ID : GraphQLDate , PROPERTY_TYPE_DATETIME_ID : GraphQLDateTime , PROPERTY_TYPE_DECIMAL_ID : GraphQLDecimal , PROPERTY_TYPE_DOUBLE_ID : GraphQLFloat , PROPERTY_TYPE_FLOAT_ID : GraphQLFloat , PROPERTY_TYPE_INTEGER_ID : GraphQLInt , PROPERTY_TYPE_STRING_ID : GraphQLString , } result = scalar_types . get ( property_type , None ) if result : return result mapping_types = { PROPERTY_TYPE_EMBEDDED_SET_ID : GraphQLList , PROPERTY_TYPE_EMBEDDED_LIST_ID : GraphQLList , } wrapping_type = mapping_types . get ( property_type , None ) if wrapping_type : linked_property_obj = property_obj . qualifier if linked_property_obj in scalar_types : return wrapping_type ( scalar_types [ linked_property_obj ] ) return None | Return the best GraphQL type representation for an OrientDB property descriptor . |
38,906 | def _get_union_type_name ( type_names_to_union ) : if not type_names_to_union : raise AssertionError ( u'Expected a non-empty list of type names to union, received: ' u'{}' . format ( type_names_to_union ) ) return u'Union__' + u'__' . join ( sorted ( type_names_to_union ) ) | Construct a unique union type name based on the type names being unioned . |
38,907 | def _get_fields_for_class ( schema_graph , graphql_types , field_type_overrides , hidden_classes , cls_name ) : properties = schema_graph . get_element_by_class_name ( cls_name ) . properties all_properties = { property_name : _property_descriptor_to_graphql_type ( property_obj ) for property_name , property_obj in six . iteritems ( properties ) } result = { property_name : graphql_representation for property_name , graphql_representation in six . iteritems ( all_properties ) if graphql_representation is not None } schema_element = schema_graph . get_element_by_class_name ( cls_name ) outbound_edges = ( ( 'out_{}' . format ( out_edge_name ) , schema_graph . get_element_by_class_name ( out_edge_name ) . properties [ EDGE_DESTINATION_PROPERTY_NAME ] . qualifier ) for out_edge_name in schema_element . out_connections ) inbound_edges = ( ( 'in_{}' . format ( in_edge_name ) , schema_graph . get_element_by_class_name ( in_edge_name ) . properties [ EDGE_SOURCE_PROPERTY_NAME ] . qualifier ) for in_edge_name in schema_element . in_connections ) for field_name , to_type_name in chain ( outbound_edges , inbound_edges ) : edge_endpoint_type_name = None subclasses = schema_graph . get_subclass_set ( to_type_name ) to_type_abstract = schema_graph . get_element_by_class_name ( to_type_name ) . abstract if not to_type_abstract and len ( subclasses ) > 1 : type_names_to_union = [ subclass for subclass in subclasses if subclass not in hidden_classes ] if type_names_to_union : edge_endpoint_type_name = _get_union_type_name ( type_names_to_union ) else : if to_type_name not in hidden_classes : edge_endpoint_type_name = to_type_name if edge_endpoint_type_name is not None : result [ field_name ] = GraphQLList ( graphql_types [ edge_endpoint_type_name ] ) for field_name , field_type in six . iteritems ( field_type_overrides ) : if field_name not in result : raise AssertionError ( u'Attempting to override field "{}" from class "{}", but the ' u'class does not contain said field' . format ( field_name , cls_name ) ) else : result [ field_name ] = field_type return result | Return a dict from field name to GraphQL field type for the specified graph class . |
38,908 | def _create_field_specification ( schema_graph , graphql_types , field_type_overrides , hidden_classes , cls_name ) : def field_maker_func ( ) : result = EXTENDED_META_FIELD_DEFINITIONS . copy ( ) result . update ( OrderedDict ( [ ( name , GraphQLField ( value ) ) for name , value in sorted ( six . iteritems ( _get_fields_for_class ( schema_graph , graphql_types , field_type_overrides , hidden_classes , cls_name ) ) , key = lambda x : x [ 0 ] ) ] ) ) return result return field_maker_func | Return a function that specifies the fields present on the given type . |
38,909 | def _create_interface_specification ( schema_graph , graphql_types , hidden_classes , cls_name ) : def interface_spec ( ) : abstract_inheritance_set = ( superclass_name for superclass_name in sorted ( list ( schema_graph . get_inheritance_set ( cls_name ) ) ) if ( superclass_name not in hidden_classes and schema_graph . get_element_by_class_name ( superclass_name ) . abstract ) ) return [ graphql_types [ x ] for x in abstract_inheritance_set if x not in hidden_classes ] return interface_spec | Return a function that specifies the interfaces implemented by the given type . |
38,910 | def _create_union_types_specification ( schema_graph , graphql_types , hidden_classes , base_name ) : def types_spec ( ) : return [ graphql_types [ x ] for x in sorted ( list ( schema_graph . get_subclass_set ( base_name ) ) ) if x not in hidden_classes ] return types_spec | Return a function that gives the types in the union type rooted at base_name . |
38,911 | def get_graphql_schema_from_schema_graph ( schema_graph , class_to_field_type_overrides , hidden_classes ) : _validate_overriden_fields_are_not_defined_in_superclasses ( class_to_field_type_overrides , schema_graph ) inherited_field_type_overrides = _get_inherited_field_types ( class_to_field_type_overrides , schema_graph ) if not schema_graph . get_element_by_class_name ( ORIENTDB_BASE_VERTEX_CLASS_NAME ) . properties : hidden_classes . add ( ORIENTDB_BASE_VERTEX_CLASS_NAME ) graphql_types = OrderedDict ( ) type_equivalence_hints = OrderedDict ( ) for vertex_cls_name in sorted ( schema_graph . vertex_class_names ) : vertex_cls = schema_graph . get_element_by_class_name ( vertex_cls_name ) if vertex_cls_name in hidden_classes : continue inherited_field_type_overrides . setdefault ( vertex_cls_name , dict ( ) ) field_type_overrides = inherited_field_type_overrides [ vertex_cls_name ] field_specification_lambda = _create_field_specification ( schema_graph , graphql_types , field_type_overrides , hidden_classes , vertex_cls_name ) current_graphql_type = None if vertex_cls . abstract : current_graphql_type = GraphQLInterfaceType ( vertex_cls_name , fields = field_specification_lambda ) else : interface_specification_lambda = _create_interface_specification ( schema_graph , graphql_types , hidden_classes , vertex_cls_name ) current_graphql_type = GraphQLObjectType ( vertex_cls_name , field_specification_lambda , interfaces = interface_specification_lambda , is_type_of = lambda : None ) graphql_types [ vertex_cls_name ] = current_graphql_type for vertex_cls_name in sorted ( schema_graph . vertex_class_names ) : vertex_cls = schema_graph . get_element_by_class_name ( vertex_cls_name ) if vertex_cls_name in hidden_classes : continue vertex_cls_subclasses = schema_graph . get_subclass_set ( vertex_cls_name ) if not vertex_cls . abstract and len ( vertex_cls_subclasses ) > 1 : union_type_name = _get_union_type_name ( vertex_cls_subclasses ) type_specification_lambda = _create_union_types_specification ( schema_graph , graphql_types , hidden_classes , vertex_cls_name ) union_type = GraphQLUnionType ( union_type_name , types = type_specification_lambda ) graphql_types [ union_type_name ] = union_type type_equivalence_hints [ graphql_types [ vertex_cls_name ] ] = union_type for non_graph_cls_name in sorted ( schema_graph . non_graph_class_names ) : if non_graph_cls_name in hidden_classes : continue if not schema_graph . get_element_by_class_name ( non_graph_cls_name ) . abstract : continue cls_subclasses = schema_graph . get_subclass_set ( non_graph_cls_name ) if len ( cls_subclasses ) > 1 : all_non_abstract_subclasses_are_vertices = True for subclass_name in cls_subclasses : subclass = schema_graph . get_element_by_class_name ( subclass_name ) if subclass_name != non_graph_cls_name : if not subclass . abstract and not subclass . is_vertex : all_non_abstract_subclasses_are_vertices = False break if all_non_abstract_subclasses_are_vertices : inherited_field_type_overrides . setdefault ( non_graph_cls_name , dict ( ) ) field_type_overrides = inherited_field_type_overrides [ non_graph_cls_name ] field_specification_lambda = _create_field_specification ( schema_graph , graphql_types , field_type_overrides , hidden_classes , non_graph_cls_name ) graphql_type = GraphQLInterfaceType ( non_graph_cls_name , fields = field_specification_lambda ) graphql_types [ non_graph_cls_name ] = graphql_type if not graphql_types : raise EmptySchemaError ( u'After evaluating all subclasses of V, we were not able to find ' u'visible schema data to import into the GraphQL schema object' ) RootSchemaQuery = GraphQLObjectType ( 'RootSchemaQuery' , OrderedDict ( [ ( name , GraphQLField ( value ) ) for name , value in sorted ( six . iteritems ( graphql_types ) , key = lambda x : x [ 0 ] ) if not isinstance ( value , GraphQLUnionType ) ] ) ) schema = GraphQLSchema ( RootSchemaQuery , directives = DIRECTIVES ) return schema , _get_referenced_type_equivalences ( graphql_types , type_equivalence_hints ) | Return a GraphQL schema object corresponding to the schema of the given schema graph . |
38,912 | def workaround_lowering_pass ( ir_blocks , query_metadata_table ) : new_ir_blocks = [ ] for block in ir_blocks : if isinstance ( block , Filter ) : new_block = _process_filter_block ( query_metadata_table , block ) else : new_block = block new_ir_blocks . append ( new_block ) return new_ir_blocks | Extract locations from TernaryConditionals and rewrite their Filter blocks as necessary . |
38,913 | def _process_filter_block ( query_metadata_table , block ) : base_predicate = block . predicate ternary_conditionals = [ ] problematic_locations = [ ] def find_ternary_conditionals ( expression ) : if isinstance ( expression , TernaryConditional ) : ternary_conditionals . append ( expression ) return expression def extract_locations_visitor ( expression ) : if isinstance ( expression , ( ContextField , ContextFieldExistence ) ) : location_at_vertex = expression . location . at_vertex ( ) if location_at_vertex not in problematic_locations : problematic_locations . append ( location_at_vertex ) return expression return_value = base_predicate . visit_and_update ( find_ternary_conditionals ) if return_value is not base_predicate : raise AssertionError ( u'Read-only visitor function "find_ternary_conditionals" ' u'caused state to change: ' u'{} {}' . format ( base_predicate , return_value ) ) for ternary in ternary_conditionals : return_value = ternary . visit_and_update ( extract_locations_visitor ) if return_value is not ternary : raise AssertionError ( u'Read-only visitor function "extract_locations_visitor" ' u'caused state to change: ' u'{} {}' . format ( ternary , return_value ) ) tautologies = [ _create_tautological_expression_for_location ( query_metadata_table , location ) for location in problematic_locations ] if not tautologies : return block final_predicate = base_predicate for tautology in tautologies : final_predicate = BinaryComposition ( u'&&' , final_predicate , tautology ) return Filter ( final_predicate ) | Rewrite the provided Filter block if necessary . |
38,914 | def _create_tautological_expression_for_location ( query_metadata_table , location ) : location_type = query_metadata_table . get_location_info ( location ) . type location_exists = BinaryComposition ( u'!=' , ContextField ( location , location_type ) , NullLiteral ) location_does_not_exist = BinaryComposition ( u'=' , ContextField ( location , location_type ) , NullLiteral ) return BinaryComposition ( u'||' , location_exists , location_does_not_exist ) | For a given location create a BinaryComposition that always evaluates to true . |
38,915 | def get_only_element_from_collection ( one_element_collection ) : if len ( one_element_collection ) != 1 : raise AssertionError ( u'Expected a collection with exactly one element, but got: {}' . format ( one_element_collection ) ) return funcy . first ( one_element_collection ) | Assert that the collection has exactly one element then return that element . |
38,916 | def get_ast_field_name ( ast ) : replacements = { TYPENAME_META_FIELD_NAME : '@class' } base_field_name = ast . name . value normalized_name = replacements . get ( base_field_name , base_field_name ) return normalized_name | Return the normalized field name for the given AST node . |
38,917 | def get_field_type_from_schema ( schema_type , field_name ) : if field_name == '@class' : return GraphQLString else : if field_name not in schema_type . fields : raise AssertionError ( u'Field {} passed validation but was not present on type ' u'{}' . format ( field_name , schema_type ) ) return schema_type . fields [ field_name ] . type | Return the type of the field in the given type accounting for field name normalization . |
38,918 | def get_vertex_field_type ( current_schema_type , vertex_field_name ) : if not is_vertex_field_name ( vertex_field_name ) : raise AssertionError ( u'Trying to load the vertex field type of a non-vertex field: ' u'{} {}' . format ( current_schema_type , vertex_field_name ) ) raw_field_type = get_field_type_from_schema ( current_schema_type , vertex_field_name ) if not isinstance ( strip_non_null_from_type ( raw_field_type ) , GraphQLList ) : raise AssertionError ( u'Found an edge whose schema type was not GraphQLList: ' u'{} {} {}' . format ( current_schema_type , vertex_field_name , raw_field_type ) ) return raw_field_type . of_type | Return the type of the vertex within the specified vertex field name of the given type . |
38,919 | def get_edge_direction_and_name ( vertex_field_name ) : edge_direction = None edge_name = None if vertex_field_name . startswith ( OUTBOUND_EDGE_FIELD_PREFIX ) : edge_direction = OUTBOUND_EDGE_DIRECTION edge_name = vertex_field_name [ len ( OUTBOUND_EDGE_FIELD_PREFIX ) : ] elif vertex_field_name . startswith ( INBOUND_EDGE_FIELD_PREFIX ) : edge_direction = INBOUND_EDGE_DIRECTION edge_name = vertex_field_name [ len ( INBOUND_EDGE_FIELD_PREFIX ) : ] else : raise AssertionError ( u'Unreachable condition reached:' , vertex_field_name ) validate_safe_string ( edge_name ) return edge_direction , edge_name | Get the edge direction and name from a non - root vertex field name . |
38,920 | def is_vertex_field_type ( graphql_type ) : underlying_type = strip_non_null_from_type ( graphql_type ) return isinstance ( underlying_type , ( GraphQLInterfaceType , GraphQLObjectType , GraphQLUnionType ) ) | Return True if the argument is a vertex field type and False otherwise . |
38,921 | def ensure_unicode_string ( value ) : if not isinstance ( value , six . string_types ) : raise TypeError ( u'Expected string value, got: {}' . format ( value ) ) return six . text_type ( value ) | Ensure the value is a string and return it as unicode . |
38,922 | def get_uniquely_named_objects_by_name ( object_list ) : if not object_list : return dict ( ) result = dict ( ) for obj in object_list : name = obj . name . value if name in result : raise GraphQLCompilationError ( u'Found duplicate object key: ' u'{} {}' . format ( name , object_list ) ) result [ name ] = obj return result | Return dict of name - > object pairs from a list of objects with unique names . |
38,923 | def validate_safe_string ( value ) : legal_strings_with_special_chars = frozenset ( { '@rid' , '@class' , '@this' , '%' } ) if not isinstance ( value , six . string_types ) : raise TypeError ( u'Expected string value, got: {} {}' . format ( type ( value ) . __name__ , value ) ) if not value : raise GraphQLCompilationError ( u'Empty strings are not allowed!' ) if value [ 0 ] in string . digits : raise GraphQLCompilationError ( u'String values cannot start with a digit: {}' . format ( value ) ) if not set ( value ) . issubset ( VARIABLE_ALLOWED_CHARS ) and value not in legal_strings_with_special_chars : raise GraphQLCompilationError ( u'Encountered illegal characters in string: {}' . format ( value ) ) | Ensure the provided string does not have illegal characters . |
38,924 | def validate_edge_direction ( edge_direction ) : if not isinstance ( edge_direction , six . string_types ) : raise TypeError ( u'Expected string edge_direction, got: {} {}' . format ( type ( edge_direction ) , edge_direction ) ) if edge_direction not in ALLOWED_EDGE_DIRECTIONS : raise ValueError ( u'Unrecognized edge direction: {}' . format ( edge_direction ) ) | Ensure the provided edge direction is either in or out . |
38,925 | def validate_marked_location ( location ) : if not isinstance ( location , ( Location , FoldScopeLocation ) ) : raise TypeError ( u'Expected Location or FoldScopeLocation location, got: {} {}' . format ( type ( location ) . __name__ , location ) ) if location . field is not None : raise GraphQLCompilationError ( u'Cannot mark location at a field: {}' . format ( location ) ) | Validate that a Location object is safe for marking and not at a field . |
38,926 | def invert_dict ( invertible_dict ) : inverted = { } for k , v in six . iteritems ( invertible_dict ) : if not isinstance ( v , Hashable ) : raise TypeError ( u'Expected an invertible dict, but value at key {} has type {}' . format ( k , type ( v ) . __name__ ) ) if v in inverted : raise TypeError ( u'Expected an invertible dict, but keys ' u'{} and {} map to the same value' . format ( inverted [ v ] , k ) ) inverted [ v ] = k return inverted | Invert a dict . A dict is invertible if values are unique and hashable . |
38,927 | def read_file ( filename ) : here = os . path . abspath ( os . path . dirname ( __file__ ) ) with codecs . open ( os . path . join ( here , 'graphql_compiler' , filename ) , 'r' ) as f : return f . read ( ) | Read package file as text to get name and version |
38,928 | def find_version ( ) : version_file = read_file ( '__init__.py' ) version_match = re . search ( r'^__version__ = ["\']([^"\']*)["\']' , version_file , re . M ) if version_match : return version_match . group ( 1 ) raise RuntimeError ( 'Unable to find version string.' ) | Only define version in one place |
38,929 | def find_name ( ) : name_file = read_file ( '__init__.py' ) name_match = re . search ( r'^__package_name__ = ["\']([^"\']*)["\']' , name_file , re . M ) if name_match : return name_match . group ( 1 ) raise RuntimeError ( 'Unable to find name string.' ) | Only define name in one place |
38,930 | def workaround_type_coercions_in_recursions ( match_query ) : new_match_traversals = [ ] for current_traversal in match_query . match_traversals : new_traversal = [ ] for match_step in current_traversal : new_match_step = match_step has_coerce_type = match_step . coerce_type_block is not None has_recurse_root = isinstance ( match_step . root_block , Recurse ) if has_coerce_type and has_recurse_root : new_where_block = convert_coerce_type_and_add_to_where_block ( match_step . coerce_type_block , match_step . where_block ) new_match_step = match_step . _replace ( coerce_type_block = None , where_block = new_where_block ) new_traversal . append ( new_match_step ) new_match_traversals . append ( new_traversal ) return match_query . _replace ( match_traversals = new_match_traversals ) | Lower CoerceType blocks into Filter blocks within Recurse steps . |
38,931 | def main ( ) : query = ' ' . join ( sys . stdin . readlines ( ) ) sys . stdout . write ( pretty_print_graphql ( query ) ) | Read a GraphQL query from standard input and output it pretty - printed to standard output . |
38,932 | def _safe_gremlin_string ( value ) : if not isinstance ( value , six . string_types ) : if isinstance ( value , bytes ) : value = value . decode ( 'utf-8' ) else : raise GraphQLInvalidArgumentError ( u'Attempting to convert a non-string into a string: ' u'{}' . format ( value ) ) escaped_and_quoted = json . dumps ( value ) if not escaped_and_quoted [ 0 ] == escaped_and_quoted [ - 1 ] == '"' : raise AssertionError ( u'Unreachable state reached: {} {}' . format ( value , escaped_and_quoted ) ) no_quotes = escaped_and_quoted [ 1 : - 1 ] re_escaped = no_quotes . replace ( '\\"' , '"' ) . replace ( '\'' , '\\\'' ) final_escaped_value = '\'' + re_escaped + '\'' return final_escaped_value | Sanitize and represent a string argument in Gremlin . |
38,933 | def _safe_gremlin_list ( inner_type , argument_value ) : if not isinstance ( argument_value , list ) : raise GraphQLInvalidArgumentError ( u'Attempting to represent a non-list as a list: ' u'{}' . format ( argument_value ) ) stripped_type = strip_non_null_from_type ( inner_type ) components = ( _safe_gremlin_argument ( stripped_type , x ) for x in argument_value ) return u'[' + u',' . join ( components ) + u']' | Represent the list of inner_type objects in Gremlin form . |
38,934 | def _safe_gremlin_argument ( expected_type , argument_value ) : if GraphQLString . is_same_type ( expected_type ) : return _safe_gremlin_string ( argument_value ) elif GraphQLID . is_same_type ( expected_type ) : if not isinstance ( argument_value , six . string_types ) : if isinstance ( argument_value , bytes ) : argument_value = argument_value . decode ( 'utf-8' ) else : argument_value = six . text_type ( argument_value ) return _safe_gremlin_string ( argument_value ) elif GraphQLFloat . is_same_type ( expected_type ) : return represent_float_as_str ( argument_value ) elif GraphQLInt . is_same_type ( expected_type ) : if isinstance ( argument_value , bool ) : raise GraphQLInvalidArgumentError ( u'Attempting to represent a non-int as an int: ' u'{}' . format ( argument_value ) ) return type_check_and_str ( int , argument_value ) elif GraphQLBoolean . is_same_type ( expected_type ) : return type_check_and_str ( bool , argument_value ) elif GraphQLDecimal . is_same_type ( expected_type ) : return _safe_gremlin_decimal ( argument_value ) elif GraphQLDate . is_same_type ( expected_type ) : return _safe_gremlin_date_and_datetime ( expected_type , ( datetime . date , ) , argument_value ) elif GraphQLDateTime . is_same_type ( expected_type ) : return _safe_gremlin_date_and_datetime ( expected_type , ( datetime . datetime , arrow . Arrow ) , argument_value ) elif isinstance ( expected_type , GraphQLList ) : return _safe_gremlin_list ( expected_type . of_type , argument_value ) else : raise AssertionError ( u'Could not safely represent the requested GraphQL type: ' u'{} {}' . format ( expected_type , argument_value ) ) | Return a Gremlin string representing the given argument value . |
38,935 | def insert_arguments_into_gremlin_query ( compilation_result , arguments ) : if compilation_result . language != GREMLIN_LANGUAGE : raise AssertionError ( u'Unexpected query output language: {}' . format ( compilation_result ) ) base_query = compilation_result . query argument_types = compilation_result . input_metadata sanitized_arguments = { key : _safe_gremlin_argument ( argument_types [ key ] , value ) for key , value in six . iteritems ( arguments ) } return Template ( base_query ) . substitute ( sanitized_arguments ) | Insert the arguments into the compiled Gremlin query to form a complete query . |
38,936 | def _get_vertex_location_name ( location ) : mark_name , field_name = location . get_location_name ( ) if field_name is not None : raise AssertionError ( u'Location unexpectedly pointed to a field: {}' . format ( location ) ) return mark_name | Get the location name from a location that is expected to point to a vertex . |
38,937 | def _first_step_to_match ( match_step ) : parts = [ ] if match_step . root_block is not None : if not isinstance ( match_step . root_block , QueryRoot ) : raise AssertionError ( u'Expected None or QueryRoot root block, received: ' u'{} {}' . format ( match_step . root_block , match_step ) ) match_step . root_block . validate ( ) start_class = get_only_element_from_collection ( match_step . root_block . start_class ) parts . append ( u'class: %s' % ( start_class , ) ) if match_step . coerce_type_block is not None : raise AssertionError ( u'Invalid MATCH step: {}' . format ( match_step ) ) if match_step . where_block : match_step . where_block . validate ( ) parts . append ( u'where: (%s)' % ( match_step . where_block . predicate . to_match ( ) , ) ) if match_step . as_block is None : raise AssertionError ( u'Found a MATCH step without a corresponding Location. ' u'This should never happen: {}' . format ( match_step ) ) else : match_step . as_block . validate ( ) parts . append ( u'as: %s' % ( _get_vertex_location_name ( match_step . as_block . location ) , ) ) return u'{{ %s }}' % ( u', ' . join ( parts ) , ) | Transform the very first MATCH step into a MATCH query string . |
38,938 | def _represent_match_traversal ( match_traversal ) : output = [ ] output . append ( _first_step_to_match ( match_traversal [ 0 ] ) ) for step in match_traversal [ 1 : ] : output . append ( _subsequent_step_to_match ( step ) ) return u'' . join ( output ) | Emit MATCH query code for an entire MATCH traversal sequence . |
38,939 | def _represent_fold ( fold_location , fold_ir_blocks ) : start_let_template = u'$%(mark_name)s = %(base_location)s' traverse_edge_template = u'.%(direction)s("%(edge_name)s")' base_template = start_let_template + traverse_edge_template edge_direction , edge_name = fold_location . get_first_folded_edge ( ) mark_name , _ = fold_location . get_location_name ( ) base_location_name , _ = fold_location . base_location . get_location_name ( ) validate_safe_string ( mark_name ) validate_safe_string ( base_location_name ) validate_safe_string ( edge_direction ) validate_safe_string ( edge_name ) template_data = { 'mark_name' : mark_name , 'base_location' : base_location_name , 'direction' : edge_direction , 'edge_name' : edge_name , } final_string = base_template % template_data for block in fold_ir_blocks : if isinstance ( block , Filter ) : final_string += u'[' + block . predicate . to_match ( ) + u']' elif isinstance ( block , Traverse ) : template_data = { 'direction' : block . direction , 'edge_name' : block . edge_name , } final_string += traverse_edge_template % template_data elif isinstance ( block , MarkLocation ) : pass else : raise AssertionError ( u'Found an unexpected IR block in the folded IR blocks: ' u'{} {} {}' . format ( type ( block ) , block , fold_ir_blocks ) ) final_string += '.asList()' return final_string | Emit a LET clause corresponding to the IR blocks for a |
38,940 | def _construct_output_to_match ( output_block ) : output_block . validate ( ) selections = ( u'%s AS `%s`' % ( output_block . fields [ key ] . to_match ( ) , key ) for key in sorted ( output_block . fields . keys ( ) ) ) return u'SELECT %s FROM' % ( u', ' . join ( selections ) , ) | Transform a ConstructResult block into a MATCH query string . |
38,941 | def _construct_where_to_match ( where_block ) : if where_block . predicate == TrueLiteral : raise AssertionError ( u'Received WHERE block with TrueLiteral predicate: {}' . format ( where_block ) ) return u'WHERE ' + where_block . predicate . to_match ( ) | Transform a Filter block into a MATCH query string . |
38,942 | def emit_code_from_multiple_match_queries ( match_queries ) : optional_variable_base_name = '$optional__' union_variable_name = '$result' query_data = deque ( [ u'SELECT EXPAND(' , union_variable_name , u')' , u' LET ' ] ) optional_variables = [ ] sub_queries = [ emit_code_from_single_match_query ( match_query ) for match_query in match_queries ] for ( i , sub_query ) in enumerate ( sub_queries ) : variable_name = optional_variable_base_name + str ( i ) variable_assignment = variable_name + u' = (' sub_query_end = u'),' query_data . append ( variable_assignment ) query_data . append ( sub_query ) query_data . append ( sub_query_end ) optional_variables . append ( variable_name ) query_data . append ( union_variable_name ) query_data . append ( u' = UNIONALL(' ) query_data . append ( u', ' . join ( optional_variables ) ) query_data . append ( u')' ) return u' ' . join ( query_data ) | Return a MATCH query string from a list of MatchQuery namedtuples . |
38,943 | def emit_code_from_ir ( compound_match_query , compiler_metadata ) : match_queries = compound_match_query . match_queries if len ( match_queries ) == 1 : query_string = emit_code_from_single_match_query ( match_queries [ 0 ] ) elif len ( match_queries ) > 1 : query_string = emit_code_from_multiple_match_queries ( match_queries ) else : raise AssertionError ( u'Received CompoundMatchQuery with an empty list of MatchQueries: ' u'{}' . format ( match_queries ) ) return query_string | Return a MATCH query string from a CompoundMatchQuery . |
38,944 | def _serialize_date ( value ) : if not isinstance ( value , date ) : raise ValueError ( u'The received object was not a date: ' u'{} {}' . format ( type ( value ) , value ) ) return value . isoformat ( ) | Serialize a Date object to its proper ISO - 8601 representation . |
38,945 | def _serialize_datetime ( value ) : if not isinstance ( value , ( datetime , arrow . Arrow ) ) : raise ValueError ( u'The received object was not a datetime: ' u'{} {}' . format ( type ( value ) , value ) ) return value . isoformat ( ) | Serialize a DateTime object to its proper ISO - 8601 representation . |
38,946 | def _parse_datetime_value ( value ) : if value . endswith ( 'Z' ) : value = value [ : - 1 ] + '+00:00' return arrow . get ( value , 'YYYY-MM-DDTHH:mm:ssZ' ) . datetime | Deserialize a DateTime object from its proper ISO - 8601 representation . |
38,947 | def insert_meta_fields_into_existing_schema ( graphql_schema ) : root_type_name = graphql_schema . get_query_type ( ) . name for type_name , type_obj in six . iteritems ( graphql_schema . get_type_map ( ) ) : if type_name . startswith ( '__' ) or type_name == root_type_name : continue if not isinstance ( type_obj , ( GraphQLObjectType , GraphQLInterfaceType ) ) : continue for meta_field_name , meta_field in six . iteritems ( EXTENDED_META_FIELD_DEFINITIONS ) : if meta_field_name in type_obj . fields : raise AssertionError ( u'Unexpectedly encountered an existing field named {} while ' u'attempting to add a meta-field of the same name. Make sure ' u'you are not attempting to add meta-fields twice.' . format ( meta_field_name ) ) type_obj . fields [ meta_field_name ] = meta_field | Add compiler - specific meta - fields into all interfaces and types of the specified schema . |
38,948 | def validate_context_for_visiting_vertex_field ( parent_location , vertex_field_name , context ) : if is_in_fold_innermost_scope ( context ) : raise GraphQLCompilationError ( u'Traversing inside a @fold block after filtering on {} or outputting fields ' u'is not supported! Parent location: {}, vertex field name: {}' . format ( COUNT_META_FIELD_NAME , parent_location , vertex_field_name ) ) | Ensure that the current context allows for visiting a vertex field . |
38,949 | def pretty_print_graphql ( query , use_four_spaces = True ) : output = visit ( parse ( query ) , CustomPrintingVisitor ( ) ) if use_four_spaces : return fix_indentation_depth ( output ) return output | Take a GraphQL query pretty print it and return it . |
38,950 | def fix_indentation_depth ( query ) : lines = query . split ( '\n' ) final_lines = [ ] for line in lines : consecutive_spaces = 0 for char in line : if char == ' ' : consecutive_spaces += 1 else : break if consecutive_spaces % 2 != 0 : raise AssertionError ( u'Indentation was not a multiple of two: ' u'{}' . format ( consecutive_spaces ) ) final_lines . append ( ( ' ' * consecutive_spaces ) + line [ consecutive_spaces : ] ) return '\n' . join ( final_lines ) | Make indentation use 4 spaces rather than the 2 spaces GraphQL normally uses . |
38,951 | def leave_Directive ( self , node , * args ) : name_to_arg_value = { arg . split ( ':' , 1 ) [ 0 ] : arg for arg in node . arguments } ordered_args = node . arguments directive = DIRECTIVES_BY_NAME . get ( node . name ) if directive : sorted_args = [ ] encountered_argument_names = set ( ) for defined_arg_name in six . iterkeys ( directive . args ) : if defined_arg_name in name_to_arg_value : encountered_argument_names . add ( defined_arg_name ) sorted_args . append ( name_to_arg_value [ defined_arg_name ] ) unsorted_args = [ value for name , value in six . iteritems ( name_to_arg_value ) if name not in encountered_argument_names ] ordered_args = sorted_args + unsorted_args return '@' + node . name + wrap ( '(' , join ( ordered_args , ', ' ) , ')' ) | Call when exiting a directive node in the ast . |
38,952 | def lower_ir ( ir_blocks , query_metadata_table , type_equivalence_hints = None ) : sanity_check_ir_blocks_from_frontend ( ir_blocks , query_metadata_table ) location_types = { location : location_info . type for location , location_info in query_metadata_table . registered_locations } coerced_locations = { location for location , location_info in query_metadata_table . registered_locations if location_info . coerced_from_type is not None } location_to_optional_results = extract_optional_location_root_info ( ir_blocks ) complex_optional_roots , location_to_optional_roots = location_to_optional_results simple_optional_root_info = extract_simple_optional_location_info ( ir_blocks , complex_optional_roots , location_to_optional_roots ) ir_blocks = remove_end_optionals ( ir_blocks ) if len ( simple_optional_root_info ) > 0 : where_filter_predicate = construct_where_filter_predicate ( query_metadata_table , simple_optional_root_info ) ir_blocks . insert ( - 1 , GlobalOperationsStart ( ) ) ir_blocks . insert ( - 1 , Filter ( where_filter_predicate ) ) ir_blocks = lower_context_field_existence ( ir_blocks , query_metadata_table ) ir_blocks = optimize_boolean_expression_comparisons ( ir_blocks ) ir_blocks = rewrite_binary_composition_inside_ternary_conditional ( ir_blocks ) ir_blocks = merge_consecutive_filter_clauses ( ir_blocks ) ir_blocks = lower_has_substring_binary_compositions ( ir_blocks ) ir_blocks = orientdb_eval_scheduling . workaround_lowering_pass ( ir_blocks , query_metadata_table ) match_query = convert_to_match_query ( ir_blocks ) match_query = lower_comparisons_to_between ( match_query ) match_query = lower_backtrack_blocks ( match_query , location_types ) match_query = truncate_repeated_single_step_traversals ( match_query ) match_query = orientdb_class_with_while . workaround_type_coercions_in_recursions ( match_query ) new_folds = { key : merge_consecutive_filter_clauses ( remove_backtrack_blocks_from_fold ( lower_folded_coerce_types_into_filter_blocks ( folded_ir_blocks ) ) ) for key , folded_ir_blocks in six . iteritems ( match_query . folds ) } match_query = match_query . _replace ( folds = new_folds ) compound_match_query = convert_optional_traversals_to_compound_match_query ( match_query , complex_optional_roots , location_to_optional_roots ) compound_match_query = prune_non_existent_outputs ( compound_match_query ) compound_match_query = collect_filters_to_first_location_occurrence ( compound_match_query ) compound_match_query = lower_context_field_expressions ( compound_match_query ) compound_match_query = truncate_repeated_single_step_traversals_in_sub_queries ( compound_match_query ) compound_match_query = orientdb_query_execution . expose_ideal_query_execution_start_points ( compound_match_query , location_types , coerced_locations ) return compound_match_query | Lower the IR into an IR form that can be represented in MATCH queries . |
38,953 | def toposort_classes ( classes ) : def get_class_topolist ( class_name , name_to_class , processed_classes , current_trace ) : if class_name in processed_classes : return [ ] if class_name in current_trace : raise AssertionError ( 'Encountered self-reference in dependency chain of {}' . format ( class_name ) ) cls = name_to_class [ class_name ] dependencies = _list_superclasses ( cls ) properties = cls [ 'properties' ] if 'properties' in cls else [ ] for prop in properties : if 'linkedClass' in prop : dependencies . append ( prop [ 'linkedClass' ] ) class_list = [ ] current_trace . add ( class_name ) for dependency in dependencies : class_list . extend ( get_class_topolist ( dependency , name_to_class , processed_classes , current_trace ) ) current_trace . remove ( class_name ) class_list . append ( name_to_class [ class_name ] ) processed_classes . add ( class_name ) return class_list class_map = { c [ 'name' ] : c for c in classes } seen_classes = set ( ) toposorted = [ ] for name in class_map . keys ( ) : toposorted . extend ( get_class_topolist ( name , class_map , seen_classes , set ( ) ) ) return toposorted | Sort class metadatas so that a superclass is always before the subclass |
38,954 | def _list_superclasses ( class_def ) : superclasses = class_def . get ( 'superClasses' , [ ] ) if superclasses : return list ( superclasses ) sup = class_def . get ( 'superClass' , None ) if sup : return [ sup ] else : return [ ] | Return a list of the superclasses of the given class |
38,955 | def _construct_location_stack_entry ( location , num_traverses ) : if not isinstance ( num_traverses , int ) or num_traverses < 0 : raise AssertionError ( u'Attempted to create a LocationStackEntry namedtuple with an invalid ' u'value for "num_traverses" {}. This is not allowed.' . format ( num_traverses ) ) if not isinstance ( location , Location ) : raise AssertionError ( u'Attempted to create a LocationStackEntry namedtuple with an invalid ' u'value for "location" {}. This is not allowed.' . format ( location ) ) return LocationStackEntry ( location = location , num_traverses = num_traverses ) | Return a LocationStackEntry namedtuple with the specified parameters . |
38,956 | def _get_fields ( ast ) : if not ast . selection_set : return [ ] , [ ] property_fields = [ ] vertex_fields = [ ] seen_field_names = set ( ) switched_to_vertices = False for field_ast in ast . selection_set . selections : if not isinstance ( field_ast , Field ) : continue name = get_ast_field_name ( field_ast ) if name in seen_field_names : raise GraphQLCompilationError ( u'Encountered repeated field name: {}' . format ( name ) ) seen_field_names . add ( name ) if is_vertex_field_name ( name ) : switched_to_vertices = True vertex_fields . append ( field_ast ) else : if switched_to_vertices : raise GraphQLCompilationError ( u'Encountered property field {} ' u'after vertex fields!' . format ( name ) ) property_fields . append ( field_ast ) return vertex_fields , property_fields | Return a list of vertex fields and a list of property fields for the given AST node . |
38,957 | def _get_inline_fragment ( ast ) : if not ast . selection_set : return None fragments = [ ast_node for ast_node in ast . selection_set . selections if isinstance ( ast_node , InlineFragment ) ] if not fragments : return None if len ( fragments ) > 1 : raise GraphQLCompilationError ( u'Cannot compile GraphQL with more than one fragment in ' u'a given selection set.' ) return fragments [ 0 ] | Return the inline fragment at the current AST node or None if no fragment exists . |
38,958 | def _process_output_source_directive ( schema , current_schema_type , ast , location , context , local_unique_directives ) : output_source_directive = local_unique_directives . get ( 'output_source' , None ) if output_source_directive : if has_encountered_output_source ( context ) : raise GraphQLCompilationError ( u'Cannot have more than one output source!' ) if is_in_optional_scope ( context ) : raise GraphQLCompilationError ( u'Cannot have the output source in an optional block!' ) set_output_source_data ( context , location ) return blocks . OutputSource ( ) else : return None | Process the output_source directive modifying the context as appropriate . |
38,959 | def _compile_property_ast ( schema , current_schema_type , ast , location , context , unique_local_directives ) : validate_property_directives ( unique_local_directives ) if location . field == COUNT_META_FIELD_NAME : if not is_in_fold_scope ( context ) : raise GraphQLCompilationError ( u'Cannot use the "{}" meta field when not within a @fold ' u'vertex field, as counting elements only makes sense ' u'in a fold. Location: {}' . format ( COUNT_META_FIELD_NAME , location ) ) tag_directive = unique_local_directives . get ( 'tag' , None ) if tag_directive : if is_in_fold_scope ( context ) : raise GraphQLCompilationError ( u'Tagging values within a @fold vertex field is ' u'not allowed! Location: {}' . format ( location ) ) if location . field == COUNT_META_FIELD_NAME : raise AssertionError ( u'Tags are prohibited within @fold, but unexpectedly found use of ' u'a tag on the {} meta field that is only allowed within a @fold!' u'Location: {}' . format ( COUNT_META_FIELD_NAME , location ) ) tag_name = tag_directive . arguments [ 0 ] . value . value if tag_name in context [ 'tags' ] : raise GraphQLCompilationError ( u'Cannot reuse tag name: {}' . format ( tag_name ) ) validate_safe_string ( tag_name ) context [ 'tags' ] [ tag_name ] = { 'location' : location , 'optional' : is_in_optional_scope ( context ) , 'type' : strip_non_null_from_type ( current_schema_type ) , } context [ 'metadata' ] . record_tag_info ( tag_name , TagInfo ( location = location ) ) output_directive = unique_local_directives . get ( 'output' , None ) if output_directive : output_name = output_directive . arguments [ 0 ] . value . value if output_name in context [ 'outputs' ] : raise GraphQLCompilationError ( u'Cannot reuse output name: ' u'{}, {}' . format ( output_name , context ) ) validate_safe_string ( output_name ) validate_output_name ( output_name ) graphql_type = strip_non_null_from_type ( current_schema_type ) if is_in_fold_scope ( context ) : set_fold_innermost_scope ( context ) if location . field != COUNT_META_FIELD_NAME : graphql_type = GraphQLList ( graphql_type ) context [ 'outputs' ] [ output_name ] = { 'location' : location , 'optional' : is_in_optional_scope ( context ) , 'type' : graphql_type , 'fold' : context . get ( 'fold' , None ) , } | Process property directives at this AST node updating the query context as appropriate . |
38,960 | def _get_recurse_directive_depth ( field_name , field_directives ) : recurse_directive = field_directives [ 'recurse' ] optional_directive = field_directives . get ( 'optional' , None ) if optional_directive : raise GraphQLCompilationError ( u'Found both @optional and @recurse on ' u'the same vertex field: {}' . format ( field_name ) ) recurse_args = get_uniquely_named_objects_by_name ( recurse_directive . arguments ) recurse_depth = int ( recurse_args [ 'depth' ] . value . value ) if recurse_depth < 1 : raise GraphQLCompilationError ( u'Found recurse directive with disallowed depth: ' u'{}' . format ( recurse_depth ) ) return recurse_depth | Validate and return the depth parameter of the recurse directive . |
38,961 | def _validate_recurse_directive_types ( current_schema_type , field_schema_type , context ) : type_hints = context [ 'type_equivalence_hints' ] . get ( field_schema_type ) type_hints_inverse = context [ 'type_equivalence_hints_inverse' ] . get ( field_schema_type ) allowed_current_types = { field_schema_type } if type_hints and isinstance ( type_hints , GraphQLUnionType ) : allowed_current_types . update ( type_hints . types ) if type_hints_inverse and isinstance ( type_hints_inverse , GraphQLUnionType ) : allowed_current_types . update ( type_hints_inverse . types ) current_scope_is_allowed = current_schema_type in allowed_current_types is_implemented_interface = ( isinstance ( field_schema_type , GraphQLInterfaceType ) and isinstance ( current_schema_type , GraphQLObjectType ) and field_schema_type in current_schema_type . interfaces ) if not any ( ( current_scope_is_allowed , is_implemented_interface ) ) : raise GraphQLCompilationError ( u'Edges expanded with a @recurse directive must either ' u'be of the same type as their enclosing scope, a supertype ' u'of the enclosing scope, or be of an interface type that is ' u'implemented by the type of their enclosing scope. ' u'Enclosing scope type: {}, edge type: ' u'{}' . format ( current_schema_type , field_schema_type ) ) | Perform type checks on the enclosing type and the recursed type for a recurse directive . |
38,962 | def _compile_fragment_ast ( schema , current_schema_type , ast , location , context ) : query_metadata_table = context [ 'metadata' ] coerces_to_type_name = ast . type_condition . name . value coerces_to_type_obj = schema . get_type ( coerces_to_type_name ) basic_blocks = [ ] is_same_type_as_scope = current_schema_type . is_same_type ( coerces_to_type_obj ) equivalent_union_type = context [ 'type_equivalence_hints' ] . get ( coerces_to_type_obj , None ) is_base_type_of_union = ( isinstance ( current_schema_type , GraphQLUnionType ) and current_schema_type . is_same_type ( equivalent_union_type ) ) if not ( is_same_type_as_scope or is_base_type_of_union ) : query_metadata_table . record_coercion_at_location ( location , coerces_to_type_obj ) basic_blocks . append ( blocks . CoerceType ( { coerces_to_type_name } ) ) inner_basic_blocks = _compile_ast_node_to_ir ( schema , coerces_to_type_obj , ast , location , context ) basic_blocks . extend ( inner_basic_blocks ) return basic_blocks | Return a list of basic blocks corresponding to the inline fragment at this AST node . |
38,963 | def _compile_ast_node_to_ir ( schema , current_schema_type , ast , location , context ) : basic_blocks = [ ] local_unique_directives = get_unique_directives ( ast ) fields = _get_fields ( ast ) vertex_fields , property_fields = fields fragment = _get_inline_fragment ( ast ) filter_operations = get_local_filter_directives ( ast , current_schema_type , vertex_fields ) fragment_exists = fragment is not None fields_exist = vertex_fields or property_fields if fragment_exists and fields_exist : raise GraphQLCompilationError ( u'Cannot compile GraphQL that has inline fragment and ' u'selected fields in the same selection. Please move the ' u'selected fields inside the inline fragment.' ) if location . field is not None : if fragment_exists : raise AssertionError ( u'Found inline fragment at a property field: ' u'{} {}' . format ( location , fragment ) ) if len ( property_fields ) > 0 : raise AssertionError ( u'Found property fields on a property field: ' u'{} {}' . format ( location , property_fields ) ) for filter_operation_info in filter_operations : filter_block = process_filter_directive ( filter_operation_info , location , context ) if isinstance ( location , FoldScopeLocation ) and location . field == COUNT_META_FIELD_NAME : set_fold_innermost_scope ( context ) expected_field = expressions . LocalField ( COUNT_META_FIELD_NAME ) replacement_field = expressions . FoldedContextField ( location , GraphQLInt ) visitor_fn = expressions . make_replacement_visitor ( expected_field , replacement_field ) filter_block = filter_block . visit_and_update_expressions ( visitor_fn ) visitor_fn = expressions . make_type_replacement_visitor ( expressions . ContextField , lambda context_field : expressions . GlobalContextField ( context_field . location , context_field . field_type ) ) filter_block = filter_block . visit_and_update_expressions ( visitor_fn ) set_fold_count_filter ( context ) context [ 'global_filters' ] . append ( filter_block ) else : basic_blocks . append ( filter_block ) if location . field is not None : _compile_property_ast ( schema , current_schema_type , ast , location , context , local_unique_directives ) else : if fragment_exists : basic_blocks . extend ( _compile_fragment_ast ( schema , current_schema_type , fragment , location , context ) ) else : basic_blocks . extend ( _compile_vertex_ast ( schema , current_schema_type , ast , location , context , local_unique_directives , fields ) ) return basic_blocks | Compile the given GraphQL AST node into a list of basic blocks . |
38,964 | def _validate_all_tags_are_used ( metadata ) : tag_names = set ( [ tag_name for tag_name , _ in metadata . tags ] ) filter_arg_names = set ( ) for location , _ in metadata . registered_locations : for filter_info in metadata . get_filter_infos ( location ) : for filter_arg in filter_info . args : if is_tag_argument ( filter_arg ) : filter_arg_names . add ( get_directive_argument_name ( filter_arg ) ) unused_tags = tag_names - filter_arg_names if unused_tags : raise GraphQLCompilationError ( u'This GraphQL query contains @tag directives whose values ' u'are not used: {}. This is not allowed. Please either use ' u'them in a filter or remove them entirely.' . format ( unused_tags ) ) | Ensure all tags are used in some filter . |
38,965 | def _compile_output_step ( outputs ) : if not outputs : raise GraphQLCompilationError ( u'No fields were selected for output! Please mark at least ' u'one field with the @output directive.' ) output_fields = { } for output_name , output_context in six . iteritems ( outputs ) : location = output_context [ 'location' ] optional = output_context [ 'optional' ] graphql_type = output_context [ 'type' ] expression = None existence_check = None if isinstance ( location , FoldScopeLocation ) : if optional : raise AssertionError ( u'Unreachable state reached, optional in fold: ' u'{}' . format ( output_context ) ) if location . field == COUNT_META_FIELD_NAME : expression = expressions . FoldCountContextField ( location ) else : expression = expressions . FoldedContextField ( location , graphql_type ) else : expression = expressions . OutputContextField ( location , graphql_type ) if optional : existence_check = expressions . ContextFieldExistence ( location . at_vertex ( ) ) if existence_check : expression = expressions . TernaryConditional ( existence_check , expression , expressions . NullLiteral ) output_fields [ output_name ] = expression return blocks . ConstructResult ( output_fields ) | Construct the final ConstructResult basic block that defines the output format of the query . |
38,966 | def _validate_schema_and_ast ( schema , ast ) : core_graphql_errors = validate ( schema , ast ) unsupported_default_directives = frozenset ( [ frozenset ( [ 'include' , frozenset ( [ 'FIELD' , 'FRAGMENT_SPREAD' , 'INLINE_FRAGMENT' ] ) , frozenset ( [ 'if' ] ) ] ) , frozenset ( [ 'skip' , frozenset ( [ 'FIELD' , 'FRAGMENT_SPREAD' , 'INLINE_FRAGMENT' ] ) , frozenset ( [ 'if' ] ) ] ) , frozenset ( [ 'deprecated' , frozenset ( [ 'ENUM_VALUE' , 'FIELD_DEFINITION' ] ) , frozenset ( [ 'reason' ] ) ] ) ] ) expected_directives = { frozenset ( [ directive . name , frozenset ( directive . locations ) , frozenset ( six . viewkeys ( directive . args ) ) ] ) for directive in DIRECTIVES } actual_directives = { frozenset ( [ directive . name , frozenset ( directive . locations ) , frozenset ( six . viewkeys ( directive . args ) ) ] ) for directive in schema . get_directives ( ) } missing_directives = expected_directives - actual_directives if missing_directives : missing_message = ( u'The following directives were missing from the ' u'provided schema: {}' . format ( missing_directives ) ) core_graphql_errors . append ( missing_message ) extra_directives = actual_directives - expected_directives - unsupported_default_directives if extra_directives : extra_message = ( u'The following directives were supplied in the given schema, but are not ' u'not supported by the GraphQL compiler: {}' . format ( extra_directives ) ) core_graphql_errors . append ( extra_message ) return core_graphql_errors | Validate the supplied graphql schema and ast . |
38,967 | def graphql_to_ir ( schema , graphql_string , type_equivalence_hints = None ) : graphql_string = _preprocess_graphql_string ( graphql_string ) try : ast = parse ( graphql_string ) except GraphQLSyntaxError as e : raise GraphQLParsingError ( e ) validation_errors = _validate_schema_and_ast ( schema , ast ) if validation_errors : raise GraphQLValidationError ( u'String does not validate: {}' . format ( validation_errors ) ) if len ( ast . definitions ) != 1 : raise AssertionError ( u'Unsupported graphql string with multiple definitions, should have ' u'been caught in validation: \n{}\n{}' . format ( graphql_string , ast ) ) base_ast = ast . definitions [ 0 ] return _compile_root_ast_to_ir ( schema , base_ast , type_equivalence_hints = type_equivalence_hints ) | Convert the given GraphQL string into compiler IR using the given schema object . |
38,968 | def pretty_print_gremlin ( gremlin ) : gremlin = remove_custom_formatting ( gremlin ) too_many_parts = re . split ( r'([)}]|scatter)[ ]?\.' , gremlin ) parts = [ too_many_parts [ i ] + too_many_parts [ i + 1 ] for i in six . moves . xrange ( 0 , len ( too_many_parts ) - 1 , 2 ) ] parts . append ( too_many_parts [ - 1 ] ) for i in six . moves . xrange ( 1 , len ( parts ) ) : parts [ i ] = '.' + parts [ i ] indentation = 0 indentation_increment = 4 output = [ ] for current_part in parts : if any ( [ current_part . startswith ( '.out' ) , current_part . startswith ( '.in' ) , current_part . startswith ( '.ifThenElse' ) ] ) : indentation += indentation_increment elif current_part . startswith ( '.back' ) or current_part . startswith ( '.optional' ) : indentation -= indentation_increment if indentation < 0 : raise AssertionError ( u'Indentation became negative: {}' . format ( indentation ) ) output . append ( ( ' ' * indentation ) + current_part ) return '\n' . join ( output ) . strip ( ) | Return a human - readable representation of a gremlin command string . |
38,969 | def pretty_print_match ( match , parameterized = True ) : left_curly = '{{' if parameterized else '{' right_curly = '}}' if parameterized else '}' match = remove_custom_formatting ( match ) parts = re . split ( '({}|{})' . format ( left_curly , right_curly ) , match ) inside_braces = False indent_size = 4 indent = ' ' * indent_size output = [ parts [ 0 ] ] for current_index , current_part in enumerate ( parts [ 1 : ] ) : if current_part == left_curly : if inside_braces : raise AssertionError ( u'Found open-braces pair while already inside braces: ' u'{} {} {}' . format ( current_index , parts , match ) ) inside_braces = True output . append ( current_part + '\n' ) elif current_part == right_curly : if not inside_braces : raise AssertionError ( u'Found close-braces pair while not inside braces: ' u'{} {} {}' . format ( current_index , parts , match ) ) inside_braces = False output . append ( current_part ) else : if not inside_braces : stripped_part = current_part . lstrip ( ) if stripped_part . startswith ( '.' ) : output . append ( stripped_part ) else : output . append ( current_part ) else : separate_keywords = re . split ( ', ([a-z]+:)' , current_part ) output . append ( indent + separate_keywords [ 0 ] . lstrip ( ) ) for i in six . moves . xrange ( 1 , len ( separate_keywords ) - 1 , 2 ) : output . append ( ',\n{indent}{keyword} {value}' . format ( keyword = separate_keywords [ i ] . strip ( ) , value = separate_keywords [ i + 1 ] . strip ( ) , indent = indent ) ) output . append ( '\n' ) return '' . join ( output ) . strip ( ) | Return a human - readable representation of a parameterized MATCH query string . |
38,970 | def represent_float_as_str ( value ) : if not isinstance ( value , float ) : raise GraphQLInvalidArgumentError ( u'Attempting to represent a non-float as a float: ' u'{}' . format ( value ) ) with decimal . localcontext ( ) as ctx : ctx . prec = 20 return u'{:f}' . format ( decimal . Decimal ( value ) ) | Represent a float as a string without losing precision . |
38,971 | def coerce_to_decimal ( value ) : if isinstance ( value , decimal . Decimal ) : return value else : try : return decimal . Decimal ( value ) except decimal . InvalidOperation as e : raise GraphQLInvalidArgumentError ( e ) | Attempt to coerce the value to a Decimal or raise an error if unable to do so . |
38,972 | def make_replacement_visitor ( find_expression , replace_expression ) : def visitor_fn ( expression ) : if expression == find_expression : return replace_expression else : return expression return visitor_fn | Return a visitor function that replaces every instance of one expression with another one . |
38,973 | def make_type_replacement_visitor ( find_types , replacement_func ) : def visitor_fn ( expression ) : if isinstance ( expression , find_types ) : return replacement_func ( expression ) else : return expression return visitor_fn | Return a visitor function that replaces expressions of a given type with new expressions . |
38,974 | def _validate_operator_name ( operator , supported_operators ) : if not isinstance ( operator , six . text_type ) : raise TypeError ( u'Expected operator as unicode string, got: {} {}' . format ( type ( operator ) . __name__ , operator ) ) if operator not in supported_operators : raise GraphQLCompilationError ( u'Unrecognized operator: {}' . format ( operator ) ) | Ensure the named operator is valid and supported . |
38,975 | def validate ( self ) : if self . value is None or self . value is True or self . value is False : return if isinstance ( self . value , six . string_types ) : validate_safe_string ( self . value ) return if isinstance ( self . value , int ) : return if isinstance ( self . value , list ) : if len ( self . value ) > 0 : for x in self . value : validate_safe_string ( x ) return raise GraphQLCompilationError ( u'Cannot represent literal: {}' . format ( self . value ) ) | Validate that the Literal is correctly representable . |
38,976 | def validate ( self ) : if not self . variable_name . startswith ( u'$' ) : raise GraphQLCompilationError ( u'Expected variable name to start with $, but was: ' u'{}' . format ( self . variable_name ) ) if self . variable_name in RESERVED_MATCH_KEYWORDS : raise GraphQLCompilationError ( u'Cannot use reserved MATCH keyword {} as variable ' u'name!' . format ( self . variable_name ) ) validate_safe_string ( self . variable_name [ 1 : ] ) if not is_graphql_type ( self . inferred_type ) : raise ValueError ( u'Invalid value of "inferred_type": {}' . format ( self . inferred_type ) ) if isinstance ( self . inferred_type , GraphQLNonNull ) : raise ValueError ( u'GraphQL non-null types are not supported as "inferred_type": ' u'{}' . format ( self . inferred_type ) ) if isinstance ( self . inferred_type , GraphQLList ) : inner_type = strip_non_null_from_type ( self . inferred_type . of_type ) if GraphQLDate . is_same_type ( inner_type ) or GraphQLDateTime . is_same_type ( inner_type ) : raise GraphQLCompilationError ( u'Lists of Date or DateTime cannot currently be represented as ' u'Variable objects: {}' . format ( self . inferred_type ) ) | Validate that the Variable is correctly representable . |
38,977 | def to_match ( self ) : self . validate ( ) variable_with_no_dollar_sign = self . variable_name [ 1 : ] match_variable_name = '{%s}' % ( six . text_type ( variable_with_no_dollar_sign ) , ) if GraphQLDate . is_same_type ( self . inferred_type ) : return u'date(%s, "%s")' % ( match_variable_name , STANDARD_DATE_FORMAT ) elif GraphQLDateTime . is_same_type ( self . inferred_type ) : return u'date(%s, "%s")' % ( match_variable_name , STANDARD_DATETIME_FORMAT ) else : return match_variable_name | Return a unicode object with the MATCH representation of this Variable . |
38,978 | def validate ( self ) : if not isinstance ( self . location , Location ) : raise TypeError ( u'Expected Location location, got: {} {}' . format ( type ( self . location ) . __name__ , self . location ) ) if self . location . field is None : raise AssertionError ( u'Received Location without a field: {}' . format ( self . location ) ) if not is_graphql_type ( self . field_type ) : raise ValueError ( u'Invalid value of "field_type": {}' . format ( self . field_type ) ) | Validate that the GlobalContextField is correctly representable . |
38,979 | def to_match ( self ) : self . validate ( ) mark_name , field_name = self . location . get_location_name ( ) validate_safe_string ( mark_name ) validate_safe_string ( field_name ) return u'%s.%s' % ( mark_name , field_name ) | Return a unicode object with the MATCH representation of this GlobalContextField . |
38,980 | def to_match ( self ) : self . validate ( ) mark_name , field_name = self . location . get_location_name ( ) validate_safe_string ( mark_name ) if field_name is None : return u'$matched.%s' % ( mark_name , ) else : validate_safe_string ( field_name ) return u'$matched.%s.%s' % ( mark_name , field_name ) | Return a unicode object with the MATCH representation of this ContextField . |
38,981 | def validate ( self ) : if not isinstance ( self . location , Location ) : raise TypeError ( u'Expected Location location, got: {} {}' . format ( type ( self . location ) . __name__ , self . location ) ) if not self . location . field : raise ValueError ( u'Expected Location object that points to a field, got: ' u'{}' . format ( self . location ) ) if not is_graphql_type ( self . field_type ) : raise ValueError ( u'Invalid value of "field_type": {}' . format ( self . field_type ) ) stripped_field_type = strip_non_null_from_type ( self . field_type ) if isinstance ( stripped_field_type , GraphQLList ) : inner_type = strip_non_null_from_type ( stripped_field_type . of_type ) if GraphQLDate . is_same_type ( inner_type ) or GraphQLDateTime . is_same_type ( inner_type ) : raise GraphQLCompilationError ( u'Lists of Date or DateTime cannot currently be represented as ' u'OutputContextField objects: {}' . format ( self . field_type ) ) | Validate that the OutputContextField is correctly representable . |
38,982 | def validate ( self ) : if not isinstance ( self . fold_scope_location , FoldScopeLocation ) : raise TypeError ( u'Expected FoldScopeLocation fold_scope_location, got: {} {}' . format ( type ( self . fold_scope_location ) , self . fold_scope_location ) ) if self . fold_scope_location . field is None : raise ValueError ( u'Expected FoldScopeLocation at a field, but got: {}' . format ( self . fold_scope_location ) ) if self . fold_scope_location . field == COUNT_META_FIELD_NAME : if not GraphQLInt . is_same_type ( self . field_type ) : raise TypeError ( u'Expected the _x_count meta-field to be of GraphQLInt type, but ' u'encountered type {} instead: {}' . format ( self . field_type , self . fold_scope_location ) ) else : if not isinstance ( self . field_type , GraphQLList ) : raise ValueError ( u'Invalid value of "field_type" for a field that is not ' u'a meta-field, expected a list type but got: {} {}' . format ( self . field_type , self . fold_scope_location ) ) inner_type = strip_non_null_from_type ( self . field_type . of_type ) if isinstance ( inner_type , GraphQLList ) : raise GraphQLCompilationError ( u'Outputting list-valued fields in a @fold context is currently not supported: ' u'{} {}' . format ( self . fold_scope_location , self . field_type . of_type ) ) | Validate that the FoldedContextField is correctly representable . |
38,983 | def validate ( self ) : if not isinstance ( self . fold_scope_location , FoldScopeLocation ) : raise TypeError ( u'Expected FoldScopeLocation fold_scope_location, got: {} {}' . format ( type ( self . fold_scope_location ) , self . fold_scope_location ) ) if self . fold_scope_location . field != COUNT_META_FIELD_NAME : raise AssertionError ( u'Unexpected field in the FoldScopeLocation of this ' u'FoldCountContextField object: {} {}' . format ( self . fold_scope_location , self ) ) | Validate that the FoldCountContextField is correctly representable . |
38,984 | def validate ( self ) : if not isinstance ( self . location , Location ) : raise TypeError ( u'Expected Location location, got: {} {}' . format ( type ( self . location ) . __name__ , self . location ) ) if self . location . field : raise ValueError ( u'Expected location to point to a vertex, ' u'but found a field: {}' . format ( self . location ) ) | Validate that the ContextFieldExistence is correctly representable . |
38,985 | def validate ( self ) : _validate_operator_name ( self . operator , UnaryTransformation . SUPPORTED_OPERATORS ) if not isinstance ( self . inner_expression , Expression ) : raise TypeError ( u'Expected Expression inner_expression, got {} {}' . format ( type ( self . inner_expression ) . __name__ , self . inner_expression ) ) | Validate that the UnaryTransformation is correctly representable . |
38,986 | def to_match ( self ) : self . validate ( ) translation_table = { u'size' : u'size()' , } match_operator = translation_table . get ( self . operator ) if not match_operator : raise AssertionError ( u'Unrecognized operator used: ' u'{} {}' . format ( self . operator , self ) ) template = u'%(inner)s.%(operator)s' args = { 'inner' : self . inner_expression . to_match ( ) , 'operator' : match_operator , } return template % args | Return a unicode object with the MATCH representation of this UnaryTransformation . |
38,987 | def validate ( self ) : _validate_operator_name ( self . operator , BinaryComposition . SUPPORTED_OPERATORS ) if not isinstance ( self . left , Expression ) : raise TypeError ( u'Expected Expression left, got: {} {} {}' . format ( type ( self . left ) . __name__ , self . left , self ) ) if not isinstance ( self . right , Expression ) : raise TypeError ( u'Expected Expression right, got: {} {}' . format ( type ( self . right ) . __name__ , self . right ) ) | Validate that the BinaryComposition is correctly representable . |
38,988 | def to_match ( self ) : self . validate ( ) regular_operator_format = '(%(left)s %(operator)s %(right)s)' inverted_operator_format = '(%(right)s %(operator)s %(left)s)' intersects_operator_format = '(%(operator)s(%(left)s, %(right)s).asList().size() > 0)' if any ( ( isinstance ( self . left , Literal ) and self . left . value is None , isinstance ( self . right , Literal ) and self . right . value is None ) ) : translation_table = { u'=' : ( u'IS' , regular_operator_format ) , u'!=' : ( u'IS NOT' , regular_operator_format ) , } else : translation_table = { u'=' : ( u'=' , regular_operator_format ) , u'!=' : ( u'<>' , regular_operator_format ) , u'>=' : ( u'>=' , regular_operator_format ) , u'<=' : ( u'<=' , regular_operator_format ) , u'>' : ( u'>' , regular_operator_format ) , u'<' : ( u'<' , regular_operator_format ) , u'+' : ( u'+' , regular_operator_format ) , u'||' : ( u'OR' , regular_operator_format ) , u'&&' : ( u'AND' , regular_operator_format ) , u'contains' : ( u'CONTAINS' , regular_operator_format ) , u'intersects' : ( u'intersect' , intersects_operator_format ) , u'has_substring' : ( None , None ) , u'LIKE' : ( u'LIKE' , regular_operator_format ) , u'INSTANCEOF' : ( u'INSTANCEOF' , regular_operator_format ) , } match_operator , format_spec = translation_table . get ( self . operator , ( None , None ) ) if not match_operator : raise AssertionError ( u'Unrecognized operator used: ' u'{} {}' . format ( self . operator , self ) ) return format_spec % dict ( operator = match_operator , left = self . left . to_match ( ) , right = self . right . to_match ( ) ) | Return a unicode object with the MATCH representation of this BinaryComposition . |
38,989 | def validate ( self ) : if not isinstance ( self . predicate , Expression ) : raise TypeError ( u'Expected Expression predicate, got: {} {}' . format ( type ( self . predicate ) . __name__ , self . predicate ) ) if not isinstance ( self . if_true , Expression ) : raise TypeError ( u'Expected Expression if_true, got: {} {}' . format ( type ( self . if_true ) . __name__ , self . if_true ) ) if not isinstance ( self . if_false , Expression ) : raise TypeError ( u'Expected Expression if_false, got: {} {}' . format ( type ( self . if_false ) . __name__ , self . if_false ) ) | Validate that the TernaryConditional is correctly representable . |
38,990 | def to_match ( self ) : self . validate ( ) def visitor_fn ( expression ) : if isinstance ( expression , TernaryConditional ) : raise ValueError ( u'Cannot emit MATCH code for TernaryConditional that contains ' u'in its predicate another TernaryConditional: ' u'{} {}' . format ( expression , self ) ) return expression self . predicate . visit_and_update ( visitor_fn ) format_spec = u'if(eval("%(predicate)s"), %(if_true)s, %(if_false)s)' predicate_string = self . predicate . to_match ( ) if u'"' in predicate_string : raise AssertionError ( u'Found a double-quote within the predicate string, this would ' u'have terminated the if(eval()) early and should be fixed: ' u'{} {}' . format ( predicate_string , self ) ) return format_spec % dict ( predicate = predicate_string , if_true = self . if_true . to_match ( ) , if_false = self . if_false . to_match ( ) ) | Return a unicode object with the MATCH representation of this TernaryConditional . |
38,991 | def sanity_check_ir_blocks_from_frontend ( ir_blocks , query_metadata_table ) : if not ir_blocks : raise AssertionError ( u'Received no ir_blocks: {}' . format ( ir_blocks ) ) _sanity_check_fold_scope_locations_are_unique ( ir_blocks ) _sanity_check_no_nested_folds ( ir_blocks ) _sanity_check_query_root_block ( ir_blocks ) _sanity_check_output_source_follower_blocks ( ir_blocks ) _sanity_check_block_pairwise_constraints ( ir_blocks ) _sanity_check_mark_location_preceding_optional_traverse ( ir_blocks ) _sanity_check_every_location_is_marked ( ir_blocks ) _sanity_check_coerce_type_outside_of_fold ( ir_blocks ) _sanity_check_all_marked_locations_are_registered ( ir_blocks , query_metadata_table ) _sanity_check_registered_locations_parent_locations ( query_metadata_table ) | Assert that IR blocks originating from the frontend do not have nonsensical structure . |
38,992 | def _sanity_check_registered_locations_parent_locations ( query_metadata_table ) : for location , location_info in query_metadata_table . registered_locations : if ( location != query_metadata_table . root_location and not query_metadata_table . root_location . is_revisited_at ( location ) ) : if location_info . parent_location is None : raise AssertionError ( u'Found a location that is not the root location of the query ' u'or a revisit of the root, but does not have a parent: ' u'{} {}' . format ( location , location_info ) ) if location_info . parent_location is not None : query_metadata_table . get_location_info ( location_info . parent_location ) | Assert that all registered locations parent locations are also registered . |
38,993 | def _sanity_check_all_marked_locations_are_registered ( ir_blocks , query_metadata_table ) : registered_locations = { location for location , _ in query_metadata_table . registered_locations } ir_encountered_locations = { block . location for block in ir_blocks if isinstance ( block , MarkLocation ) } unregistered_locations = ir_encountered_locations - registered_locations unencountered_locations = registered_locations - ir_encountered_locations if unregistered_locations : raise AssertionError ( u'IR blocks unexpectedly contain locations not registered in the ' u'QueryMetadataTable: {}' . format ( unregistered_locations ) ) if unencountered_locations : raise AssertionError ( u'QueryMetadataTable unexpectedly contains registered locations that ' u'never appear in the IR blocks: {}' . format ( unencountered_locations ) ) | Assert that all locations in MarkLocation blocks have registered and valid metadata . |
38,994 | def _sanity_check_fold_scope_locations_are_unique ( ir_blocks ) : observed_locations = dict ( ) for block in ir_blocks : if isinstance ( block , Fold ) : alternate = observed_locations . get ( block . fold_scope_location , None ) if alternate is not None : raise AssertionError ( u'Found two Fold blocks with identical FoldScopeLocations: ' u'{} {} {}' . format ( alternate , block , ir_blocks ) ) observed_locations [ block . fold_scope_location ] = block | Assert that every FoldScopeLocation that exists on a Fold block is unique . |
38,995 | def _sanity_check_no_nested_folds ( ir_blocks ) : fold_seen = False for block in ir_blocks : if isinstance ( block , Fold ) : if fold_seen : raise AssertionError ( u'Found a nested Fold contexts: {}' . format ( ir_blocks ) ) else : fold_seen = True elif isinstance ( block , Unfold ) : if not fold_seen : raise AssertionError ( u'Found an Unfold block without a matching Fold: ' u'{}' . format ( ir_blocks ) ) else : fold_seen = False | Assert that there are no nested Fold contexts and that every Fold has a matching Unfold . |
38,996 | def _sanity_check_query_root_block ( ir_blocks ) : if not isinstance ( ir_blocks [ 0 ] , QueryRoot ) : raise AssertionError ( u'The first block was not QueryRoot: {}' . format ( ir_blocks ) ) for block in ir_blocks [ 1 : ] : if isinstance ( block , QueryRoot ) : raise AssertionError ( u'Found QueryRoot after the first block: {}' . format ( ir_blocks ) ) | Assert that QueryRoot is always the first block and only the first block . |
38,997 | def _sanity_check_construct_result_block ( ir_blocks ) : if not isinstance ( ir_blocks [ - 1 ] , ConstructResult ) : raise AssertionError ( u'The last block was not ConstructResult: {}' . format ( ir_blocks ) ) for block in ir_blocks [ : - 1 ] : if isinstance ( block , ConstructResult ) : raise AssertionError ( u'Found ConstructResult before the last block: ' u'{}' . format ( ir_blocks ) ) | Assert that ConstructResult is always the last block and only the last block . |
38,998 | def _sanity_check_block_pairwise_constraints ( ir_blocks ) : for first_block , second_block in pairwise ( ir_blocks ) : if isinstance ( first_block , MarkLocation ) and isinstance ( second_block , Filter ) : raise AssertionError ( u'Found Filter after MarkLocation block: {}' . format ( ir_blocks ) ) if isinstance ( first_block , MarkLocation ) and isinstance ( second_block , MarkLocation ) : raise AssertionError ( u'Found consecutive MarkLocation blocks: {}' . format ( ir_blocks ) ) if isinstance ( first_block , Traverse ) and first_block . optional : if not isinstance ( second_block , ( MarkLocation , CoerceType , Filter ) ) : raise AssertionError ( u'Expected MarkLocation, CoerceType or Filter after Traverse ' u'with optional=True. Found: {}' . format ( ir_blocks ) ) if isinstance ( first_block , Backtrack ) and first_block . optional : if not isinstance ( second_block , MarkLocation ) : raise AssertionError ( u'Expected MarkLocation after Backtrack with optional=True, ' u'but none was found: {}' . format ( ir_blocks ) ) if isinstance ( second_block , Recurse ) : if not ( isinstance ( first_block , MarkLocation ) or isinstance ( first_block , Backtrack ) ) : raise AssertionError ( u'Expected MarkLocation or Backtrack before Recurse, but none ' u'was found: {}' . format ( ir_blocks ) ) | Assert that adjacent blocks obey all invariants . |
38,999 | def _sanity_check_mark_location_preceding_optional_traverse ( ir_blocks ) : _ , new_ir_blocks = extract_folds_from_ir_blocks ( ir_blocks ) for first_block , second_block in pairwise ( new_ir_blocks ) : if isinstance ( second_block , Traverse ) and second_block . optional : if not isinstance ( first_block , MarkLocation ) : raise AssertionError ( u'Expected MarkLocation before Traverse with optional=True, ' u'but none was found: {}' . format ( ir_blocks ) ) | Assert that optional Traverse blocks are preceded by a MarkLocation . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.