溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PostgreSQL 源碼解讀(175)- 查詢#93(語(yǔ)法分析:gram.y)#2

發(fā)布時(shí)間:2020-08-10 17:16:56 來(lái)源:ITPUB博客 閱讀:588 作者:husthxd 欄目:關(guān)系型數(shù)據(jù)庫(kù)

本節(jié)繼續(xù)介紹PostgreSQL的語(yǔ)法分析定義文件gram.y的第二部分Definitions.
Bison輸入文件的組成:


%{
Declarations
%}
Definitions
%%
Productions
%%
User subroutines

一、Definitions

Definitions在Bison的作用與Flex中的功能也差不多,在這個(gè)段定義一些Bison專有變量或相關(guān)選項(xiàng).
%purge-parser
指示Bison創(chuàng)建一個(gè)可重入的解析器.與普通的解析器一個(gè)很大的不同的,yylval的類型是union指針而不是union.

%expect
%expect N告訴Bison,解析器應(yīng)該有N個(gè)shift/reduce沖突,如果不匹配,Bison將報(bào)告編譯時(shí)錯(cuò)誤。

%name-prefix
命名函數(shù)名稱,默認(rèn)為yy
%name-prefix “base_yy”意味著默認(rèn)的yyxx()會(huì)變成base_yyxx().比如yyparse(),yylex(),yyerror(),yylval,yychar和
yydebug.

%locations
位置

%parse-param
%parse-param聲明的內(nèi)容位于yyparse()的括號(hào)之間,可以聲明任意多的參數(shù).
比如%parse-param {core_yyscan_t yyscanner},參數(shù)為core_yyscan_t yyscanner.

%lex-param
%lex-param聲明的內(nèi)容位于yylex()的括號(hào)之間,可以聲明任意多的參數(shù).
比如%lex-param {core_yyscan_t yyscanner},參數(shù)為core_yyscan_t yyscanner.

%union
%union聲明了在解析器中標(biāo)識(shí)符所使用的類型.
Bison解析器,每一個(gè)標(biāo)識(shí)符,包括tokens和非終結(jié)符,都有值與之關(guān)聯(lián),默認(rèn)的,值的類型都是整型,但在實(shí)際應(yīng)用中遠(yuǎn)遠(yuǎn)不夠.
%union可以為標(biāo)識(shí)符值創(chuàng)建C語(yǔ)言u(píng)nion聲明.


%union
{
    core_YYSTYPE        core_yystype;
    /* these fields must match core_YYSTYPE: */
    int                    ival;
    char                *str;
    const char            *keyword;
    ...
}

其中core_yystype的類型為core_YYSTYPE聯(lián)合體.


/*
 * The scanner returns extra data about scanned tokens in this union type.
 * Note that this is a subset of the fields used in YYSTYPE of the bison
 * parsers built atop the scanner.
 */
typedef union core_YYSTYPE
{
    int            ival;            /* for integer literals */
    char       *str;            /* for identifiers and non-integer literals */
    const char *keyword;        /* canonical spelling of keywords */
} core_YYSTYPE;

一旦定義了union,那需要通過(guò)將union中合適的名稱放在尖括號(hào)(<>)中,用以告訴Bison哪些符號(hào)具有哪些類型的值.

%type
類型定義,如:


%type <node>    stmt schema_stmt
        AlterEventTrigStmt AlterCollationStmt
        ...

表示標(biāo)識(shí)符/非終結(jié)符 的類型可以是stmt/schema_stmt/AlterEventTrigStmt/…

%nonassoc
使用%nonassoc聲明非關(guān)聯(lián)操作符。

%left
左關(guān)聯(lián)操作符

%right
右關(guān)聯(lián)操作符

二、gram.y定義部分源碼


%pure-parser
%expect 0
%name-prefix="base_yy"
%locations
%parse-param {core_yyscan_t yyscanner}
%lex-param   {core_yyscan_t yyscanner}
%union
{
    core_YYSTYPE        core_yystype;
    /* these fields must match core_YYSTYPE: */
    int                    ival;
    char                *str;
    const char            *keyword;
    char                chr;
    bool                boolean;
    JoinType            jtype;
    DropBehavior        dbehavior;
    OnCommitAction        oncommit;
    List                *list;
    Node                *node;
    Value                *value;
    ObjectType            objtype;
    TypeName            *typnam;
    FunctionParameter   *fun_param;
    FunctionParameterMode fun_param_mode;
    ObjectWithArgs        *objwithargs;
    DefElem                *defelt;
    SortBy                *sortby;
    WindowDef            *windef;
    JoinExpr            *jexpr;
    IndexElem            *ielem;
    Alias                *alias;
    RangeVar            *range;
    IntoClause            *into;
    WithClause            *with;
    InferClause            *infer;
    OnConflictClause    *onconflict;
    A_Indices            *aind;
    ResTarget            *target;
    struct PrivTarget    *privtarget;
    AccessPriv            *accesspriv;
    struct ImportQual    *importqual;
    InsertStmt            *istmt;
    VariableSetStmt        *vsetstmt;
    PartitionElem        *partelem;
    PartitionSpec        *partspec;
    PartitionBoundSpec    *partboundspec;
    RoleSpec            *rolespec;
}
%type <node>    stmt schema_stmt
        AlterEventTrigStmt AlterCollationStmt
        AlterDatabaseStmt AlterDatabaseSetStmt AlterDomainStmt AlterEnumStmt
        AlterFdwStmt AlterForeignServerStmt AlterGroupStmt
        AlterObjectDependsStmt AlterObjectSchemaStmt AlterOwnerStmt
        AlterOperatorStmt AlterSeqStmt AlterSystemStmt AlterTableStmt
        AlterTblSpcStmt AlterExtensionStmt AlterExtensionContentsStmt AlterForeignTableStmt
        AlterCompositeTypeStmt AlterUserMappingStmt
        AlterRoleStmt AlterRoleSetStmt AlterPolicyStmt
        AlterDefaultPrivilegesStmt DefACLAction
        AnalyzeStmt CallStmt ClosePortalStmt ClusterStmt CommentStmt
        ConstraintsSetStmt CopyStmt CreateAsStmt CreateCastStmt
        CreateDomainStmt CreateExtensionStmt CreateGroupStmt CreateOpClassStmt
        CreateOpFamiXXXtmt AlterOpFamiXXXtmt CreatePLangStmt
        CreateSchemaStmt CreateSeqStmt CreateStmt CreateStatsStmt CreateTableSpaceStmt
        CreateFdwStmt CreateForeignServerStmt CreateForeignTableStmt
        CreateAssertStmt CreateTransformStmt CreateTrigStmt CreateEventTrigStmt
        CreateUserStmt CreateUserMappingStmt CreateRoleStmt CreatePolicyStmt
        CreatedbStmt DeclareCursorStmt DefineStmt DeleteStmt DiscardStmt DoStmt
        DropOpClassStmt DropOpFamiXXXtmt DropPLangStmt DropStmt
        DropAssertStmt DropCastStmt DropRoleStmt
        DropdbStmt DropTableSpaceStmt
        DropTransformStmt
        DropUserMappingStmt ExplainStmt FetchStmt
        GrantStmt GrantRoleStmt ImportForeignSchemaStmt IndexStmt InsertStmt
        ListenStmt LoadStmt LockStmt NotifyStmt ExplainableStmt PreparableStmt
        CreateFunctionStmt AlterFunctionStmt ReindexStmt RemoveAggrStmt
        RemoveFuncStmt RemoveOperStmt RenameStmt RevokeStmt RevokeRoleStmt
        RuleActionStmt RuleActionStmtOrEmpty RuleStmt
        SecLabelStmt SelectStmt TransactionStmt TruncateStmt
        UnlistenStmt UpdateStmt VacuumStmt
        VariableResetStmt VariableSetStmt VariableShowStmt
        ViewStmt CheckPointStmt CreateConversionStmt
        DeallocateStmt PrepareStmt ExecuteStmt
        DropOwnedStmt ReassignOwnedStmt
        AlterTSConfigurationStmt AlterTSDictionaryStmt
        CreateMatViewStmt RefreshMatViewStmt CreateAmStmt
        CreatePublicationStmt AlterPublicationStmt
        CreateSubscriptionStmt AlterSubscriptionStmt DropSubscriptionStmt
%type <node>    select_no_parens select_with_parens select_clause
                simple_select values_clause
%type <node>    alter_column_default opclass_item opclass_drop alter_using
%type <ival>    add_drop opt_asc_desc opt_nulls_order
%type <node>    alter_table_cmd alter_type_cmd opt_collate_clause
       replica_identity partition_cmd index_partition_cmd
%type <list>    alter_table_cmds alter_type_cmds
%type <list>    alter_identity_column_option_list
%type <defelt>  alter_identity_column_option
%type <dbehavior>    opt_drop_behavior
%type <list>    createdb_opt_list createdb_opt_items copy_opt_list
                transaction_mode_list
                create_extension_opt_list alter_extension_opt_list
%type <defelt>    createdb_opt_item copy_opt_item
                transaction_mode_item
                create_extension_opt_item alter_extension_opt_item
%type <ival>    opt_lock lock_type cast_context
%type <ival>    vacuum_option_list vacuum_option_elem
                analyze_option_list analyze_option_elem
%type <boolean>    opt_or_replace
                opt_grant_grant_option opt_grant_admin_option
                opt_nowait opt_if_exists opt_with_data
%type <ival>    opt_nowait_or_skip
%type <list>    OptRoleList AlterOptRoleList
%type <defelt>    CreateOptRoleElem AlterOptRoleElem
%type <str>        opt_type
%type <str>        foreign_server_version opt_foreign_server_version
%type <str>        opt_in_database
%type <str>        OptSchemaName
%type <list>    OptSchemaEltList
%type <boolean> TriggerForSpec TriggerForType
%type <ival>    TriggerActionTime
%type <list>    TriggerEvents TriggerOneEvent
%type <value>    TriggerFuncArg
%type <node>    TriggerWhen
%type <str>        TransitionRelName
%type <boolean>    TransitionRowOrTable TransitionOldOrNew
%type <node>    TriggerTransition
%type <list>    event_trigger_when_list event_trigger_value_list
%type <defelt>    event_trigger_when_item
%type <chr>        enable_trigger
%type <str>        copy_file_name
                database_name access_method_clause access_method attr_name
                name cursor_name file_name
                index_name opt_index_name cluster_index_specification
%type <list>    func_name handler_name qual_Op qual_all_Op subquery_Op
                opt_class opt_inline_handler opt_validator validator_clause
                opt_collate
%type <range>    qualified_name insert_target OptConstrFromTable
%type <str>        all_Op MathOp
%type <str>        row_security_cmd RowSecurityDefaultForCmd
%type <boolean> RowSecurityDefaultPermissive
%type <node>    RowSecurityOptionalWithCheck RowSecurityOptionalExpr
%type <list>    RowSecurityDefaultToRole RowSecurityOptionalToRole
%type <str>        iso_level opt_encoding
%type <rolespec> grantee
%type <list>    grantee_list
%type <accesspriv> privilege
%type <list>    privileges privilege_list
%type <privtarget> privilege_target
%type <objwithargs> function_with_argtypes aggregate_with_argtypes operator_with_argtypes
%type <list>    function_with_argtypes_list aggregate_with_argtypes_list operator_with_argtypes_list
%type <ival>    defacl_privilege_target
%type <defelt>    DefACLOption
%type <list>    DefACLOptionList
%type <ival>    import_qualification_type
%type <importqual> import_qualification
%type <node>    vacuum_relation
%type <list>    stmtblock stmtmulti
                OptTableElementList TableElementList OptInherit definition
                OptTypedTableElementList TypedTableElementList
                reloptions opt_reloptions
                OptWith distinct_clause opt_all_clause opt_definition func_args func_args_list
                func_args_with_defaults func_args_with_defaults_list
                aggr_args aggr_args_list
                func_as createfunc_opt_list alterfunc_opt_list
                old_aggr_definition old_aggr_list
                oper_argtypes RuleActionList RuleActionMulti
                opt_column_list columnList opt_name_list
                sort_clause opt_sort_clause sortby_list index_params
                opt_include opt_c_include index_including_params
                name_list role_list from_clause from_list opt_array_bounds
                qualified_name_list any_name any_name_list type_name_list
                any_operator expr_list attrs
                target_list opt_target_list insert_column_list set_target_list
                set_clause_list set_clause
                def_list operator_def_list indirection opt_indirection
                reloption_list group_clause TriggerFuncArgs select_limit
                opt_select_limit opclass_item_list opclass_drop_list
                opclass_purpose opt_opfamily transaction_mode_list_or_empty
                OptTableFuncElementList TableFuncElementList opt_type_modifiers
                prep_type_clause
                execute_param_clause using_clause returning_clause
                opt_enum_val_list enum_val_list table_func_column_list
                create_generic_options alter_generic_options
                relation_expr_list dostmt_opt_list
                transform_element_list transform_type_list
                TriggerTransitions TriggerReferencing
                publication_name_list
                vacuum_relation_list opt_vacuum_relation_list
%type <list>    group_by_list
%type <node>    group_by_item empty_grouping_set rollup_clause cube_clause
%type <node>    grouping_sets_clause
%type <node>    opt_publication_for_tables publication_for_tables
%type <value>    publication_name_item
%type <list>    opt_fdw_options fdw_options
%type <defelt>    fdw_option
%type <range>    OptTempTableName
%type <into>    into_clause create_as_target create_mv_target
%type <defelt>    createfunc_opt_item common_func_opt_item dostmt_opt_item
%type <fun_param> func_arg func_arg_with_default table_func_column aggr_arg
%type <fun_param_mode> arg_class
%type <typnam>    func_return func_type
%type <boolean>  opt_trusted opt_restart_seqs
%type <ival>     OptTemp
%type <ival>     OptNoLog
%type <oncommit> OnCommitOption
%type <ival>    for_locking_strength
%type <node>    for_locking_item
%type <list>    for_locking_clause opt_for_locking_clause for_locking_items
%type <list>    locked_rels_list
%type <boolean>    all_or_distinct
%type <node>    join_outer join_qual
%type <jtype>    join_type
%type <list>    extract_list overlay_list position_list
%type <list>    substr_list trim_list
%type <list>    opt_interval interval_second
%type <node>    overlay_placing substr_from substr_for
%type <boolean> opt_instead
%type <boolean> opt_unique opt_concurrently opt_verbose opt_full
%type <boolean> opt_freeze opt_analyze opt_default opt_recheck
%type <defelt>    opt_binary opt_oids copy_delimiter
%type <boolean> copy_from opt_program
%type <ival>    opt_column event cursor_options opt_hold opt_set_data
%type <objtype>    drop_type_any_name drop_type_name drop_type_name_on_any_name
                comment_type_any_name comment_type_name
                security_label_type_any_name security_label_type_name
%type <node>    fetch_args limit_clause select_limit_value
                offset_clause select_offset_value
                select_fetch_first_value I_or_F_const
%type <ival>    row_or_rows first_or_next
%type <list>    OptSeqOptList SeqOptList OptParenthesizedSeqOptList
%type <defelt>    SeqOptElem
%type <istmt>    insert_rest
%type <infer>    opt_conf_expr
%type <onconflict> opt_on_conflict
%type <vsetstmt> generic_set set_rest set_rest_more generic_reset reset_rest
                 SetResetClause FunctionSetResetClause
%type <node>    TableElement TypedTableElement ConstraintElem TableFuncElement
%type <node>    columnDef columnOptions
%type <defelt>    def_elem reloption_elem old_aggr_elem operator_def_elem
%type <node>    def_arg columnElem where_clause where_or_current_clause
                a_expr b_expr c_expr AexprConst indirection_el opt_slice_bound
                columnref in_expr having_clause func_table xmltable array_expr
                ExclusionWhereClause operator_def_arg
%type <list>    rowsfrom_item rowsfrom_list opt_col_def_list
%type <boolean> opt_ordinality
%type <list>    ExclusionConstraintList ExclusionConstraintElem
%type <list>    func_arg_list
%type <node>    func_arg_expr
%type <list>    row explicit_row implicit_row type_list array_expr_list
%type <node>    case_expr case_arg when_clause case_default
%type <list>    when_clause_list
%type <ival>    sub_type
%type <value>    NumericOnly
%type <list>    NumericOnly_list
%type <alias>    alias_clause opt_alias_clause
%type <list>    func_alias_clause
%type <sortby>    sortby
%type <ielem>    index_elem
%type <node>    table_ref
%type <jexpr>    joined_table
%type <range>    relation_expr
%type <range>    relation_expr_opt_alias
%type <node>    tablesample_clause opt_repeatable_clause
%type <target>    target_el set_target insert_column_item
%type <str>        generic_option_name
%type <node>    generic_option_arg
%type <defelt>    generic_option_elem alter_generic_option_elem
%type <list>    generic_option_list alter_generic_option_list
%type <str>        explain_option_name
%type <node>    explain_option_arg
%type <defelt>    explain_option_elem
%type <list>    explain_option_list
%type <ival>    reindex_target_type reindex_target_multitable
%type <ival>    reindex_option_list reindex_option_elem
%type <node>    copy_generic_opt_arg copy_generic_opt_arg_list_item
%type <defelt>    copy_generic_opt_elem
%type <list>    copy_generic_opt_list copy_generic_opt_arg_list
%type <list>    copy_options
%type <typnam>    Typename SimpleTypename ConstTypename
                GenericType Numeric opt_float
                Character ConstCharacter
                CharacterWithLength CharacterWithoutLength
                ConstDatetime ConstInterval
                Bit ConstBit BitWithLength BitWithoutLength
%type <str>        character
%type <str>        extract_arg
%type <boolean> opt_varying opt_timezone opt_no_inherit
%type <ival>    Iconst SignedIconst
%type <str>        Sconst comment_text notify_payload
%type <str>        RoleId opt_boolean_or_string
%type <list>    var_list
%type <str>        ColId ColLabel var_name type_function_name param_name
%type <str>        NonReservedWord NonReservedWord_or_Sconst
%type <str>        createdb_opt_name
%type <node>    var_value zone_value
%type <rolespec> auth_ident RoleSpec opt_granted_by
%type <keyword> unreserved_keyword type_func_name_keyword
%type <keyword> col_name_keyword reserved_keyword
%type <node>    TableConstraint TableLikeClause
%type <ival>    TableLikeOptionList TableLikeOption
%type <list>    ColQualList
%type <node>    ColConstraint ColConstraintElem ConstraintAttr
%type <ival>    key_actions key_delete key_match key_update key_action
%type <ival>    ConstraintAttributeSpec ConstraintAttributeElem
%type <str>        ExistingIndex
%type <list>    constraints_set_list
%type <boolean> constraints_set_mode
%type <str>        OptTableSpace OptConsTableSpace
%type <rolespec> OptTableSpaceOwner
%type <ival>    opt_check_option
%type <str>        opt_provider security_label
%type <target>    xml_attribute_el
%type <list>    xml_attribute_list xml_attributes
%type <node>    xml_root_version opt_xml_root_standalone
%type <node>    xmlexists_argument
%type <ival>    document_or_content
%type <boolean> xml_whitespace_option
%type <list>    xmltable_column_list xmltable_column_option_list
%type <node>    xmltable_column_el
%type <defelt>    xmltable_column_option_el
%type <list>    xml_namespace_list
%type <target>    xml_namespace_el
%type <node>    func_application func_expr_common_subexpr
%type <node>    func_expr func_expr_windowless
%type <node>    common_table_expr
%type <with>    with_clause opt_with_clause
%type <list>    cte_list
%type <list>    within_group_clause
%type <node>    filter_clause
%type <list>    window_clause window_definition_list opt_partition_clause
%type <windef>    window_definition over_clause window_specification
                opt_frame_clause frame_extent frame_bound
%type <ival>    opt_window_exclusion_clause
%type <str>        opt_existing_window_name
%type <boolean> opt_if_not_exists
%type <ival>    generated_when override_kind
%type <partspec>    PartitionSpec OptPartitionSpec
%type <str>            part_strategy
%type <partelem>    part_elem
%type <list>        part_params
%type <partboundspec> PartitionBoundSpec
%type <node>        partbound_datum PartitionRangeDatum
%type <list>        hash_partbound partbound_datum_list range_datum_list
%type <defelt>        hash_partbound_elem
/*
 * Non-keyword token types.  These are hard-wired into the "flex" lexer.
 * They must be listed first so that their numeric codes do not depend on
 * the set of keywords.  PL/pgSQL depends on this so that it can share the
 * same lexer.  If you add/change tokens here, fix PL/pgSQL to match!
 * 非關(guān)鍵字token類型.
 * 這些都被硬鏈接到"flex"的詞法分析器中.
 * 必須首先列出這些token,這樣他們的數(shù)字代碼就不用依賴關(guān)鍵字集合了.
 * PL/pgsQL依賴于該集合以便可以共享相同的詞法分析器.
 * 如果在這里添加/修改tokens,那么注意相應(yīng)的修改PL/pgSQL.
 *
 * DOT_DOT is unused in the core SQL grammar, and so will always provoke
 * parse errors.  It is needed by PL/pgSQL.
 * DOT_DOT在核心SQL語(yǔ)法中不會(huì)使用,因此通常會(huì)提示解析錯(cuò)誤.用于PL/pgSQL.
 */
%token <str>    IDENT FCONST SCONST BCONST XCONST Op
%token <ival>    ICONST PARAM
%token            TYPECAST DOT_DOT COLON_EQUALS EQUALS_GREATER
%token            LESS_EQUALS GREATER_EQUALS NOT_EQUALS
/*
 * If you want to make any keyword changes, update the keyword table in
 * src/include/parser/kwlist.h and add new keywords to the appropriate one
 * of the reserved-or-not-so-reserved keyword lists, below; search
 * this file for "Keyword category lists".
 * 如果希望修改關(guān)鍵字,更新src/include/parser/kwlist.h,
 *   同時(shí)在下面的關(guān)鍵字列表中在合適的位置添加新的關(guān)鍵字.可在文件中搜索"Keyword category lists"
 */
/* ordinary key words in alphabetical order */
//以字母順序排列的普通關(guān)鍵字.
%token <keyword> ABORT_P ABSOLUTE_P ACCESS ACTION ADD_P ADMIN AFTER
    AGGREGATE ALL ALSO ALTER ALWAYS ANAXXXE ANALYZE AND ANY ARRAY AS ASC
    ASSERTION ASSIGNMENT ASYMMETRIC AT ATTACH ATTRIBUTE AUTHORIZATION
    BACKWARD BEFORE BEGIN_P BETWEEN BIGINT BINARY BIT
    BOOLEAN_P BOTH BY
    CACHE CALL CALLED CASCADE CASCADED CASE CAST CATALOG_P CHAIN CHAR_P
    CHARACTER CHARACTERISTICS CHECK CHECKPOINT CLASS CLOSE
    CLUSTER COALESCE COLLATE COLLATION COLUMN COLUMNS COMMENT COMMENTS COMMIT
    COMMITTED CONCURRENTLY CONFIGURATION CONFLICT CONNECTION CONSTRAINT
    CONSTRAINTS CONTENT_P CONTINUE_P CONVERSION_P COPY COST CREATE
    CROSS CSV CUBE CURRENT_P
    CURRENT_CATALOG CURRENT_DATE CURRENT_ROLE CURRENT_SCHEMA
    CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR CYCLE
    DATA_P DATABASE DAY_P DEALLOCATE DEC DECIMAL_P DECLARE DEFAULT DEFAULTS
    DEFERRABLE DEFERRED DEFINER DELETE_P DELIMITER DELIMITERS DEPENDS DESC
    DETACH DICTIONARY DISABLE_P DISCARD DISTINCT DO DOCUMENT_P DOMAIN_P
    DOUBLE_P DROP
    EACH ELSE ENABLE_P ENCODING ENCRYPTED END_P ENUM_P ESCAPE EVENT EXCEPT
    EXCLUDE EXCLUDING EXCLUSIVE EXECUTE EXISTS EXPLAIN
    EXTENSION EXTERNAL EXTRACT
    FALSE_P FAMILY FETCH FILTER FIRST_P FLOAT_P FOLLOWING FOR
    FORCE FOREIGN FORWARD FREEZE FROM FULL FUNCTION FUNCTIONS
    GENERATED GLOBAL GRANT GRANTED GREATEST GROUP_P GROUPING GROUPS
    HANDLER HAVING HEADER_P HOLD HOUR_P
    IDENTITY_P IF_P ILIKE IMMEDIATE IMMUTABLE IMPLICIT_P IMPORT_P IN_P INCLUDE
    INCLUDING INCREMENT INDEX INDEXES INHERIT INHERITS INITIALLY INLINE_P
    INNER_P INOUT INPUT_P INSENSITIVE INSERT INSTEAD INT_P INTEGER
    INTERSECT INTERVAL INTO INVOKER IS ISNULL ISOLATION
    JOIN
    KEY
    LABEL LANGUAGE LARGE_P LAST_P LATERAL_P
    LEADING LEAKPROOF LEAST LEFT LEVEL LIKE LIMIT LISTEN LOAD LOCAL
    LOCALTIME LOCALTIMESTAMP LOCATION LOCK_P LOCKED LOGGED
    MAPPING MATCH MATERIALIZED MAXVALUE METHOD MINUTE_P MINVALUE MODE MONTH_P MOVE
    NAME_P NAMES NATIONAL NATURAL NCHAR NEW NEXT NO NONE
    NOT NOTHING NOTIFY NOTNULL NOWAIT NULL_P NULLIF
    NULLS_P NUMERIC
    OBJECT_P OF OFF OFFSET OIDS OLD ON ONLY OPERATOR OPTION OPTIONS OR
    ORDER ORDINALITY OTHERS OUT_P OUTER_P
    OVER OVERLAPS OVERLAY OVERRIDING OWNED OWNER
    PARALLEL PARSER PARTIAL PARTITION PASSING PASSWORD PLACING PLANS POLICY
    POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
    PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROCEDURES PROGRAM PUBLICATION
    QUOTE
    RANGE READ REAL REASSIGN RECHECK RECURSIVE REF REFERENCES REFERENCING
    REFRESH REINDEX RELATIVE_P RELEASE RENAME REPEATABLE REPLACE REPLICA
    RESET RESTART RESTRICT RETURNING RETURNS REVOKE RIGHT ROLE ROLLBACK ROLLUP
    ROUTINE ROUTINES ROW ROWS RULE
    SAVEPOINT SCHEMA SCHEMAS SCROLL SEARCH SECOND_P SECURITY SELECT SEQUENCE SEQUENCES
    SERIALIZABLE SERVER SESSION SESSION_USER SET SETS SETOF SHARE SHOW
    SIMILAR SIMPLE SKIP SMALLINT SNAPSHOT SOME SQL_P STABLE STANDALONE_P
    START STATEMENT STATISTICS STDIN STDOUT STORAGE STRICT_P STRIP_P
    SUBSCRIPTION SUBSTRING SYMMETRIC SYSID SYSTEM_P
    TABLE TABLES TABLESAMPLE TABLESPACE TEMP TEMPLATE TEMPORARY TEXT_P THEN
    TIES TIME TIMESTAMP TO TRAILING TRANSACTION TRANSFORM
    TREAT TRIGGER TRIM TRUE_P
    TRUNCATE TRUSTED TYPE_P TYPES_P
    UNBOUNDED UNCOMMITTED UNENCRYPTED UNION UNIQUE UNKNOWN UNLISTEN UNLOGGED
    UNTIL UPDATE USER USING
    VACUUM VALID VALIDATE VALIDATOR VALUE_P VALUES VARCHAR VARIADIC VARYING
    VERBOSE VERSION_P VIEW VIEWS VOLATILE
    WHEN WHERE WHITESPACE_P WINDOW WITH WITHIN WITHOUT WORK WRAPPER WRITE
    XML_P XMLATTRIBUTES XMLCONCAT XMLELEMENT XMLEXISTS XMLFOREST XMLNAMESPACES
    XMLPARSE XMLPI XMLROOT XMLSERIALIZE XMLTABLE
    YEAR_P YES_P
    ZONE
/*
 * The grammar thinks these are keywords, but they are not in the kwlist.h
 * list and so can never be entered directly.  The filter in parser.c
 * creates these tokens when required (based on looking one token ahead).
 * 語(yǔ)法分析器認(rèn)為存在關(guān)鍵字,但這些關(guān)鍵字沒(méi)有在kwlist.h中列出,因此永遠(yuǎn)都不能直接進(jìn)入.
 * parser.c中的過(guò)濾器在需要的時(shí)候創(chuàng)建這些tokens(基于提前查看一個(gè)token).
 *
 * NOT_LA exists so that productions such as NOT LIKE can be given the same
 * precedence as LIKE; otherwise they'd effectively have the same precedence
 * as NOT, at least with respect to their left-hand subexpression.
 * NULLS_LA and WITH_LA are needed to make the grammar LALR(1).
 * NOT_LA之所以存在以便諸如NOT LIKE這樣的產(chǎn)生式可與LIKE具備同樣的優(yōu)先順序.
 * 否則它們會(huì)與NOT的優(yōu)先級(jí)一樣,至少對(duì)于他們的左子表達(dá)式如此.
 * NULLS_LA和WITH_LA用于產(chǎn)生LALR(1)語(yǔ)法解析器.
 */
%token        NOT_LA NULLS_LA WITH_LA
/* Precedence: lowest to highest */
//優(yōu)先級(jí):從低到高
%nonassoc    SET                /* see relation_expr_opt_alias */
%left        UNION EXCEPT
%left        INTERSECT
%left        OR
%left        AND
%right        NOT
%nonassoc    IS ISNULL NOTNULL    /* IS sets precedence for IS NULL, etc */
%nonassoc    '<' '>' '=' LESS_EQUALS GREATER_EQUALS NOT_EQUALS
%nonassoc    BETWEEN IN_P LIKE ILIKE SIMILAR NOT_LA
//轉(zhuǎn)義操作
%nonassoc    ESCAPE            /* ESCAPE must be just above LIKE/ILIKE/SIMILAR */
%left        POSTFIXOP        /* dummy for postfix Op rules */
/*
 * To support target_el without AS, we must give IDENT an explicit priority
 * between POSTFIXOP and Op.  We can safely assign the same priority to
 * various unreserved keywords as needed to resolve ambiguities (this can't
 * have any bad effects since obviously the keywords will still behave the
 * same as if they weren't keywords).  We need to do this:
 * for PARTITION, RANGE, ROWS, GROUPS to support opt_existing_window_name;
 * for RANGE, ROWS, GROUPS so that they can follow a_expr without creating
 * postfix-operator problems;
 * for GENERATED so that it can follow b_expr;
 * and for NULL so that it can follow b_expr in ColQualList without creating
 * postfix-operator problems.
 * 為了支持沒(méi)有AS的target_el,必須在POSTFIXOP和Op之間明確的給IDENT一個(gè)顯式的優(yōu)先級(jí).
 * 我們可以根據(jù)需要安全地為各種未保留的關(guān)鍵字分配相同的優(yōu)先級(jí),以解決歧義.
 * (這不會(huì)有什么不好的影響,因?yàn)轱@然的,關(guān)鍵字的行為與它們不是關(guān)鍵字是一樣的).
 * 我們需要做的事情是:
 *   對(duì)于PARTITION, RANGE, ROWS, GROUPS,需要支持opt_existing_window_name;
 *   對(duì)于RANGE, ROWS, GROUPS,以便它們可以跟隨a_expr而不會(huì)產(chǎn)生后綴操作符問(wèn)題;
 *   對(duì)于GENERATED,可以跟隨b_expr;
 *   對(duì)于NULL,可以在ColQualList中跟隨b_expr而不會(huì)產(chǎn)生后綴操作符問(wèn)題;
 *
 * To support CUBE and ROLLUP in GROUP BY without reserving them, we give them
 * an explicit priority lower than '(', so that a rule with CUBE '(' will shift
 * rather than reducing a conflicting rule that takes CUBE as a function name.
 * Using the same precedence as IDENT seems right for the reasons given above.
 * 在GROUP BY中支持CUBE/ROLLUP而無(wú)需保留它們,我們給予它們顯示的優(yōu)先級(jí),要低于字符'(',
 *   這樣存在CUBE '('的規(guī)則會(huì)進(jìn)行狀態(tài)轉(zhuǎn)換而不是把CUBE視為函數(shù)名稱而產(chǎn)生折疊沖突的規(guī)則.
 * 基于以上的理由,使用與IDENT相同的優(yōu)先級(jí)似乎是正確的.
 *
 * The frame_bound productions UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING
 * are even messier: since UNBOUNDED is an unreserved keyword (per spec!),
 * there is no principled way to distinguish these from the productions
 * .  We hack this up by giving UNBOUNDED slightly
 * lower precedence than PRECEDING and FOLLOWING.  At present this doesn't
 * appear to cause UNBOUNDED to be treated differently from other unreserved
 * keywords anywhere else in the grammar, but it's definitely risky.  We can
 * blame any funny behavior of UNBOUNDED on the SQL standard, though.
 * frame_bound產(chǎn)生式UNBOUNDED PRECEDING和UNBOUNDED FOLLOWING更加混亂:
 * 因?yàn)閁NBOUNDED是非保留關(guān)鍵字(per spec!),不存在明確的原則來(lái)區(qū)分產(chǎn)生式.
 * 通過(guò)給UNBOUNDED的優(yōu)先級(jí)比PRECEDING和FOLLOWING更低優(yōu)先級(jí)來(lái)解決此問(wèn)題.
 * 到現(xiàn)在為止,看起來(lái)不會(huì)產(chǎn)生把UNBOUNDED與語(yǔ)法中其他任何地方的非保留關(guān)鍵字區(qū)別對(duì)待,
 *   但這肯定存在風(fēng)險(xiǎn).
 * 不過(guò),我們可以將UNBOUNDED的任何有趣行為歸咎于SQL標(biāo)準(zhǔn)。
 *
 */
//理想的情況下不應(yīng)存在于IDENT相同的優(yōu)先級(jí).
%nonassoc    UNBOUNDED        /* ideally should have same precedence as IDENT */
%nonassoc    IDENT GENERATED NULL_P PARTITION RANGE ROWS GROUPS PRECEDING FOLLOWING CUBE ROLLUP
//多字符組成的操作符和用戶自定義操作符
%left        Op OPERATOR        /* multi-character ops and user-defined operators */
%left        '+' '-'
%left        '*' '/' '%'
%left        '^'
/* Unary Operators */
//一元運(yùn)算符
%left        AT                /* sets precedence for AT TIME ZONE */
%left        COLLATE
%right        UMINUS
%left        '[' ']'
%left        '(' ')'
%left        TYPECAST
%left        '.'
/*
 * These might seem to be low-precedence, but actually they are not part
 * of the arithmetic hierarchy at all in their use as JOIN operators.
 * We make them high-precedence to support their use as function names.
 * They wouldn't be given a precedence at all, were it not that we need
 * left-associativity among the JOIN rules themselves.
 * 這些操作符看起來(lái)優(yōu)先級(jí)比較低,但實(shí)際上在把它們作為連接操作符時(shí),
 *   它們根本不是算術(shù)層次結(jié)構(gòu)的一部分.
 * 提高它們的優(yōu)先級(jí),可以支持將它們用作函數(shù)名稱.
 * 如果我們不需要連接規(guī)則本身的左結(jié)合性,它們根本就不會(huì)被授予優(yōu)先級(jí).
 */
%left        JOIN CROSS LEFT FULL RIGHT INNER_P NATURAL
/* kluge to keep xml_whitespace_option from causing shift/reduce conflicts */
//可防止xml_whitespace_option引起的轉(zhuǎn)移/折疊沖突.
%right        PRESERVE STRIP_P

三、參考資料

Flex&Bison

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI