LCOV - code coverage report
Current view: top level - src/pl/plpgsql/src - pl_gram.y (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 1189 1362 87.3 %
Date: 2019-08-24 16:07:17 Functions: 25 29 86.2 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : %{
       2             : /*-------------------------------------------------------------------------
       3             :  *
       4             :  * pl_gram.y            - Parser for the PL/pgSQL procedural language
       5             :  *
       6             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/pl/plpgsql/src/pl_gram.y
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : 
      16             : #include "postgres.h"
      17             : 
      18             : #include "catalog/namespace.h"
      19             : #include "catalog/pg_proc.h"
      20             : #include "catalog/pg_type.h"
      21             : #include "parser/parser.h"
      22             : #include "parser/parse_type.h"
      23             : #include "parser/scanner.h"
      24             : #include "parser/scansup.h"
      25             : #include "utils/builtins.h"
      26             : 
      27             : #include "plpgsql.h"
      28             : 
      29             : 
      30             : /* Location tracking support --- simpler than bison's default */
      31             : #define YYLLOC_DEFAULT(Current, Rhs, N) \
      32             :     do { \
      33             :         if (N) \
      34             :             (Current) = (Rhs)[1]; \
      35             :         else \
      36             :             (Current) = (Rhs)[0]; \
      37             :     } while (0)
      38             : 
      39             : /*
      40             :  * Bison doesn't allocate anything that needs to live across parser calls,
      41             :  * so we can easily have it use palloc instead of malloc.  This prevents
      42             :  * memory leaks if we error out during parsing.  Note this only works with
      43             :  * bison >= 2.0.  However, in bison 1.875 the default is to use alloca()
      44             :  * if possible, so there's not really much problem anyhow, at least if
      45             :  * you're building with gcc.
      46             :  */
      47             : #define YYMALLOC palloc
      48             : #define YYFREE   pfree
      49             : 
      50             : 
      51             : typedef struct
      52             : {
      53             :     int         location;
      54             :     int         leaderlen;
      55             : } sql_error_callback_arg;
      56             : 
      57             : #define parser_errposition(pos)  plpgsql_scanner_errposition(pos)
      58             : 
      59             : union YYSTYPE;                  /* need forward reference for tok_is_keyword */
      60             : 
      61             : static  bool            tok_is_keyword(int token, union YYSTYPE *lval,
      62             :                                        int kw_token, const char *kw_str);
      63             : static  void            word_is_not_variable(PLword *word, int location);
      64             : static  void            cword_is_not_variable(PLcword *cword, int location);
      65             : static  void            current_token_is_not_variable(int tok);
      66             : static  PLpgSQL_expr    *read_sql_construct(int until,
      67             :                                             int until2,
      68             :                                             int until3,
      69             :                                             const char *expected,
      70             :                                             const char *sqlstart,
      71             :                                             bool isexpression,
      72             :                                             bool valid_sql,
      73             :                                             bool trim,
      74             :                                             int *startloc,
      75             :                                             int *endtoken);
      76             : static  PLpgSQL_expr    *read_sql_expression(int until,
      77             :                                              const char *expected);
      78             : static  PLpgSQL_expr    *read_sql_expression2(int until, int until2,
      79             :                                               const char *expected,
      80             :                                               int *endtoken);
      81             : static  PLpgSQL_expr    *read_sql_stmt(const char *sqlstart);
      82             : static  PLpgSQL_type    *read_datatype(int tok);
      83             : static  PLpgSQL_stmt    *make_execsql_stmt(int firsttoken, int location);
      84             : static  PLpgSQL_stmt_fetch *read_fetch_direction(void);
      85             : static  void             complete_direction(PLpgSQL_stmt_fetch *fetch,
      86             :                                             bool *check_FROM);
      87             : static  PLpgSQL_stmt    *make_return_stmt(int location);
      88             : static  PLpgSQL_stmt    *make_return_next_stmt(int location);
      89             : static  PLpgSQL_stmt    *make_return_query_stmt(int location);
      90             : static  PLpgSQL_stmt    *make_case(int location, PLpgSQL_expr *t_expr,
      91             :                                    List *case_when_list, List *else_stmts);
      92             : static  char            *NameOfDatum(PLwdatum *wdatum);
      93             : static  void             check_assignable(PLpgSQL_datum *datum, int location);
      94             : static  void             read_into_target(PLpgSQL_variable **target,
      95             :                                           bool *strict);
      96             : static  PLpgSQL_row     *read_into_scalar_list(char *initial_name,
      97             :                                                PLpgSQL_datum *initial_datum,
      98             :                                                int initial_location);
      99             : static  PLpgSQL_row     *make_scalar_list1(char *initial_name,
     100             :                                            PLpgSQL_datum *initial_datum,
     101             :                                            int lineno, int location);
     102             : static  void             check_sql_expr(const char *stmt, int location,
     103             :                                         int leaderlen);
     104             : static  void             plpgsql_sql_error_callback(void *arg);
     105             : static  PLpgSQL_type    *parse_datatype(const char *string, int location);
     106             : static  void             check_labels(const char *start_label,
     107             :                                       const char *end_label,
     108             :                                       int end_location);
     109             : static  PLpgSQL_expr    *read_cursor_args(PLpgSQL_var *cursor,
     110             :                                           int until, const char *expected);
     111             : static  List            *read_raise_options(void);
     112             : static  void            check_raise_parameters(PLpgSQL_stmt_raise *stmt);
     113             : 
     114             : %}
     115             : 
     116             : %expect 0
     117             : %name-prefix="plpgsql_yy"
     118             : %locations
     119             : 
     120             : %union {
     121             :         core_YYSTYPE            core_yystype;
     122             :         /* these fields must match core_YYSTYPE: */
     123             :         int                     ival;
     124             :         char                    *str;
     125             :         const char              *keyword;
     126             : 
     127             :         PLword                  word;
     128             :         PLcword                 cword;
     129             :         PLwdatum                wdatum;
     130             :         bool                    boolean;
     131             :         Oid                     oid;
     132             :         struct
     133             :         {
     134             :             char *name;
     135             :             int  lineno;
     136             :         }                       varname;
     137             :         struct
     138             :         {
     139             :             char *name;
     140             :             int  lineno;
     141             :             PLpgSQL_datum   *scalar;
     142             :             PLpgSQL_datum   *row;
     143             :         }                       forvariable;
     144             :         struct
     145             :         {
     146             :             char *label;
     147             :             int  n_initvars;
     148             :             int  *initvarnos;
     149             :         }                       declhdr;
     150             :         struct
     151             :         {
     152             :             List *stmts;
     153             :             char *end_label;
     154             :             int   end_label_location;
     155             :         }                       loop_body;
     156             :         List                    *list;
     157             :         PLpgSQL_type            *dtype;
     158             :         PLpgSQL_datum           *datum;
     159             :         PLpgSQL_var             *var;
     160             :         PLpgSQL_expr            *expr;
     161             :         PLpgSQL_stmt            *stmt;
     162             :         PLpgSQL_condition       *condition;
     163             :         PLpgSQL_exception       *exception;
     164             :         PLpgSQL_exception_block *exception_block;
     165             :         PLpgSQL_nsitem          *nsitem;
     166             :         PLpgSQL_diag_item       *diagitem;
     167             :         PLpgSQL_stmt_fetch      *fetch;
     168             :         PLpgSQL_case_when       *casewhen;
     169             : }
     170             : 
     171             : %type <declhdr> decl_sect
     172             : %type <varname> decl_varname
     173             : %type <boolean>   decl_const decl_notnull exit_type
     174             : %type <expr>  decl_defval decl_cursor_query
     175             : %type <dtype> decl_datatype
     176             : %type <oid>       decl_collate
     177             : %type <datum> decl_cursor_args
     178             : %type <list>  decl_cursor_arglist
     179             : %type <nsitem>    decl_aliasitem
     180             : 
     181             : %type <expr>  expr_until_semi expr_until_rightbracket
     182             : %type <expr>  expr_until_then expr_until_loop opt_expr_until_when
     183             : %type <expr>  opt_exitcond
     184             : 
     185             : %type <datum> assign_var
     186             : %type <var>       cursor_variable
     187             : %type <datum> decl_cursor_arg
     188             : %type <forvariable>   for_variable
     189             : %type <ival>  foreach_slice
     190             : %type <stmt>  for_control
     191             : 
     192             : %type <str>       any_identifier opt_block_label opt_loop_label opt_label
     193             : %type <str>       option_value
     194             : 
     195             : %type <list>  proc_sect stmt_elsifs stmt_else
     196             : %type <loop_body> loop_body
     197             : %type <stmt>  proc_stmt pl_block
     198             : %type <stmt>  stmt_assign stmt_if stmt_loop stmt_while stmt_exit
     199             : %type <stmt>  stmt_return stmt_raise stmt_assert stmt_execsql
     200             : %type <stmt>  stmt_dynexecute stmt_for stmt_perform stmt_call stmt_getdiag
     201             : %type <stmt>  stmt_open stmt_fetch stmt_move stmt_close stmt_null
     202             : %type <stmt>  stmt_commit stmt_rollback stmt_set
     203             : %type <stmt>  stmt_case stmt_foreach_a
     204             : 
     205             : %type <list>  proc_exceptions
     206             : %type <exception_block> exception_sect
     207             : %type <exception> proc_exception
     208             : %type <condition> proc_conditions proc_condition
     209             : 
     210             : %type <casewhen>  case_when
     211             : %type <list>  case_when_list opt_case_else
     212             : 
     213             : %type <boolean>   getdiag_area_opt
     214             : %type <list>  getdiag_list
     215             : %type <diagitem> getdiag_list_item
     216             : %type <datum> getdiag_target
     217             : %type <ival>  getdiag_item
     218             : 
     219             : %type <ival>  opt_scrollable
     220             : %type <fetch> opt_fetch_direction
     221             : 
     222             : %type <ival>  opt_transaction_chain
     223             : 
     224             : %type <keyword>   unreserved_keyword
     225             : 
     226             : 
     227             : /*
     228             :  * Basic non-keyword token types.  These are hard-wired into the core lexer.
     229             :  * They must be listed first so that their numeric codes do not depend on
     230             :  * the set of keywords.  Keep this list in sync with backend/parser/gram.y!
     231             :  *
     232             :  * Some of these are not directly referenced in this file, but they must be
     233             :  * here anyway.
     234             :  */
     235             : %token <str>  IDENT FCONST SCONST BCONST XCONST Op
     236             : %token <ival> ICONST PARAM
     237             : %token          TYPECAST DOT_DOT COLON_EQUALS EQUALS_GREATER
     238             : %token          LESS_EQUALS GREATER_EQUALS NOT_EQUALS
     239             : 
     240             : /*
     241             :  * Other tokens recognized by plpgsql's lexer interface layer (pl_scanner.c).
     242             :  */
     243             : %token <word>     T_WORD      /* unrecognized simple identifier */
     244             : %token <cword>        T_CWORD     /* unrecognized composite identifier */
     245             : %token <wdatum>       T_DATUM     /* a VAR, ROW, REC, or RECFIELD variable */
     246             : %token              LESS_LESS
     247             : %token              GREATER_GREATER
     248             : 
     249             : /*
     250             :  * Keyword tokens.  Some of these are reserved and some are not;
     251             :  * see pl_scanner.c for info.  Be sure unreserved keywords are listed
     252             :  * in the "unreserved_keyword" production below.
     253             :  */
     254             : %token <keyword>  K_ABSOLUTE
     255             : %token <keyword>  K_ALIAS
     256             : %token <keyword>  K_ALL
     257             : %token <keyword>  K_AND
     258             : %token <keyword>  K_ARRAY
     259             : %token <keyword>  K_ASSERT
     260             : %token <keyword>  K_BACKWARD
     261             : %token <keyword>  K_BEGIN
     262             : %token <keyword>  K_BY
     263             : %token <keyword>  K_CALL
     264             : %token <keyword>  K_CASE
     265             : %token <keyword>  K_CHAIN
     266             : %token <keyword>  K_CLOSE
     267             : %token <keyword>  K_COLLATE
     268             : %token <keyword>  K_COLUMN
     269             : %token <keyword>  K_COLUMN_NAME
     270             : %token <keyword>  K_COMMIT
     271             : %token <keyword>  K_CONSTANT
     272             : %token <keyword>  K_CONSTRAINT
     273             : %token <keyword>  K_CONSTRAINT_NAME
     274             : %token <keyword>  K_CONTINUE
     275             : %token <keyword>  K_CURRENT
     276             : %token <keyword>  K_CURSOR
     277             : %token <keyword>  K_DATATYPE
     278             : %token <keyword>  K_DEBUG
     279             : %token <keyword>  K_DECLARE
     280             : %token <keyword>  K_DEFAULT
     281             : %token <keyword>  K_DETAIL
     282             : %token <keyword>  K_DIAGNOSTICS
     283             : %token <keyword>  K_DO
     284             : %token <keyword>  K_DUMP
     285             : %token <keyword>  K_ELSE
     286             : %token <keyword>  K_ELSIF
     287             : %token <keyword>  K_END
     288             : %token <keyword>  K_ERRCODE
     289             : %token <keyword>  K_ERROR
     290             : %token <keyword>  K_EXCEPTION
     291             : %token <keyword>  K_EXECUTE
     292             : %token <keyword>  K_EXIT
     293             : %token <keyword>  K_FETCH
     294             : %token <keyword>  K_FIRST
     295             : %token <keyword>  K_FOR
     296             : %token <keyword>  K_FOREACH
     297             : %token <keyword>  K_FORWARD
     298             : %token <keyword>  K_FROM
     299             : %token <keyword>  K_GET
     300             : %token <keyword>  K_HINT
     301             : %token <keyword>  K_IF
     302             : %token <keyword>  K_IMPORT
     303             : %token <keyword>  K_IN
     304             : %token <keyword>  K_INFO
     305             : %token <keyword>  K_INSERT
     306             : %token <keyword>  K_INTO
     307             : %token <keyword>  K_IS
     308             : %token <keyword>  K_LAST
     309             : %token <keyword>  K_LOG
     310             : %token <keyword>  K_LOOP
     311             : %token <keyword>  K_MESSAGE
     312             : %token <keyword>  K_MESSAGE_TEXT
     313             : %token <keyword>  K_MOVE
     314             : %token <keyword>  K_NEXT
     315             : %token <keyword>  K_NO
     316             : %token <keyword>  K_NOT
     317             : %token <keyword>  K_NOTICE
     318             : %token <keyword>  K_NULL
     319             : %token <keyword>  K_OPEN
     320             : %token <keyword>  K_OPTION
     321             : %token <keyword>  K_OR
     322             : %token <keyword>  K_PERFORM
     323             : %token <keyword>  K_PG_CONTEXT
     324             : %token <keyword>  K_PG_DATATYPE_NAME
     325             : %token <keyword>  K_PG_EXCEPTION_CONTEXT
     326             : %token <keyword>  K_PG_EXCEPTION_DETAIL
     327             : %token <keyword>  K_PG_EXCEPTION_HINT
     328             : %token <keyword>  K_PRINT_STRICT_PARAMS
     329             : %token <keyword>  K_PRIOR
     330             : %token <keyword>  K_QUERY
     331             : %token <keyword>  K_RAISE
     332             : %token <keyword>  K_RELATIVE
     333             : %token <keyword>  K_RESET
     334             : %token <keyword>  K_RETURN
     335             : %token <keyword>  K_RETURNED_SQLSTATE
     336             : %token <keyword>  K_REVERSE
     337             : %token <keyword>  K_ROLLBACK
     338             : %token <keyword>  K_ROW_COUNT
     339             : %token <keyword>  K_ROWTYPE
     340             : %token <keyword>  K_SCHEMA
     341             : %token <keyword>  K_SCHEMA_NAME
     342             : %token <keyword>  K_SCROLL
     343             : %token <keyword>  K_SET
     344             : %token <keyword>  K_SLICE
     345             : %token <keyword>  K_SQLSTATE
     346             : %token <keyword>  K_STACKED
     347             : %token <keyword>  K_STRICT
     348             : %token <keyword>  K_TABLE
     349             : %token <keyword>  K_TABLE_NAME
     350             : %token <keyword>  K_THEN
     351             : %token <keyword>  K_TO
     352             : %token <keyword>  K_TYPE
     353             : %token <keyword>  K_USE_COLUMN
     354             : %token <keyword>  K_USE_VARIABLE
     355             : %token <keyword>  K_USING
     356             : %token <keyword>  K_VARIABLE_CONFLICT
     357             : %token <keyword>  K_WARNING
     358             : %token <keyword>  K_WHEN
     359             : %token <keyword>  K_WHILE
     360             : 
     361             : %%
     362             : 
     363             : pl_function     : comp_options pl_block opt_semi
     364             :                     {
     365        3616 :                         plpgsql_parse_result = (PLpgSQL_stmt_block *) $2;
     366             :                     }
     367             :                 ;
     368             : 
     369             : comp_options    :
     370             :                 | comp_options comp_option
     371             :                 ;
     372             : 
     373             : comp_option     : '#' K_OPTION K_DUMP
     374             :                     {
     375           0 :                         plpgsql_DumpExecTree = true;
     376             :                     }
     377             :                 | '#' K_PRINT_STRICT_PARAMS option_value
     378             :                     {
     379           8 :                         if (strcmp($3, "on") == 0)
     380           4 :                             plpgsql_curr_compile->print_strict_params = true;
     381           4 :                         else if (strcmp($3, "off") == 0)
     382           4 :                             plpgsql_curr_compile->print_strict_params = false;
     383             :                         else
     384           0 :                             elog(ERROR, "unrecognized print_strict_params option %s", $3);
     385             :                     }
     386             :                 | '#' K_VARIABLE_CONFLICT K_ERROR
     387             :                     {
     388           0 :                         plpgsql_curr_compile->resolve_option = PLPGSQL_RESOLVE_ERROR;
     389             :                     }
     390             :                 | '#' K_VARIABLE_CONFLICT K_USE_VARIABLE
     391             :                     {
     392           4 :                         plpgsql_curr_compile->resolve_option = PLPGSQL_RESOLVE_VARIABLE;
     393             :                     }
     394             :                 | '#' K_VARIABLE_CONFLICT K_USE_COLUMN
     395             :                     {
     396           4 :                         plpgsql_curr_compile->resolve_option = PLPGSQL_RESOLVE_COLUMN;
     397             :                     }
     398             :                 ;
     399             : 
     400             : option_value : T_WORD
     401             :                 {
     402           8 :                     $$ = $1.ident;
     403             :                 }
     404             :              | unreserved_keyword
     405             :                 {
     406           0 :                     $$ = pstrdup($1);
     407             :                 }
     408             : 
     409             : opt_semi        :
     410             :                 | ';'
     411             :                 ;
     412             : 
     413             : pl_block        : decl_sect K_BEGIN proc_sect exception_sect K_END opt_label
     414             :                     {
     415             :                         PLpgSQL_stmt_block *new;
     416             : 
     417        3750 :                         new = palloc0(sizeof(PLpgSQL_stmt_block));
     418             : 
     419        3750 :                         new->cmd_type    = PLPGSQL_STMT_BLOCK;
     420        3750 :                         new->lineno      = plpgsql_location_to_lineno(@2);
     421        3750 :                         new->stmtid      = ++plpgsql_curr_compile->nstatements;
     422        3750 :                         new->label       = $1.label;
     423        3750 :                         new->n_initvars = $1.n_initvars;
     424        3750 :                         new->initvarnos = $1.initvarnos;
     425        3750 :                         new->body        = $3;
     426        3750 :                         new->exceptions  = $4;
     427             : 
     428        3750 :                         check_labels($1.label, $6, @6);
     429        3750 :                         plpgsql_ns_pop();
     430             : 
     431        3750 :                         $$ = (PLpgSQL_stmt *)new;
     432             :                     }
     433             :                 ;
     434             : 
     435             : 
     436             : decl_sect       : opt_block_label
     437             :                     {
     438             :                         /* done with decls, so resume identifier lookup */
     439        2476 :                         plpgsql_IdentifierLookup = IDENTIFIER_LOOKUP_NORMAL;
     440        2476 :                         $$.label      = $1;
     441        2476 :                         $$.n_initvars = 0;
     442        2476 :                         $$.initvarnos = NULL;
     443             :                     }
     444             :                 | opt_block_label decl_start
     445             :                     {
     446           4 :                         plpgsql_IdentifierLookup = IDENTIFIER_LOOKUP_NORMAL;
     447           4 :                         $$.label      = $1;
     448           4 :                         $$.n_initvars = 0;
     449           4 :                         $$.initvarnos = NULL;
     450             :                     }
     451             :                 | opt_block_label decl_start decl_stmts
     452             :                     {
     453        1366 :                         plpgsql_IdentifierLookup = IDENTIFIER_LOOKUP_NORMAL;
     454        1366 :                         $$.label      = $1;
     455             :                         /* Remember variables declared in decl_stmts */
     456        1366 :                         $$.n_initvars = plpgsql_add_initdatums(&($$.initvarnos));
     457             :                     }
     458             :                 ;
     459             : 
     460             : decl_start      : K_DECLARE
     461             :                     {
     462             :                         /* Forget any variables created before block */
     463        1382 :                         plpgsql_add_initdatums(NULL);
     464             :                         /*
     465             :                          * Disable scanner lookup of identifiers while
     466             :                          * we process the decl_stmts
     467             :                          */
     468        1382 :                         plpgsql_IdentifierLookup = IDENTIFIER_LOOKUP_DECLARE;
     469             :                     }
     470             :                 ;
     471             : 
     472             : decl_stmts      : decl_stmts decl_stmt
     473             :                 | decl_stmt
     474             :                 ;
     475             : 
     476             : decl_stmt       : decl_statement
     477             :                 | K_DECLARE
     478             :                     {
     479             :                         /* We allow useless extra DECLAREs */
     480             :                     }
     481             :                 | LESS_LESS any_identifier GREATER_GREATER
     482             :                     {
     483             :                         /*
     484             :                          * Throw a helpful error if user tries to put block
     485             :                          * label just before BEGIN, instead of before DECLARE.
     486             :                          */
     487           0 :                         ereport(ERROR,
     488             :                                 (errcode(ERRCODE_SYNTAX_ERROR),
     489             :                                  errmsg("block label must be placed before DECLARE, not after"),
     490             :                                  parser_errposition(@1)));
     491             :                     }
     492             :                 ;
     493             : 
     494             : decl_statement  : decl_varname decl_const decl_datatype decl_collate decl_notnull decl_defval
     495             :                     {
     496             :                         PLpgSQL_variable    *var;
     497             : 
     498             :                         /*
     499             :                          * If a collation is supplied, insert it into the
     500             :                          * datatype.  We assume decl_datatype always returns
     501             :                          * a freshly built struct not shared with other
     502             :                          * variables.
     503             :                          */
     504        2208 :                         if (OidIsValid($4))
     505             :                         {
     506           0 :                             if (!OidIsValid($3->collation))
     507           0 :                                 ereport(ERROR,
     508             :                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
     509             :                                          errmsg("collations are not supported by type %s",
     510             :                                                 format_type_be($3->typoid)),
     511             :                                          parser_errposition(@4)));
     512           0 :                             $3->collation = $4;
     513             :                         }
     514             : 
     515        2208 :                         var = plpgsql_build_variable($1.name, $1.lineno,
     516        2208 :                                                      $3, true);
     517        2208 :                         var->isconst = $2;
     518        2208 :                         var->notnull = $5;
     519        2208 :                         var->default_val = $6;
     520             : 
     521             :                         /*
     522             :                          * The combination of NOT NULL without an initializer
     523             :                          * can't work, so let's reject it at compile time.
     524             :                          */
     525        2208 :                         if (var->notnull && var->default_val == NULL)
     526           6 :                             ereport(ERROR,
     527             :                                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
     528             :                                      errmsg("variable \"%s\" must have a default value, since it's declared NOT NULL",
     529             :                                             var->refname),
     530             :                                      parser_errposition(@5)));
     531             :                     }
     532             :                 | decl_varname K_ALIAS K_FOR decl_aliasitem ';'
     533             :                     {
     534          56 :                         plpgsql_ns_additem($4->itemtype,
     535          56 :                                            $4->itemno, $1.name);
     536             :                     }
     537             :                 | decl_varname opt_scrollable K_CURSOR
     538          72 :                     { plpgsql_ns_push($1.name, PLPGSQL_LABEL_OTHER); }
     539             :                   decl_cursor_args decl_is_for decl_cursor_query
     540             :                     {
     541             :                         PLpgSQL_var *new;
     542             :                         PLpgSQL_expr *curname_def;
     543             :                         char        buf[1024];
     544             :                         char        *cp1;
     545             :                         char        *cp2;
     546             : 
     547             :                         /* pop local namespace for cursor args */
     548          72 :                         plpgsql_ns_pop();
     549             : 
     550          72 :                         new = (PLpgSQL_var *)
     551          72 :                             plpgsql_build_variable($1.name, $1.lineno,
     552             :                                                    plpgsql_build_datatype(REFCURSOROID,
     553             :                                                                           -1,
     554             :                                                                           InvalidOid,
     555             :                                                                           NULL),
     556             :                                                    true);
     557             : 
     558          72 :                         curname_def = palloc0(sizeof(PLpgSQL_expr));
     559             : 
     560          72 :                         strcpy(buf, "SELECT ");
     561          72 :                         cp1 = new->refname;
     562          72 :                         cp2 = buf + strlen(buf);
     563             :                         /*
     564             :                          * Don't trust standard_conforming_strings here;
     565             :                          * it might change before we use the string.
     566             :                          */
     567          72 :                         if (strchr(cp1, '\\') != NULL)
     568           0 :                             *cp2++ = ESCAPE_STRING_SYNTAX;
     569          72 :                         *cp2++ = '\'';
     570         264 :                         while (*cp1)
     571             :                         {
     572         120 :                             if (SQL_STR_DOUBLE(*cp1, true))
     573           0 :                                 *cp2++ = *cp1;
     574         120 :                             *cp2++ = *cp1++;
     575             :                         }
     576          72 :                         strcpy(cp2, "'::pg_catalog.refcursor");
     577          72 :                         curname_def->query = pstrdup(buf);
     578          72 :                         new->default_val = curname_def;
     579             : 
     580          72 :                         new->cursor_explicit_expr = $7;
     581          72 :                         if ($5 == NULL)
     582          24 :                             new->cursor_explicit_argrow = -1;
     583             :                         else
     584          48 :                             new->cursor_explicit_argrow = $5->dno;
     585          72 :                         new->cursor_options = CURSOR_OPT_FAST_PLAN | $2;
     586             :                     }
     587             :                 ;
     588             : 
     589             : opt_scrollable :
     590             :                     {
     591          64 :                         $$ = 0;
     592             :                     }
     593             :                 | K_NO K_SCROLL
     594             :                     {
     595           4 :                         $$ = CURSOR_OPT_NO_SCROLL;
     596             :                     }
     597             :                 | K_SCROLL
     598             :                     {
     599           4 :                         $$ = CURSOR_OPT_SCROLL;
     600             :                     }
     601             :                 ;
     602             : 
     603             : decl_cursor_query :
     604             :                     {
     605          72 :                         $$ = read_sql_stmt("");
     606             :                     }
     607             :                 ;
     608             : 
     609             : decl_cursor_args :
     610             :                     {
     611          24 :                         $$ = NULL;
     612             :                     }
     613             :                 | '(' decl_cursor_arglist ')'
     614             :                     {
     615             :                         PLpgSQL_row *new;
     616             :                         int i;
     617             :                         ListCell *l;
     618             : 
     619          48 :                         new = palloc0(sizeof(PLpgSQL_row));
     620          48 :                         new->dtype = PLPGSQL_DTYPE_ROW;
     621          48 :                         new->refname = "(unnamed row)";
     622          48 :                         new->lineno = plpgsql_location_to_lineno(@1);
     623          48 :                         new->rowtupdesc = NULL;
     624          48 :                         new->nfields = list_length($2);
     625          48 :                         new->fieldnames = palloc(new->nfields * sizeof(char *));
     626          48 :                         new->varnos = palloc(new->nfields * sizeof(int));
     627             : 
     628          48 :                         i = 0;
     629         144 :                         foreach (l, $2)
     630             :                         {
     631          96 :                             PLpgSQL_variable *arg = (PLpgSQL_variable *) lfirst(l);
     632             :                             Assert(!arg->isconst);
     633          96 :                             new->fieldnames[i] = arg->refname;
     634          96 :                             new->varnos[i] = arg->dno;
     635          96 :                             i++;
     636             :                         }
     637          48 :                         list_free($2);
     638             : 
     639          48 :                         plpgsql_adddatum((PLpgSQL_datum *) new);
     640          48 :                         $$ = (PLpgSQL_datum *) new;
     641             :                     }
     642             :                 ;
     643             : 
     644             : decl_cursor_arglist : decl_cursor_arg
     645             :                     {
     646          48 :                         $$ = list_make1($1);
     647             :                     }
     648             :                 | decl_cursor_arglist ',' decl_cursor_arg
     649             :                     {
     650          48 :                         $$ = lappend($1, $3);
     651             :                     }
     652             :                 ;
     653             : 
     654             : decl_cursor_arg : decl_varname decl_datatype
     655             :                     {
     656          96 :                         $$ = (PLpgSQL_datum *)
     657          96 :                             plpgsql_build_variable($1.name, $1.lineno,
     658             :                                                    $2, true);
     659             :                     }
     660             :                 ;
     661             : 
     662             : decl_is_for     :   K_IS |      /* Oracle */
     663             :                     K_FOR;      /* SQL standard */
     664             : 
     665             : decl_aliasitem  : T_WORD
     666             :                     {
     667             :                         PLpgSQL_nsitem *nsi;
     668             : 
     669          56 :                         nsi = plpgsql_ns_lookup(plpgsql_ns_top(), false,
     670          56 :                                                 $1.ident, NULL, NULL,
     671             :                                                 NULL);
     672          56 :                         if (nsi == NULL)
     673           0 :                             ereport(ERROR,
     674             :                                     (errcode(ERRCODE_UNDEFINED_OBJECT),
     675             :                                      errmsg("variable \"%s\" does not exist",
     676             :                                             $1.ident),
     677             :                                      parser_errposition(@1)));
     678          56 :                         $$ = nsi;
     679             :                     }
     680             :                 | unreserved_keyword
     681             :                     {
     682             :                         PLpgSQL_nsitem *nsi;
     683             : 
     684           0 :                         nsi = plpgsql_ns_lookup(plpgsql_ns_top(), false,
     685             :                                                 $1, NULL, NULL,
     686             :                                                 NULL);
     687           0 :                         if (nsi == NULL)
     688           0 :                             ereport(ERROR,
     689             :                                     (errcode(ERRCODE_UNDEFINED_OBJECT),
     690             :                                      errmsg("variable \"%s\" does not exist",
     691             :                                             $1),
     692             :                                      parser_errposition(@1)));
     693           0 :                         $$ = nsi;
     694             :                     }
     695             :                 | T_CWORD
     696             :                     {
     697             :                         PLpgSQL_nsitem *nsi;
     698             : 
     699           0 :                         if (list_length($1.idents) == 2)
     700           0 :                             nsi = plpgsql_ns_lookup(plpgsql_ns_top(), false,
     701           0 :                                                     strVal(linitial($1.idents)),
     702           0 :                                                     strVal(lsecond($1.idents)),
     703             :                                                     NULL,
     704             :                                                     NULL);
     705           0 :                         else if (list_length($1.idents) == 3)
     706           0 :                             nsi = plpgsql_ns_lookup(plpgsql_ns_top(), false,
     707           0 :                                                     strVal(linitial($1.idents)),
     708           0 :                                                     strVal(lsecond($1.idents)),
     709           0 :                                                     strVal(lthird($1.idents)),
     710             :                                                     NULL);
     711             :                         else
     712           0 :                             nsi = NULL;
     713           0 :                         if (nsi == NULL)
     714           0 :                             ereport(ERROR,
     715             :                                     (errcode(ERRCODE_UNDEFINED_OBJECT),
     716             :                                      errmsg("variable \"%s\" does not exist",
     717             :                                             NameListToString($1.idents)),
     718             :                                      parser_errposition(@1)));
     719           0 :                         $$ = nsi;
     720             :                     }
     721             :                 ;
     722             : 
     723             : decl_varname    : T_WORD
     724             :                     {
     725        2422 :                         $$.name = $1.ident;
     726        2422 :                         $$.lineno = plpgsql_location_to_lineno(@1);
     727             :                         /*
     728             :                          * Check to make sure name isn't already declared
     729             :                          * in the current block.
     730             :                          */
     731        2422 :                         if (plpgsql_ns_lookup(plpgsql_ns_top(), true,
     732        2422 :                                               $1.ident, NULL, NULL,
     733             :                                               NULL) != NULL)
     734           0 :                             yyerror("duplicate declaration");
     735             : 
     736        4796 :                         if (plpgsql_curr_compile->extra_warnings & PLPGSQL_XCHECK_SHADOWVAR ||
     737        2374 :                             plpgsql_curr_compile->extra_errors & PLPGSQL_XCHECK_SHADOWVAR)
     738             :                         {
     739             :                             PLpgSQL_nsitem *nsi;
     740          48 :                             nsi = plpgsql_ns_lookup(plpgsql_ns_top(), false,
     741          48 :                                                     $1.ident, NULL, NULL, NULL);
     742          48 :                             if (nsi != NULL)
     743          36 :                                 ereport(plpgsql_curr_compile->extra_errors & PLPGSQL_XCHECK_SHADOWVAR ? ERROR : WARNING,
     744             :                                         (errcode(ERRCODE_DUPLICATE_ALIAS),
     745             :                                          errmsg("variable \"%s\" shadows a previously defined variable",
     746             :                                                 $1.ident),
     747             :                                          parser_errposition(@1)));
     748             :                         }
     749             : 
     750             :                     }
     751             :                 | unreserved_keyword
     752             :                     {
     753          16 :                         $$.name = pstrdup($1);
     754          16 :                         $$.lineno = plpgsql_location_to_lineno(@1);
     755             :                         /*
     756             :                          * Check to make sure name isn't already declared
     757             :                          * in the current block.
     758             :                          */
     759          16 :                         if (plpgsql_ns_lookup(plpgsql_ns_top(), true,
     760             :                                               $1, NULL, NULL,
     761             :                                               NULL) != NULL)
     762           0 :                             yyerror("duplicate declaration");
     763             : 
     764          32 :                         if (plpgsql_curr_compile->extra_warnings & PLPGSQL_XCHECK_SHADOWVAR ||
     765          16 :                             plpgsql_curr_compile->extra_errors & PLPGSQL_XCHECK_SHADOWVAR)
     766             :                         {
     767             :                             PLpgSQL_nsitem *nsi;
     768           0 :                             nsi = plpgsql_ns_lookup(plpgsql_ns_top(), false,
     769             :                                                     $1, NULL, NULL, NULL);
     770           0 :                             if (nsi != NULL)
     771           0 :                                 ereport(plpgsql_curr_compile->extra_errors & PLPGSQL_XCHECK_SHADOWVAR ? ERROR : WARNING,
     772             :                                         (errcode(ERRCODE_DUPLICATE_ALIAS),
     773             :                                          errmsg("variable \"%s\" shadows a previously defined variable",
     774             :                                                 $1),
     775             :                                          parser_errposition(@1)));
     776             :                         }
     777             : 
     778             :                     }
     779             :                 ;
     780             : 
     781             : decl_const      :
     782        2196 :                     { $$ = false; }
     783             :                 | K_CONSTANT
     784          14 :                     { $$ = true; }
     785             :                 ;
     786             : 
     787             : decl_datatype   :
     788             :                     {
     789             :                         /*
     790             :                          * If there's a lookahead token, read_datatype
     791             :                          * should consume it.
     792             :                          */
     793        2306 :                         $$ = read_datatype(yychar);
     794        2304 :                         yyclearin;
     795             :                     }
     796             :                 ;
     797             : 
     798             : decl_collate    :
     799        2208 :                     { $$ = InvalidOid; }
     800             :                 | K_COLLATE T_WORD
     801             :                     {
     802           0 :                         $$ = get_collation_oid(list_make1(makeString($2.ident)),
     803             :                                                false);
     804             :                     }
     805             :                 | K_COLLATE unreserved_keyword
     806             :                     {
     807           0 :                         $$ = get_collation_oid(list_make1(makeString(pstrdup($2))),
     808             :                                                false);
     809             :                     }
     810             :                 | K_COLLATE T_CWORD
     811             :                     {
     812           0 :                         $$ = get_collation_oid($2.idents, false);
     813             :                     }
     814             :                 ;
     815             : 
     816             : decl_notnull    :
     817        2186 :                     { $$ = false; }
     818             :                 | K_NOT K_NULL
     819          22 :                     { $$ = true; }
     820             :                 ;
     821             : 
     822             : decl_defval     : ';'
     823        1828 :                     { $$ = NULL; }
     824             :                 | decl_defkey
     825             :                     {
     826         380 :                         $$ = read_sql_expression(';', ";");
     827             :                     }
     828             :                 ;
     829             : 
     830             : decl_defkey     : assign_operator
     831             :                 | K_DEFAULT
     832             :                 ;
     833             : 
     834             : /*
     835             :  * Ada-based PL/SQL uses := for assignment and variable defaults, while
     836             :  * the SQL standard uses equals for these cases and for GET
     837             :  * DIAGNOSTICS, so we support both.  FOR and OPEN only support :=.
     838             :  */
     839             : assign_operator : '='
     840             :                 | COLON_EQUALS
     841             :                 ;
     842             : 
     843             : proc_sect       :
     844        7780 :                     { $$ = NIL; }
     845             :                 | proc_sect proc_stmt
     846             :                     {
     847             :                         /* don't bother linking null statements into list */
     848       14874 :                         if ($2 == NULL)
     849          20 :                             $$ = $1;
     850             :                         else
     851       14854 :                             $$ = lappend($1, $2);
     852             :                     }
     853             :                 ;
     854             : 
     855             : proc_stmt       : pl_block ';'
     856         134 :                         { $$ = $1; }
     857             :                 | stmt_assign
     858        2060 :                         { $$ = $1; }
     859             :                 | stmt_if
     860        2708 :                         { $$ = $1; }
     861             :                 | stmt_case
     862           4 :                         { $$ = $1; }
     863             :                 | stmt_loop
     864          32 :                         { $$ = $1; }
     865             :                 | stmt_while
     866          54 :                         { $$ = $1; }
     867             :                 | stmt_for
     868         496 :                         { $$ = $1; }
     869             :                 | stmt_foreach_a
     870          40 :                         { $$ = $1; }
     871             :                 | stmt_exit
     872          90 :                         { $$ = $1; }
     873             :                 | stmt_return
     874        4030 :                         { $$ = $1; }
     875             :                 | stmt_raise
     876        2870 :                         { $$ = $1; }
     877             :                 | stmt_assert
     878          34 :                         { $$ = $1; }
     879             :                 | stmt_execsql
     880        1352 :                         { $$ = $1; }
     881             :                 | stmt_dynexecute
     882         204 :                         { $$ = $1; }
     883             :                 | stmt_perform
     884         282 :                         { $$ = $1; }
     885             :                 | stmt_call
     886          54 :                         { $$ = $1; }
     887             :                 | stmt_getdiag
     888          52 :                         { $$ = $1; }
     889             :                 | stmt_open
     890          68 :                         { $$ = $1; }
     891             :                 | stmt_fetch
     892          80 :                         { $$ = $1; }
     893             :                 | stmt_move
     894          12 :                         { $$ = $1; }
     895             :                 | stmt_close
     896          44 :                         { $$ = $1; }
     897             :                 | stmt_null
     898          20 :                         { $$ = $1; }
     899             :                 | stmt_commit
     900          60 :                         { $$ = $1; }
     901             :                 | stmt_rollback
     902          30 :                         { $$ = $1; }
     903             :                 | stmt_set
     904          64 :                         { $$ = $1; }
     905             :                 ;
     906             : 
     907             : stmt_perform    : K_PERFORM expr_until_semi
     908             :                     {
     909             :                         PLpgSQL_stmt_perform *new;
     910             : 
     911         282 :                         new = palloc0(sizeof(PLpgSQL_stmt_perform));
     912         282 :                         new->cmd_type = PLPGSQL_STMT_PERFORM;
     913         282 :                         new->lineno   = plpgsql_location_to_lineno(@1);
     914         282 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
     915         282 :                         new->expr  = $2;
     916             : 
     917         282 :                         $$ = (PLpgSQL_stmt *)new;
     918             :                     }
     919             :                 ;
     920             : 
     921             : stmt_call       : K_CALL
     922             :                     {
     923             :                         PLpgSQL_stmt_call *new;
     924             : 
     925          52 :                         new = palloc0(sizeof(PLpgSQL_stmt_call));
     926          52 :                         new->cmd_type = PLPGSQL_STMT_CALL;
     927          52 :                         new->lineno = plpgsql_location_to_lineno(@1);
     928          52 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
     929          52 :                         new->expr = read_sql_stmt("CALL ");
     930          52 :                         new->is_call = true;
     931             : 
     932          52 :                         $$ = (PLpgSQL_stmt *)new;
     933             : 
     934             :                     }
     935             :                 | K_DO
     936             :                     {
     937             :                         /* use the same structures as for CALL, for simplicity */
     938             :                         PLpgSQL_stmt_call *new;
     939             : 
     940           2 :                         new = palloc0(sizeof(PLpgSQL_stmt_call));
     941           2 :                         new->cmd_type = PLPGSQL_STMT_CALL;
     942           2 :                         new->lineno = plpgsql_location_to_lineno(@1);
     943           2 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
     944           2 :                         new->expr = read_sql_stmt("DO ");
     945           2 :                         new->is_call = false;
     946             : 
     947           2 :                         $$ = (PLpgSQL_stmt *)new;
     948             : 
     949             :                     }
     950             :                 ;
     951             : 
     952             : stmt_assign     : assign_var assign_operator expr_until_semi
     953             :                     {
     954             :                         PLpgSQL_stmt_assign *new;
     955             : 
     956        2060 :                         new = palloc0(sizeof(PLpgSQL_stmt_assign));
     957        2060 :                         new->cmd_type = PLPGSQL_STMT_ASSIGN;
     958        2060 :                         new->lineno   = plpgsql_location_to_lineno(@1);
     959        2060 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
     960        2060 :                         new->varno = $1->dno;
     961        2060 :                         new->expr  = $3;
     962             : 
     963        2060 :                         $$ = (PLpgSQL_stmt *)new;
     964             :                     }
     965             :                 ;
     966             : 
     967             : stmt_getdiag    : K_GET getdiag_area_opt K_DIAGNOSTICS getdiag_list ';'
     968             :                     {
     969             :                         PLpgSQL_stmt_getdiag     *new;
     970             :                         ListCell        *lc;
     971             : 
     972          52 :                         new = palloc0(sizeof(PLpgSQL_stmt_getdiag));
     973          52 :                         new->cmd_type = PLPGSQL_STMT_GETDIAG;
     974          52 :                         new->lineno   = plpgsql_location_to_lineno(@1);
     975          52 :                         new->stmtid    = ++plpgsql_curr_compile->nstatements;
     976          52 :                         new->is_stacked = $2;
     977          52 :                         new->diag_items = $4;
     978             : 
     979             :                         /*
     980             :                          * Check information items are valid for area option.
     981             :                          */
     982         160 :                         foreach(lc, new->diag_items)
     983             :                         {
     984         108 :                             PLpgSQL_diag_item *ditem = (PLpgSQL_diag_item *) lfirst(lc);
     985             : 
     986         108 :                             switch (ditem->kind)
     987             :                             {
     988             :                                 /* these fields are disallowed in stacked case */
     989             :                                 case PLPGSQL_GETDIAG_ROW_COUNT:
     990          16 :                                     if (new->is_stacked)
     991           0 :                                         ereport(ERROR,
     992             :                                                 (errcode(ERRCODE_SYNTAX_ERROR),
     993             :                                                  errmsg("diagnostics item %s is not allowed in GET STACKED DIAGNOSTICS",
     994             :                                                         plpgsql_getdiag_kindname(ditem->kind)),
     995             :                                                  parser_errposition(@1)));
     996          16 :                                     break;
     997             :                                 /* these fields are disallowed in current case */
     998             :                                 case PLPGSQL_GETDIAG_ERROR_CONTEXT:
     999             :                                 case PLPGSQL_GETDIAG_ERROR_DETAIL:
    1000             :                                 case PLPGSQL_GETDIAG_ERROR_HINT:
    1001             :                                 case PLPGSQL_GETDIAG_RETURNED_SQLSTATE:
    1002             :                                 case PLPGSQL_GETDIAG_COLUMN_NAME:
    1003             :                                 case PLPGSQL_GETDIAG_CONSTRAINT_NAME:
    1004             :                                 case PLPGSQL_GETDIAG_DATATYPE_NAME:
    1005             :                                 case PLPGSQL_GETDIAG_MESSAGE_TEXT:
    1006             :                                 case PLPGSQL_GETDIAG_TABLE_NAME:
    1007             :                                 case PLPGSQL_GETDIAG_SCHEMA_NAME:
    1008          76 :                                     if (!new->is_stacked)
    1009           0 :                                         ereport(ERROR,
    1010             :                                                 (errcode(ERRCODE_SYNTAX_ERROR),
    1011             :                                                  errmsg("diagnostics item %s is not allowed in GET CURRENT DIAGNOSTICS",
    1012             :                                                         plpgsql_getdiag_kindname(ditem->kind)),
    1013             :                                                  parser_errposition(@1)));
    1014          76 :                                     break;
    1015             :                                 /* these fields are allowed in either case */
    1016             :                                 case PLPGSQL_GETDIAG_CONTEXT:
    1017          16 :                                     break;
    1018             :                                 default:
    1019           0 :                                     elog(ERROR, "unrecognized diagnostic item kind: %d",
    1020             :                                          ditem->kind);
    1021             :                                     break;
    1022             :                             }
    1023             :                         }
    1024             : 
    1025          52 :                         $$ = (PLpgSQL_stmt *)new;
    1026             :                     }
    1027             :                 ;
    1028             : 
    1029             : getdiag_area_opt :
    1030             :                     {
    1031          36 :                         $$ = false;
    1032             :                     }
    1033             :                 | K_CURRENT
    1034             :                     {
    1035           0 :                         $$ = false;
    1036             :                     }
    1037             :                 | K_STACKED
    1038             :                     {
    1039          20 :                         $$ = true;
    1040             :                     }
    1041             :                 ;
    1042             : 
    1043             : getdiag_list : getdiag_list ',' getdiag_list_item
    1044             :                     {
    1045          56 :                         $$ = lappend($1, $3);
    1046             :                     }
    1047             :                 | getdiag_list_item
    1048             :                     {
    1049          52 :                         $$ = list_make1($1);
    1050             :                     }
    1051             :                 ;
    1052             : 
    1053             : getdiag_list_item : getdiag_target assign_operator getdiag_item
    1054             :                     {
    1055             :                         PLpgSQL_diag_item *new;
    1056             : 
    1057         108 :                         new = palloc(sizeof(PLpgSQL_diag_item));
    1058         108 :                         new->target = $1->dno;
    1059         108 :                         new->kind = $3;
    1060             : 
    1061         108 :                         $$ = new;
    1062             :                     }
    1063             :                 ;
    1064             : 
    1065             : getdiag_item :
    1066             :                     {
    1067         108 :                         int tok = yylex();
    1068             : 
    1069         108 :                         if (tok_is_keyword(tok, &yylval,
    1070             :                                            K_ROW_COUNT, "row_count"))
    1071          16 :                             $$ = PLPGSQL_GETDIAG_ROW_COUNT;
    1072          92 :                         else if (tok_is_keyword(tok, &yylval,
    1073             :                                                 K_PG_CONTEXT, "pg_context"))
    1074          16 :                             $$ = PLPGSQL_GETDIAG_CONTEXT;
    1075          76 :                         else if (tok_is_keyword(tok, &yylval,
    1076             :                                                 K_PG_EXCEPTION_DETAIL, "pg_exception_detail"))
    1077          12 :                             $$ = PLPGSQL_GETDIAG_ERROR_DETAIL;
    1078          64 :                         else if (tok_is_keyword(tok, &yylval,
    1079             :                                                 K_PG_EXCEPTION_HINT, "pg_exception_hint"))
    1080          10 :                             $$ = PLPGSQL_GETDIAG_ERROR_HINT;
    1081          54 :                         else if (tok_is_keyword(tok, &yylval,
    1082             :                                                 K_PG_EXCEPTION_CONTEXT, "pg_exception_context"))
    1083           4 :                             $$ = PLPGSQL_GETDIAG_ERROR_CONTEXT;
    1084          50 :                         else if (tok_is_keyword(tok, &yylval,
    1085             :                                                 K_COLUMN_NAME, "column_name"))
    1086           6 :                             $$ = PLPGSQL_GETDIAG_COLUMN_NAME;
    1087          44 :                         else if (tok_is_keyword(tok, &yylval,
    1088             :                                                 K_CONSTRAINT_NAME, "constraint_name"))
    1089           6 :                             $$ = PLPGSQL_GETDIAG_CONSTRAINT_NAME;
    1090          38 :                         else if (tok_is_keyword(tok, &yylval,
    1091             :                                                 K_PG_DATATYPE_NAME, "pg_datatype_name"))
    1092           6 :                             $$ = PLPGSQL_GETDIAG_DATATYPE_NAME;
    1093          32 :                         else if (tok_is_keyword(tok, &yylval,
    1094             :                                                 K_MESSAGE_TEXT, "message_text"))
    1095          14 :                             $$ = PLPGSQL_GETDIAG_MESSAGE_TEXT;
    1096          18 :                         else if (tok_is_keyword(tok, &yylval,
    1097             :                                                 K_TABLE_NAME, "table_name"))
    1098           6 :                             $$ = PLPGSQL_GETDIAG_TABLE_NAME;
    1099          12 :                         else if (tok_is_keyword(tok, &yylval,
    1100             :                                                 K_SCHEMA_NAME, "schema_name"))
    1101           6 :                             $$ = PLPGSQL_GETDIAG_SCHEMA_NAME;
    1102           6 :                         else if (tok_is_keyword(tok, &yylval,
    1103             :                                                 K_RETURNED_SQLSTATE, "returned_sqlstate"))
    1104           6 :                             $$ = PLPGSQL_GETDIAG_RETURNED_SQLSTATE;
    1105             :                         else
    1106           0 :                             yyerror("unrecognized GET DIAGNOSTICS item");
    1107             :                     }
    1108             :                 ;
    1109             : 
    1110             : getdiag_target  : assign_var
    1111             :                     {
    1112         224 :                         if ($1->dtype == PLPGSQL_DTYPE_ROW ||
    1113         112 :                             $1->dtype == PLPGSQL_DTYPE_REC)
    1114           4 :                             ereport(ERROR,
    1115             :                                     (errcode(ERRCODE_SYNTAX_ERROR),
    1116             :                                      errmsg("\"%s\" is not a scalar variable",
    1117             :                                             ((PLpgSQL_variable *) $1)->refname),
    1118             :                                      parser_errposition(@1)));
    1119         108 :                         $$ = $1;
    1120             :                     }
    1121             :                 | T_WORD
    1122             :                     {
    1123             :                         /* just to give a better message than "syntax error" */
    1124           0 :                         word_is_not_variable(&($1), @1);
    1125             :                     }
    1126             :                 | T_CWORD
    1127             :                     {
    1128             :                         /* just to give a better message than "syntax error" */
    1129           0 :                         cword_is_not_variable(&($1), @1);
    1130             :                     }
    1131             :                 ;
    1132             : 
    1133             : 
    1134             : assign_var      : T_DATUM
    1135             :                     {
    1136        2178 :                         check_assignable($1.datum, @1);
    1137        2172 :                         $$ = $1.datum;
    1138             :                     }
    1139             :                 | assign_var '[' expr_until_rightbracket
    1140             :                     {
    1141             :                         PLpgSQL_arrayelem   *new;
    1142             : 
    1143          50 :                         new = palloc0(sizeof(PLpgSQL_arrayelem));
    1144          50 :                         new->dtype       = PLPGSQL_DTYPE_ARRAYELEM;
    1145          50 :                         new->subscript   = $3;
    1146          50 :                         new->arrayparentno = $1->dno;
    1147             :                         /* initialize cached type data to "not valid" */
    1148          50 :                         new->parenttypoid = InvalidOid;
    1149             : 
    1150          50 :                         plpgsql_adddatum((PLpgSQL_datum *) new);
    1151             : 
    1152          50 :                         $$ = (PLpgSQL_datum *) new;
    1153             :                     }
    1154             :                 ;
    1155             : 
    1156             : stmt_if         : K_IF expr_until_then proc_sect stmt_elsifs stmt_else K_END K_IF ';'
    1157             :                     {
    1158             :                         PLpgSQL_stmt_if *new;
    1159             : 
    1160        2708 :                         new = palloc0(sizeof(PLpgSQL_stmt_if));
    1161        2708 :                         new->cmd_type    = PLPGSQL_STMT_IF;
    1162        2708 :                         new->lineno      = plpgsql_location_to_lineno(@1);
    1163        2708 :                         new->stmtid      = ++plpgsql_curr_compile->nstatements;
    1164        2708 :                         new->cond        = $2;
    1165        2708 :                         new->then_body   = $3;
    1166        2708 :                         new->elsif_list = $4;
    1167        2708 :                         new->else_body  = $5;
    1168             : 
    1169        2708 :                         $$ = (PLpgSQL_stmt *)new;
    1170             :                     }
    1171             :                 ;
    1172             : 
    1173             : stmt_elsifs     :
    1174             :                     {
    1175        2708 :                         $$ = NIL;
    1176             :                     }
    1177             :                 | stmt_elsifs K_ELSIF expr_until_then proc_sect
    1178             :                     {
    1179             :                         PLpgSQL_if_elsif *new;
    1180             : 
    1181          72 :                         new = palloc0(sizeof(PLpgSQL_if_elsif));
    1182          72 :                         new->lineno = plpgsql_location_to_lineno(@2);
    1183          72 :                         new->cond   = $3;
    1184          72 :                         new->stmts  = $4;
    1185             : 
    1186          72 :                         $$ = lappend($1, new);
    1187             :                     }
    1188             :                 ;
    1189             : 
    1190             : stmt_else       :
    1191             :                     {
    1192        2374 :                         $$ = NIL;
    1193             :                     }
    1194             :                 | K_ELSE proc_sect
    1195             :                     {
    1196         334 :                         $$ = $2;
    1197             :                     }
    1198             :                 ;
    1199             : 
    1200             : stmt_case       : K_CASE opt_expr_until_when case_when_list opt_case_else K_END K_CASE ';'
    1201             :                     {
    1202           4 :                         $$ = make_case(@1, $2, $3, $4);
    1203             :                     }
    1204             :                 ;
    1205             : 
    1206             : opt_expr_until_when :
    1207             :                     {
    1208           4 :                         PLpgSQL_expr *expr = NULL;
    1209           4 :                         int tok = yylex();
    1210             : 
    1211           4 :                         if (tok != K_WHEN)
    1212             :                         {
    1213           2 :                             plpgsql_push_back_token(tok);
    1214           2 :                             expr = read_sql_expression(K_WHEN, "WHEN");
    1215             :                         }
    1216           4 :                         plpgsql_push_back_token(K_WHEN);
    1217           4 :                         $$ = expr;
    1218             :                     }
    1219             :                 ;
    1220             : 
    1221             : case_when_list  : case_when_list case_when
    1222             :                     {
    1223          10 :                         $$ = lappend($1, $2);
    1224             :                     }
    1225             :                 | case_when
    1226             :                     {
    1227           4 :                         $$ = list_make1($1);
    1228             :                     }
    1229             :                 ;
    1230             : 
    1231             : case_when       : K_WHEN expr_until_then proc_sect
    1232             :                     {
    1233          14 :                         PLpgSQL_case_when *new = palloc(sizeof(PLpgSQL_case_when));
    1234             : 
    1235          14 :                         new->lineno  = plpgsql_location_to_lineno(@1);
    1236          14 :                         new->expr    = $2;
    1237          14 :                         new->stmts   = $3;
    1238          14 :                         $$ = new;
    1239             :                     }
    1240             :                 ;
    1241             : 
    1242             : opt_case_else   :
    1243             :                     {
    1244           2 :                         $$ = NIL;
    1245             :                     }
    1246             :                 | K_ELSE proc_sect
    1247             :                     {
    1248             :                         /*
    1249             :                          * proc_sect could return an empty list, but we
    1250             :                          * must distinguish that from not having ELSE at all.
    1251             :                          * Simplest fix is to return a list with one NULL
    1252             :                          * pointer, which make_case() must take care of.
    1253             :                          */
    1254           2 :                         if ($2 != NIL)
    1255           2 :                             $$ = $2;
    1256             :                         else
    1257           0 :                             $$ = list_make1(NULL);
    1258             :                     }
    1259             :                 ;
    1260             : 
    1261             : stmt_loop       : opt_loop_label K_LOOP loop_body
    1262             :                     {
    1263             :                         PLpgSQL_stmt_loop *new;
    1264             : 
    1265          32 :                         new = palloc0(sizeof(PLpgSQL_stmt_loop));
    1266          32 :                         new->cmd_type = PLPGSQL_STMT_LOOP;
    1267          32 :                         new->lineno   = plpgsql_location_to_lineno(@2);
    1268          32 :                         new->stmtid   = ++plpgsql_curr_compile->nstatements;
    1269          32 :                         new->label     = $1;
    1270          32 :                         new->body      = $3.stmts;
    1271             : 
    1272          32 :                         check_labels($1, $3.end_label, $3.end_label_location);
    1273          32 :                         plpgsql_ns_pop();
    1274             : 
    1275          32 :                         $$ = (PLpgSQL_stmt *)new;
    1276             :                     }
    1277             :                 ;
    1278             : 
    1279             : stmt_while      : opt_loop_label K_WHILE expr_until_loop loop_body
    1280             :                     {
    1281             :                         PLpgSQL_stmt_while *new;
    1282             : 
    1283          54 :                         new = palloc0(sizeof(PLpgSQL_stmt_while));
    1284          54 :                         new->cmd_type = PLPGSQL_STMT_WHILE;
    1285          54 :                         new->lineno   = plpgsql_location_to_lineno(@2);
    1286          54 :                         new->stmtid    = ++plpgsql_curr_compile->nstatements;
    1287          54 :                         new->label     = $1;
    1288          54 :                         new->cond      = $3;
    1289          54 :                         new->body      = $4.stmts;
    1290             : 
    1291          54 :                         check_labels($1, $4.end_label, $4.end_label_location);
    1292          54 :                         plpgsql_ns_pop();
    1293             : 
    1294          54 :                         $$ = (PLpgSQL_stmt *)new;
    1295             :                     }
    1296             :                 ;
    1297             : 
    1298             : stmt_for        : opt_loop_label K_FOR for_control loop_body
    1299             :                     {
    1300             :                         /* This runs after we've scanned the loop body */
    1301         502 :                         if ($3->cmd_type == PLPGSQL_STMT_FORI)
    1302             :                         {
    1303             :                             PLpgSQL_stmt_fori       *new;
    1304             : 
    1305         190 :                             new = (PLpgSQL_stmt_fori *) $3;
    1306         190 :                             new->lineno   = plpgsql_location_to_lineno(@2);
    1307         190 :                             new->stmtid    = ++plpgsql_curr_compile->nstatements;
    1308         190 :                             new->label     = $1;
    1309         190 :                             new->body      = $4.stmts;
    1310         190 :                             $$ = (PLpgSQL_stmt *) new;
    1311             :                         }
    1312             :                         else
    1313             :                         {
    1314             :                             PLpgSQL_stmt_forq       *new;
    1315             : 
    1316             :                             Assert($3->cmd_type == PLPGSQL_STMT_FORS ||
    1317             :                                    $3->cmd_type == PLPGSQL_STMT_FORC ||
    1318             :                                    $3->cmd_type == PLPGSQL_STMT_DYNFORS);
    1319             :                             /* forq is the common supertype of all three */
    1320         312 :                             new = (PLpgSQL_stmt_forq *) $3;
    1321         312 :                             new->lineno   = plpgsql_location_to_lineno(@2);
    1322         312 :                             new->stmtid    = ++plpgsql_curr_compile->nstatements;
    1323         312 :                             new->label     = $1;
    1324         312 :                             new->body      = $4.stmts;
    1325         312 :                             $$ = (PLpgSQL_stmt *) new;
    1326             :                         }
    1327             : 
    1328         502 :                         check_labels($1, $4.end_label, $4.end_label_location);
    1329             :                         /* close namespace started in opt_loop_label */
    1330         496 :                         plpgsql_ns_pop();
    1331             :                     }
    1332             :                 ;
    1333             : 
    1334             : for_control     : for_variable K_IN
    1335             :                     {
    1336         510 :                         int         tok = yylex();
    1337         510 :                         int         tokloc = yylloc;
    1338             : 
    1339         510 :                         if (tok == K_EXECUTE)
    1340             :                         {
    1341             :                             /* EXECUTE means it's a dynamic FOR loop */
    1342             :                             PLpgSQL_stmt_dynfors    *new;
    1343             :                             PLpgSQL_expr            *expr;
    1344             :                             int                     term;
    1345             : 
    1346          70 :                             expr = read_sql_expression2(K_LOOP, K_USING,
    1347             :                                                         "LOOP or USING",
    1348             :                                                         &term);
    1349             : 
    1350          70 :                             new = palloc0(sizeof(PLpgSQL_stmt_dynfors));
    1351          70 :                             new->cmd_type = PLPGSQL_STMT_DYNFORS;
    1352          70 :                             new->stmtid    = ++plpgsql_curr_compile->nstatements;
    1353          70 :                             if ($1.row)
    1354             :                             {
    1355          14 :                                 new->var = (PLpgSQL_variable *) $1.row;
    1356          14 :                                 check_assignable($1.row, @1);
    1357             :                             }
    1358          56 :                             else if ($1.scalar)
    1359             :                             {
    1360             :                                 /* convert single scalar to list */
    1361          56 :                                 new->var = (PLpgSQL_variable *)
    1362         112 :                                     make_scalar_list1($1.name, $1.scalar,
    1363         112 :                                                       $1.lineno, @1);
    1364             :                                 /* make_scalar_list1 did check_assignable */
    1365             :                             }
    1366             :                             else
    1367             :                             {
    1368           0 :                                 ereport(ERROR,
    1369             :                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1370             :                                          errmsg("loop variable of loop over rows must be a record variable or list of scalar variables"),
    1371             :                                          parser_errposition(@1)));
    1372             :                             }
    1373          70 :                             new->query = expr;
    1374             : 
    1375          70 :                             if (term == K_USING)
    1376             :                             {
    1377             :                                 do
    1378             :                                 {
    1379           8 :                                     expr = read_sql_expression2(',', K_LOOP,
    1380             :                                                                 ", or LOOP",
    1381             :                                                                 &term);
    1382           8 :                                     new->params = lappend(new->params, expr);
    1383           8 :                                 } while (term == ',');
    1384             :                             }
    1385             : 
    1386          70 :                             $$ = (PLpgSQL_stmt *) new;
    1387             :                         }
    1388         484 :                         else if (tok == T_DATUM &&
    1389          88 :                                  yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_VAR &&
    1390          44 :                                  ((PLpgSQL_var *) yylval.wdatum.datum)->datatype->typoid == REFCURSOROID)
    1391          24 :                         {
    1392             :                             /* It's FOR var IN cursor */
    1393             :                             PLpgSQL_stmt_forc   *new;
    1394          28 :                             PLpgSQL_var         *cursor = (PLpgSQL_var *) yylval.wdatum.datum;
    1395             : 
    1396          28 :                             new = (PLpgSQL_stmt_forc *) palloc0(sizeof(PLpgSQL_stmt_forc));
    1397          28 :                             new->cmd_type = PLPGSQL_STMT_FORC;
    1398          28 :                             new->stmtid = ++plpgsql_curr_compile->nstatements;
    1399          28 :                             new->curvar = cursor->dno;
    1400             : 
    1401             :                             /* Should have had a single variable name */
    1402          28 :                             if ($1.scalar && $1.row)
    1403           0 :                                 ereport(ERROR,
    1404             :                                         (errcode(ERRCODE_SYNTAX_ERROR),
    1405             :                                          errmsg("cursor FOR loop must have only one target variable"),
    1406             :                                          parser_errposition(@1)));
    1407             : 
    1408             :                             /* can't use an unbound cursor this way */
    1409          28 :                             if (cursor->cursor_explicit_expr == NULL)
    1410           4 :                                 ereport(ERROR,
    1411             :                                         (errcode(ERRCODE_SYNTAX_ERROR),
    1412             :                                          errmsg("cursor FOR loop must use a bound cursor variable"),
    1413             :                                          parser_errposition(tokloc)));
    1414             : 
    1415             :                             /* collect cursor's parameters if any */
    1416          24 :                             new->argquery = read_cursor_args(cursor,
    1417             :                                                              K_LOOP,
    1418             :                                                              "LOOP");
    1419             : 
    1420             :                             /* create loop's private RECORD variable */
    1421          24 :                             new->var = (PLpgSQL_variable *)
    1422          24 :                                 plpgsql_build_record($1.name,
    1423          24 :                                                      $1.lineno,
    1424             :                                                      NULL,
    1425             :                                                      RECORDOID,
    1426             :                                                      true);
    1427             : 
    1428          24 :                             $$ = (PLpgSQL_stmt *) new;
    1429             :                         }
    1430             :                         else
    1431             :                         {
    1432             :                             PLpgSQL_expr    *expr1;
    1433             :                             int             expr1loc;
    1434         412 :                             bool            reverse = false;
    1435             : 
    1436             :                             /*
    1437             :                              * We have to distinguish between two
    1438             :                              * alternatives: FOR var IN a .. b and FOR
    1439             :                              * var IN query. Unfortunately this is
    1440             :                              * tricky, since the query in the second
    1441             :                              * form needn't start with a SELECT
    1442             :                              * keyword.  We use the ugly hack of
    1443             :                              * looking for two periods after the first
    1444             :                              * token. We also check for the REVERSE
    1445             :                              * keyword, which means it must be an
    1446             :                              * integer loop.
    1447             :                              */
    1448         412 :                             if (tok_is_keyword(tok, &yylval,
    1449             :                                                K_REVERSE, "reverse"))
    1450           6 :                                 reverse = true;
    1451             :                             else
    1452         406 :                                 plpgsql_push_back_token(tok);
    1453             : 
    1454             :                             /*
    1455             :                              * Read tokens until we see either a ".."
    1456             :                              * or a LOOP. The text we read may not
    1457             :                              * necessarily be a well-formed SQL
    1458             :                              * statement, so we need to invoke
    1459             :                              * read_sql_construct directly.
    1460             :                              */
    1461         412 :                             expr1 = read_sql_construct(DOT_DOT,
    1462             :                                                        K_LOOP,
    1463             :                                                        0,
    1464             :                                                        "LOOP",
    1465             :                                                        "SELECT ",
    1466             :                                                        true,
    1467             :                                                        false,
    1468             :                                                        true,
    1469             :                                                        &expr1loc,
    1470             :                                                        &tok);
    1471             : 
    1472         412 :                             if (tok == DOT_DOT)
    1473             :                             {
    1474             :                                 /* Saw "..", so it must be an integer loop */
    1475             :                                 PLpgSQL_expr        *expr2;
    1476             :                                 PLpgSQL_expr        *expr_by;
    1477             :                                 PLpgSQL_var         *fvar;
    1478             :                                 PLpgSQL_stmt_fori   *new;
    1479             : 
    1480             :                                 /* Check first expression is well-formed */
    1481         190 :                                 check_sql_expr(expr1->query, expr1loc, 7);
    1482             : 
    1483             :                                 /* Read and check the second one */
    1484         190 :                                 expr2 = read_sql_expression2(K_LOOP, K_BY,
    1485             :                                                              "LOOP",
    1486             :                                                              &tok);
    1487             : 
    1488             :                                 /* Get the BY clause if any */
    1489         190 :                                 if (tok == K_BY)
    1490          18 :                                     expr_by = read_sql_expression(K_LOOP,
    1491             :                                                                   "LOOP");
    1492             :                                 else
    1493         172 :                                     expr_by = NULL;
    1494             : 
    1495             :                                 /* Should have had a single variable name */
    1496         190 :                                 if ($1.scalar && $1.row)
    1497           0 :                                     ereport(ERROR,
    1498             :                                             (errcode(ERRCODE_SYNTAX_ERROR),
    1499             :                                              errmsg("integer FOR loop must have only one target variable"),
    1500             :                                              parser_errposition(@1)));
    1501             : 
    1502             :                                 /* create loop's private variable */
    1503         190 :                                 fvar = (PLpgSQL_var *)
    1504         380 :                                     plpgsql_build_variable($1.name,
    1505         190 :                                                            $1.lineno,
    1506             :                                                            plpgsql_build_datatype(INT4OID,
    1507             :                                                                                   -1,
    1508             :                                                                                   InvalidOid,
    1509             :                                                                                   NULL),
    1510             :                                                            true);
    1511             : 
    1512         190 :                                 new = palloc0(sizeof(PLpgSQL_stmt_fori));
    1513         190 :                                 new->cmd_type = PLPGSQL_STMT_FORI;
    1514         190 :                                 new->stmtid    = ++plpgsql_curr_compile->nstatements;
    1515         190 :                                 new->var   = fvar;
    1516         190 :                                 new->reverse  = reverse;
    1517         190 :                                 new->lower     = expr1;
    1518         190 :                                 new->upper     = expr2;
    1519         190 :                                 new->step      = expr_by;
    1520             : 
    1521         190 :                                 $$ = (PLpgSQL_stmt *) new;
    1522             :                             }
    1523             :                             else
    1524             :                             {
    1525             :                                 /*
    1526             :                                  * No "..", so it must be a query loop. We've
    1527             :                                  * prefixed an extra SELECT to the query text,
    1528             :                                  * so we need to remove that before performing
    1529             :                                  * syntax checking.
    1530             :                                  */
    1531             :                                 char                *tmp_query;
    1532             :                                 PLpgSQL_stmt_fors   *new;
    1533             : 
    1534         222 :                                 if (reverse)
    1535           0 :                                     ereport(ERROR,
    1536             :                                             (errcode(ERRCODE_SYNTAX_ERROR),
    1537             :                                              errmsg("cannot specify REVERSE in query FOR loop"),
    1538             :                                              parser_errposition(tokloc)));
    1539             : 
    1540             :                                 Assert(strncmp(expr1->query, "SELECT ", 7) == 0);
    1541         222 :                                 tmp_query = pstrdup(expr1->query + 7);
    1542         222 :                                 pfree(expr1->query);
    1543         222 :                                 expr1->query = tmp_query;
    1544             : 
    1545         222 :                                 check_sql_expr(expr1->query, expr1loc, 0);
    1546             : 
    1547         218 :                                 new = palloc0(sizeof(PLpgSQL_stmt_fors));
    1548         218 :                                 new->cmd_type = PLPGSQL_STMT_FORS;
    1549         218 :                                 new->stmtid = ++plpgsql_curr_compile->nstatements;
    1550         218 :                                 if ($1.row)
    1551             :                                 {
    1552         180 :                                     new->var = (PLpgSQL_variable *) $1.row;
    1553         180 :                                     check_assignable($1.row, @1);
    1554             :                                 }
    1555          38 :                                 else if ($1.scalar)
    1556             :                                 {
    1557             :                                     /* convert single scalar to list */
    1558          38 :                                     new->var = (PLpgSQL_variable *)
    1559          76 :                                         make_scalar_list1($1.name, $1.scalar,
    1560          76 :                                                           $1.lineno, @1);
    1561             :                                     /* make_scalar_list1 did check_assignable */
    1562             :                                 }
    1563             :                                 else
    1564             :                                 {
    1565           0 :                                     ereport(ERROR,
    1566             :                                             (errcode(ERRCODE_SYNTAX_ERROR),
    1567             :                                              errmsg("loop variable of loop over rows must be a record variable or list of scalar variables"),
    1568             :                                              parser_errposition(@1)));
    1569             :                                 }
    1570             : 
    1571         218 :                                 new->query = expr1;
    1572         218 :                                 $$ = (PLpgSQL_stmt *) new;
    1573             :                             }
    1574             :                         }
    1575             :                     }
    1576             :                 ;
    1577             : 
    1578             : /*
    1579             :  * Processing the for_variable is tricky because we don't yet know if the
    1580             :  * FOR is an integer FOR loop or a loop over query results.  In the former
    1581             :  * case, the variable is just a name that we must instantiate as a loop
    1582             :  * local variable, regardless of any other definition it might have.
    1583             :  * Therefore, we always save the actual identifier into $$.name where it
    1584             :  * can be used for that case.  We also save the outer-variable definition,
    1585             :  * if any, because that's what we need for the loop-over-query case.  Note
    1586             :  * that we must NOT apply check_assignable() or any other semantic check
    1587             :  * until we know what's what.
    1588             :  *
    1589             :  * However, if we see a comma-separated list of names, we know that it
    1590             :  * can't be an integer FOR loop and so it's OK to check the variables
    1591             :  * immediately.  In particular, for T_WORD followed by comma, we should
    1592             :  * complain that the name is not known rather than say it's a syntax error.
    1593             :  * Note that the non-error result of this case sets *both* $$.scalar and
    1594             :  * $$.row; see the for_control production.
    1595             :  */
    1596             : for_variable    : T_DATUM
    1597             :                     {
    1598         352 :                         $$.name = NameOfDatum(&($1));
    1599         352 :                         $$.lineno = plpgsql_location_to_lineno(@1);
    1600         704 :                         if ($1.datum->dtype == PLPGSQL_DTYPE_ROW ||
    1601         352 :                             $1.datum->dtype == PLPGSQL_DTYPE_REC)
    1602             :                         {
    1603         198 :                             $$.scalar = NULL;
    1604         198 :                             $$.row = $1.datum;
    1605             :                         }
    1606             :                         else
    1607             :                         {
    1608             :                             int         tok;
    1609             : 
    1610         154 :                             $$.scalar = $1.datum;
    1611         154 :                             $$.row = NULL;
    1612             :                             /* check for comma-separated list */
    1613         154 :                             tok = yylex();
    1614         154 :                             plpgsql_push_back_token(tok);
    1615         154 :                             if (tok == ',')
    1616          16 :                                 $$.row = (PLpgSQL_datum *)
    1617          20 :                                     read_into_scalar_list($$.name,
    1618             :                                                           $$.scalar,
    1619             :                                                           @1);
    1620             :                         }
    1621             :                     }
    1622             :                 | T_WORD
    1623             :                     {
    1624             :                         int         tok;
    1625             : 
    1626         204 :                         $$.name = $1.ident;
    1627         204 :                         $$.lineno = plpgsql_location_to_lineno(@1);
    1628         204 :                         $$.scalar = NULL;
    1629         204 :                         $$.row = NULL;
    1630             :                         /* check for comma-separated list */
    1631         204 :                         tok = yylex();
    1632         204 :                         plpgsql_push_back_token(tok);
    1633         204 :                         if (tok == ',')
    1634           0 :                             word_is_not_variable(&($1), @1);
    1635             :                     }
    1636             :                 | T_CWORD
    1637             :                     {
    1638             :                         /* just to give a better message than "syntax error" */
    1639           0 :                         cword_is_not_variable(&($1), @1);
    1640             :                     }
    1641             :                 ;
    1642             : 
    1643             : stmt_foreach_a  : opt_loop_label K_FOREACH for_variable foreach_slice K_IN K_ARRAY expr_until_loop loop_body
    1644             :                     {
    1645             :                         PLpgSQL_stmt_foreach_a *new;
    1646             : 
    1647          40 :                         new = palloc0(sizeof(PLpgSQL_stmt_foreach_a));
    1648          40 :                         new->cmd_type = PLPGSQL_STMT_FOREACH_A;
    1649          40 :                         new->lineno = plpgsql_location_to_lineno(@2);
    1650          40 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
    1651          40 :                         new->label = $1;
    1652          40 :                         new->slice = $4;
    1653          40 :                         new->expr = $7;
    1654          40 :                         new->body = $8.stmts;
    1655             : 
    1656          40 :                         if ($3.row)
    1657             :                         {
    1658          16 :                             new->varno = $3.row->dno;
    1659          16 :                             check_assignable($3.row, @3);
    1660             :                         }
    1661          24 :                         else if ($3.scalar)
    1662             :                         {
    1663          24 :                             new->varno = $3.scalar->dno;
    1664          24 :                             check_assignable($3.scalar, @3);
    1665             :                         }
    1666             :                         else
    1667             :                         {
    1668           0 :                             ereport(ERROR,
    1669             :                                     (errcode(ERRCODE_SYNTAX_ERROR),
    1670             :                                      errmsg("loop variable of FOREACH must be a known variable or list of variables"),
    1671             :                                              parser_errposition(@3)));
    1672             :                         }
    1673             : 
    1674          40 :                         check_labels($1, $8.end_label, $8.end_label_location);
    1675          40 :                         plpgsql_ns_pop();
    1676             : 
    1677          40 :                         $$ = (PLpgSQL_stmt *) new;
    1678             :                     }
    1679             :                 ;
    1680             : 
    1681             : foreach_slice   :
    1682             :                     {
    1683          20 :                         $$ = 0;
    1684             :                     }
    1685             :                 | K_SLICE ICONST
    1686             :                     {
    1687          20 :                         $$ = $2;
    1688             :                     }
    1689             :                 ;
    1690             : 
    1691             : stmt_exit       : exit_type opt_label opt_exitcond
    1692             :                     {
    1693             :                         PLpgSQL_stmt_exit *new;
    1694             : 
    1695         100 :                         new = palloc0(sizeof(PLpgSQL_stmt_exit));
    1696         100 :                         new->cmd_type = PLPGSQL_STMT_EXIT;
    1697         100 :                         new->stmtid    = ++plpgsql_curr_compile->nstatements;
    1698         100 :                         new->is_exit  = $1;
    1699         100 :                         new->lineno    = plpgsql_location_to_lineno(@1);
    1700         100 :                         new->label     = $2;
    1701         100 :                         new->cond      = $3;
    1702             : 
    1703         100 :                         if ($2)
    1704             :                         {
    1705             :                             /* We have a label, so verify it exists */
    1706             :                             PLpgSQL_nsitem *label;
    1707             : 
    1708          30 :                             label = plpgsql_ns_lookup_label(plpgsql_ns_top(), $2);
    1709          30 :                             if (label == NULL)
    1710           4 :                                 ereport(ERROR,
    1711             :                                         (errcode(ERRCODE_SYNTAX_ERROR),
    1712             :                                          errmsg("there is no label \"%s\" "
    1713             :                                                 "attached to any block or loop enclosing this statement",
    1714             :                                                 $2),
    1715             :                                          parser_errposition(@2)));
    1716             :                             /* CONTINUE only allows loop labels */
    1717          26 :                             if (label->itemno != PLPGSQL_LABEL_LOOP && !new->is_exit)
    1718           2 :                                 ereport(ERROR,
    1719             :                                         (errcode(ERRCODE_SYNTAX_ERROR),
    1720             :                                          errmsg("block label \"%s\" cannot be used in CONTINUE",
    1721             :                                                 $2),
    1722             :                                          parser_errposition(@2)));
    1723             :                         }
    1724             :                         else
    1725             :                         {
    1726             :                             /*
    1727             :                              * No label, so make sure there is some loop (an
    1728             :                              * unlabelled EXIT does not match a block, so this
    1729             :                              * is the same test for both EXIT and CONTINUE)
    1730             :                              */
    1731          70 :                             if (plpgsql_ns_find_nearest_loop(plpgsql_ns_top()) == NULL)
    1732           4 :                                 ereport(ERROR,
    1733             :                                         (errcode(ERRCODE_SYNTAX_ERROR),
    1734             :                                          new->is_exit ?
    1735             :                                          errmsg("EXIT cannot be used outside a loop, unless it has a label") :
    1736             :                                          errmsg("CONTINUE cannot be used outside a loop"),
    1737             :                                          parser_errposition(@1)));
    1738             :                         }
    1739             : 
    1740          90 :                         $$ = (PLpgSQL_stmt *)new;
    1741             :                     }
    1742             :                 ;
    1743             : 
    1744             : exit_type       : K_EXIT
    1745             :                     {
    1746          62 :                         $$ = true;
    1747             :                     }
    1748             :                 | K_CONTINUE
    1749             :                     {
    1750          38 :                         $$ = false;
    1751             :                     }
    1752             :                 ;
    1753             : 
    1754             : stmt_return     : K_RETURN
    1755             :                     {
    1756             :                         int tok;
    1757             : 
    1758        4048 :                         tok = yylex();
    1759        4048 :                         if (tok == 0)
    1760           0 :                             yyerror("unexpected end of function definition");
    1761             : 
    1762        4048 :                         if (tok_is_keyword(tok, &yylval,
    1763             :                                            K_NEXT, "next"))
    1764             :                         {
    1765         162 :                             $$ = make_return_next_stmt(@1);
    1766             :                         }
    1767        3886 :                         else if (tok_is_keyword(tok, &yylval,
    1768             :                                                 K_QUERY, "query"))
    1769             :                         {
    1770          64 :                             $$ = make_return_query_stmt(@1);
    1771             :                         }
    1772             :                         else
    1773             :                         {
    1774        3822 :                             plpgsql_push_back_token(tok);
    1775        3822 :                             $$ = make_return_stmt(@1);
    1776             :                         }
    1777             :                     }
    1778             :                 ;
    1779             : 
    1780             : stmt_raise      : K_RAISE
    1781             :                     {
    1782             :                         PLpgSQL_stmt_raise      *new;
    1783             :                         int tok;
    1784             : 
    1785        2878 :                         new = palloc(sizeof(PLpgSQL_stmt_raise));
    1786             : 
    1787        2878 :                         new->cmd_type    = PLPGSQL_STMT_RAISE;
    1788        2878 :                         new->lineno      = plpgsql_location_to_lineno(@1);
    1789        2878 :                         new->stmtid      = ++plpgsql_curr_compile->nstatements;
    1790        2878 :                         new->elog_level = ERROR; /* default */
    1791        2878 :                         new->condname    = NULL;
    1792        2878 :                         new->message = NULL;
    1793        2878 :                         new->params      = NIL;
    1794        2878 :                         new->options = NIL;
    1795             : 
    1796        2878 :                         tok = yylex();
    1797        2878 :                         if (tok == 0)
    1798           0 :                             yyerror("unexpected end of function definition");
    1799             : 
    1800             :                         /*
    1801             :                          * We could have just RAISE, meaning to re-throw
    1802             :                          * the current error.
    1803             :                          */
    1804        2878 :                         if (tok != ';')
    1805             :                         {
    1806             :                             /*
    1807             :                              * First is an optional elog severity level.
    1808             :                              */
    1809        2852 :                             if (tok_is_keyword(tok, &yylval,
    1810             :                                                K_EXCEPTION, "exception"))
    1811             :                             {
    1812         324 :                                 new->elog_level = ERROR;
    1813         324 :                                 tok = yylex();
    1814             :                             }
    1815        2528 :                             else if (tok_is_keyword(tok, &yylval,
    1816             :                                                     K_WARNING, "warning"))
    1817             :                             {
    1818          92 :                                 new->elog_level = WARNING;
    1819          92 :                                 tok = yylex();
    1820             :                             }
    1821        2436 :                             else if (tok_is_keyword(tok, &yylval,
    1822             :                                                     K_NOTICE, "notice"))
    1823             :                             {
    1824        2180 :                                 new->elog_level = NOTICE;
    1825        2180 :                                 tok = yylex();
    1826             :                             }
    1827         256 :                             else if (tok_is_keyword(tok, &yylval,
    1828             :                                                     K_INFO, "info"))
    1829             :                             {
    1830          94 :                                 new->elog_level = INFO;
    1831          94 :                                 tok = yylex();
    1832             :                             }
    1833         162 :                             else if (tok_is_keyword(tok, &yylval,
    1834             :                                                     K_LOG, "log"))
    1835             :                             {
    1836          20 :                                 new->elog_level = LOG;
    1837          20 :                                 tok = yylex();
    1838             :                             }
    1839         142 :                             else if (tok_is_keyword(tok, &yylval,
    1840             :                                                     K_DEBUG, "debug"))
    1841             :                             {
    1842           0 :                                 new->elog_level = DEBUG1;
    1843           0 :                                 tok = yylex();
    1844             :                             }
    1845        2852 :                             if (tok == 0)
    1846           0 :                                 yyerror("unexpected end of function definition");
    1847             : 
    1848             :                             /*
    1849             :                              * Next we can have a condition name, or
    1850             :                              * equivalently SQLSTATE 'xxxxx', or a string
    1851             :                              * literal that is the old-style message format,
    1852             :                              * or USING to start the option list immediately.
    1853             :                              */
    1854        2852 :                             if (tok == SCONST)
    1855             :                             {
    1856             :                                 /* old style message and parameters */
    1857        2724 :                                 new->message = yylval.str;
    1858             :                                 /*
    1859             :                                  * We expect either a semi-colon, which
    1860             :                                  * indicates no parameters, or a comma that
    1861             :                                  * begins the list of parameter expressions,
    1862             :                                  * or USING to begin the options list.
    1863             :                                  */
    1864        2724 :                                 tok = yylex();
    1865        2724 :                                 if (tok != ',' && tok != ';' && tok != K_USING)
    1866           0 :                                     yyerror("syntax error");
    1867             : 
    1868       10284 :                                 while (tok == ',')
    1869             :                                 {
    1870             :                                     PLpgSQL_expr *expr;
    1871             : 
    1872        4836 :                                     expr = read_sql_construct(',', ';', K_USING,
    1873             :                                                               ", or ; or USING",
    1874             :                                                               "SELECT ",
    1875             :                                                               true, true, true,
    1876             :                                                               NULL, &tok);
    1877        4836 :                                     new->params = lappend(new->params, expr);
    1878             :                                 }
    1879             :                             }
    1880         128 :                             else if (tok != K_USING)
    1881             :                             {
    1882             :                                 /* must be condition name or SQLSTATE */
    1883         116 :                                 if (tok_is_keyword(tok, &yylval,
    1884             :                                                    K_SQLSTATE, "sqlstate"))
    1885             :                                 {
    1886             :                                     /* next token should be a string literal */
    1887             :                                     char   *sqlstatestr;
    1888             : 
    1889          96 :                                     if (yylex() != SCONST)
    1890           0 :                                         yyerror("syntax error");
    1891          96 :                                     sqlstatestr = yylval.str;
    1892             : 
    1893          96 :                                     if (strlen(sqlstatestr) != 5)
    1894           0 :                                         yyerror("invalid SQLSTATE code");
    1895          96 :                                     if (strspn(sqlstatestr, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") != 5)
    1896           0 :                                         yyerror("invalid SQLSTATE code");
    1897          96 :                                     new->condname = sqlstatestr;
    1898             :                                 }
    1899             :                                 else
    1900             :                                 {
    1901          20 :                                     if (tok == T_WORD)
    1902          20 :                                         new->condname = yylval.word.ident;
    1903           0 :                                     else if (plpgsql_token_is_unreserved_keyword(tok))
    1904           0 :                                         new->condname = pstrdup(yylval.keyword);
    1905             :                                     else
    1906           0 :                                         yyerror("syntax error");
    1907          20 :                                     plpgsql_recognize_err_condition(new->condname,
    1908             :                                                                     false);
    1909             :                                 }
    1910         116 :                                 tok = yylex();
    1911         116 :                                 if (tok != ';' && tok != K_USING)
    1912           0 :                                     yyerror("syntax error");
    1913             :                             }
    1914             : 
    1915        2852 :                             if (tok == K_USING)
    1916         140 :                                 new->options = read_raise_options();
    1917             :                         }
    1918             : 
    1919        2878 :                         check_raise_parameters(new);
    1920             : 
    1921        2870 :                         $$ = (PLpgSQL_stmt *)new;
    1922             :                     }
    1923             :                 ;
    1924             : 
    1925             : stmt_assert     : K_ASSERT
    1926             :                     {
    1927             :                         PLpgSQL_stmt_assert     *new;
    1928             :                         int tok;
    1929             : 
    1930          34 :                         new = palloc(sizeof(PLpgSQL_stmt_assert));
    1931             : 
    1932          34 :                         new->cmd_type    = PLPGSQL_STMT_ASSERT;
    1933          34 :                         new->lineno      = plpgsql_location_to_lineno(@1);
    1934          34 :                         new->stmtid      = ++plpgsql_curr_compile->nstatements;
    1935             : 
    1936          34 :                         new->cond = read_sql_expression2(',', ';',
    1937             :                                                          ", or ;",
    1938             :                                                          &tok);
    1939             : 
    1940          34 :                         if (tok == ',')
    1941           8 :                             new->message = read_sql_expression(';', ";");
    1942             :                         else
    1943          26 :                             new->message = NULL;
    1944             : 
    1945          34 :                         $$ = (PLpgSQL_stmt *) new;
    1946             :                     }
    1947             :                 ;
    1948             : 
    1949             : loop_body       : proc_sect K_END K_LOOP opt_label ';'
    1950             :                     {
    1951         628 :                         $$.stmts = $1;
    1952         628 :                         $$.end_label = $4;
    1953         628 :                         $$.end_label_location = @4;
    1954             :                     }
    1955             :                 ;
    1956             : 
    1957             : /*
    1958             :  * T_WORD+T_CWORD match any initial identifier that is not a known plpgsql
    1959             :  * variable.  (The composite case is probably a syntax error, but we'll let
    1960             :  * the core parser decide that.)  Normally, we should assume that such a
    1961             :  * word is a SQL statement keyword that isn't also a plpgsql keyword.
    1962             :  * However, if the next token is assignment or '[', it can't be a valid
    1963             :  * SQL statement, and what we're probably looking at is an intended variable
    1964             :  * assignment.  Give an appropriate complaint for that, instead of letting
    1965             :  * the core parser throw an unhelpful "syntax error".
    1966             :  */
    1967             : stmt_execsql    : K_IMPORT
    1968             :                     {
    1969           0 :                         $$ = make_execsql_stmt(K_IMPORT, @1);
    1970             :                     }
    1971             :                 | K_INSERT
    1972             :                     {
    1973         356 :                         $$ = make_execsql_stmt(K_INSERT, @1);
    1974             :                     }
    1975             :                 | T_WORD
    1976             :                     {
    1977             :                         int         tok;
    1978             : 
    1979        1000 :                         tok = yylex();
    1980        1000 :                         plpgsql_push_back_token(tok);
    1981        1000 :                         if (tok == '=' || tok == COLON_EQUALS || tok == '[')
    1982           0 :                             word_is_not_variable(&($1), @1);
    1983        1000 :                         $$ = make_execsql_stmt(T_WORD, @1);
    1984             :                     }
    1985             :                 | T_CWORD
    1986             :                     {
    1987             :                         int         tok;
    1988             : 
    1989           0 :                         tok = yylex();
    1990           0 :                         plpgsql_push_back_token(tok);
    1991           0 :                         if (tok == '=' || tok == COLON_EQUALS || tok == '[')
    1992           0 :                             cword_is_not_variable(&($1), @1);
    1993           0 :                         $$ = make_execsql_stmt(T_CWORD, @1);
    1994             :                     }
    1995             :                 ;
    1996             : 
    1997             : stmt_dynexecute : K_EXECUTE
    1998             :                     {
    1999             :                         PLpgSQL_stmt_dynexecute *new;
    2000             :                         PLpgSQL_expr *expr;
    2001             :                         int endtoken;
    2002             : 
    2003         204 :                         expr = read_sql_construct(K_INTO, K_USING, ';',
    2004             :                                                   "INTO or USING or ;",
    2005             :                                                   "SELECT ",
    2006             :                                                   true, true, true,
    2007             :                                                   NULL, &endtoken);
    2008             : 
    2009         204 :                         new = palloc(sizeof(PLpgSQL_stmt_dynexecute));
    2010         204 :                         new->cmd_type = PLPGSQL_STMT_DYNEXECUTE;
    2011         204 :                         new->lineno = plpgsql_location_to_lineno(@1);
    2012         204 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
    2013         204 :                         new->query = expr;
    2014         204 :                         new->into = false;
    2015         204 :                         new->strict = false;
    2016         204 :                         new->target = NULL;
    2017         204 :                         new->params = NIL;
    2018             : 
    2019             :                         /*
    2020             :                          * We loop to allow the INTO and USING clauses to
    2021             :                          * appear in either order, since people easily get
    2022             :                          * that wrong.  This coding also prevents "INTO foo"
    2023             :                          * from getting absorbed into a USING expression,
    2024             :                          * which is *really* confusing.
    2025             :                          */
    2026             :                         for (;;)
    2027             :                         {
    2028         444 :                             if (endtoken == K_INTO)
    2029             :                             {
    2030         104 :                                 if (new->into)           /* multiple INTO */
    2031           0 :                                     yyerror("syntax error");
    2032         104 :                                 new->into = true;
    2033         104 :                                 read_into_target(&new->target, &new->strict);
    2034         104 :                                 endtoken = yylex();
    2035             :                             }
    2036         220 :                             else if (endtoken == K_USING)
    2037             :                             {
    2038          16 :                                 if (new->params)     /* multiple USING */
    2039           0 :                                     yyerror("syntax error");
    2040             :                                 do
    2041             :                                 {
    2042          28 :                                     expr = read_sql_construct(',', ';', K_INTO,
    2043             :                                                               ", or ; or INTO",
    2044             :                                                               "SELECT ",
    2045             :                                                               true, true, true,
    2046             :                                                               NULL, &endtoken);
    2047          28 :                                     new->params = lappend(new->params, expr);
    2048          28 :                                 } while (endtoken == ',');
    2049             :                             }
    2050         204 :                             else if (endtoken == ';')
    2051         204 :                                 break;
    2052             :                             else
    2053           0 :                                 yyerror("syntax error");
    2054             :                         }
    2055             : 
    2056         204 :                         $$ = (PLpgSQL_stmt *)new;
    2057             :                     }
    2058             :                 ;
    2059             : 
    2060             : 
    2061             : stmt_open       : K_OPEN cursor_variable
    2062             :                     {
    2063             :                         PLpgSQL_stmt_open *new;
    2064             :                         int               tok;
    2065             : 
    2066          84 :                         new = palloc0(sizeof(PLpgSQL_stmt_open));
    2067          84 :                         new->cmd_type = PLPGSQL_STMT_OPEN;
    2068          84 :                         new->lineno = plpgsql_location_to_lineno(@1);
    2069          84 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
    2070          84 :                         new->curvar = $2->dno;
    2071          84 :                         new->cursor_options = CURSOR_OPT_FAST_PLAN;
    2072             : 
    2073          84 :                         if ($2->cursor_explicit_expr == NULL)
    2074             :                         {
    2075             :                             /* be nice if we could use opt_scrollable here */
    2076          28 :                             tok = yylex();
    2077          28 :                             if (tok_is_keyword(tok, &yylval,
    2078             :                                                K_NO, "no"))
    2079             :                             {
    2080           0 :                                 tok = yylex();
    2081           0 :                                 if (tok_is_keyword(tok, &yylval,
    2082             :                                                    K_SCROLL, "scroll"))
    2083             :                                 {
    2084           0 :                                     new->cursor_options |= CURSOR_OPT_NO_SCROLL;
    2085           0 :                                     tok = yylex();
    2086             :                                 }
    2087             :                             }
    2088          28 :                             else if (tok_is_keyword(tok, &yylval,
    2089             :                                                     K_SCROLL, "scroll"))
    2090             :                             {
    2091          12 :                                 new->cursor_options |= CURSOR_OPT_SCROLL;
    2092          12 :                                 tok = yylex();
    2093             :                             }
    2094             : 
    2095          28 :                             if (tok != K_FOR)
    2096           0 :                                 yyerror("syntax error, expected \"FOR\"");
    2097             : 
    2098          28 :                             tok = yylex();
    2099          28 :                             if (tok == K_EXECUTE)
    2100             :                             {
    2101             :                                 int     endtoken;
    2102             : 
    2103          12 :                                 new->dynquery =
    2104          12 :                                     read_sql_expression2(K_USING, ';',
    2105             :                                                          "USING or ;",
    2106             :                                                          &endtoken);
    2107             : 
    2108             :                                 /* If we found "USING", collect argument(s) */
    2109          12 :                                 if (endtoken == K_USING)
    2110             :                                 {
    2111             :                                     PLpgSQL_expr *expr;
    2112             : 
    2113             :                                     do
    2114             :                                     {
    2115           4 :                                         expr = read_sql_expression2(',', ';',
    2116             :                                                                     ", or ;",
    2117             :                                                                     &endtoken);
    2118           4 :                                         new->params = lappend(new->params,
    2119             :                                                               expr);
    2120           4 :                                     } while (endtoken == ',');
    2121             :                                 }
    2122             :                             }
    2123             :                             else
    2124             :                             {
    2125          16 :                                 plpgsql_push_back_token(tok);
    2126          16 :                                 new->query = read_sql_stmt("");
    2127             :                             }
    2128             :                         }
    2129             :                         else
    2130             :                         {
    2131             :                             /* predefined cursor query, so read args */
    2132          56 :                             new->argquery = read_cursor_args($2, ';', ";");
    2133             :                         }
    2134             : 
    2135          68 :                         $$ = (PLpgSQL_stmt *)new;
    2136             :                     }
    2137             :                 ;
    2138             : 
    2139             : stmt_fetch      : K_FETCH opt_fetch_direction cursor_variable K_INTO
    2140             :                     {
    2141          80 :                         PLpgSQL_stmt_fetch *fetch = $2;
    2142             :                         PLpgSQL_variable *target;
    2143             : 
    2144             :                         /* We have already parsed everything through the INTO keyword */
    2145          80 :                         read_into_target(&target, NULL);
    2146             : 
    2147          80 :                         if (yylex() != ';')
    2148           0 :                             yyerror("syntax error");
    2149             : 
    2150             :                         /*
    2151             :                          * We don't allow multiple rows in PL/pgSQL's FETCH
    2152             :                          * statement, only in MOVE.
    2153             :                          */
    2154          80 :                         if (fetch->returns_multiple_rows)
    2155           0 :                             ereport(ERROR,
    2156             :                                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2157             :                                      errmsg("FETCH statement cannot return multiple rows"),
    2158             :                                      parser_errposition(@1)));
    2159             : 
    2160          80 :                         fetch->lineno = plpgsql_location_to_lineno(@1);
    2161          80 :                         fetch->target    = target;
    2162          80 :                         fetch->curvar    = $3->dno;
    2163          80 :                         fetch->is_move   = false;
    2164             : 
    2165          80 :                         $$ = (PLpgSQL_stmt *)fetch;
    2166             :                     }
    2167             :                 ;
    2168             : 
    2169             : stmt_move       : K_MOVE opt_fetch_direction cursor_variable ';'
    2170             :                     {
    2171          12 :                         PLpgSQL_stmt_fetch *fetch = $2;
    2172             : 
    2173          12 :                         fetch->lineno = plpgsql_location_to_lineno(@1);
    2174          12 :                         fetch->curvar    = $3->dno;
    2175          12 :                         fetch->is_move   = true;
    2176             : 
    2177          12 :                         $$ = (PLpgSQL_stmt *)fetch;
    2178             :                     }
    2179             :                 ;
    2180             : 
    2181             : opt_fetch_direction :
    2182             :                     {
    2183          92 :                         $$ = read_fetch_direction();
    2184             :                     }
    2185             :                 ;
    2186             : 
    2187             : stmt_close      : K_CLOSE cursor_variable ';'
    2188             :                     {
    2189             :                         PLpgSQL_stmt_close *new;
    2190             : 
    2191          44 :                         new = palloc(sizeof(PLpgSQL_stmt_close));
    2192          44 :                         new->cmd_type = PLPGSQL_STMT_CLOSE;
    2193          44 :                         new->lineno = plpgsql_location_to_lineno(@1);
    2194          44 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
    2195          44 :                         new->curvar = $2->dno;
    2196             : 
    2197          44 :                         $$ = (PLpgSQL_stmt *)new;
    2198             :                     }
    2199             :                 ;
    2200             : 
    2201             : stmt_null       : K_NULL ';'
    2202             :                     {
    2203             :                         /* We do not bother building a node for NULL */
    2204          20 :                         $$ = NULL;
    2205             :                     }
    2206             :                 ;
    2207             : 
    2208             : stmt_commit     : K_COMMIT opt_transaction_chain ';'
    2209             :                     {
    2210             :                         PLpgSQL_stmt_commit *new;
    2211             : 
    2212          60 :                         new = palloc(sizeof(PLpgSQL_stmt_commit));
    2213          60 :                         new->cmd_type = PLPGSQL_STMT_COMMIT;
    2214          60 :                         new->lineno = plpgsql_location_to_lineno(@1);
    2215          60 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
    2216          60 :                         new->chain = $2;
    2217             : 
    2218          60 :                         $$ = (PLpgSQL_stmt *)new;
    2219             :                     }
    2220             :                 ;
    2221             : 
    2222             : stmt_rollback   : K_ROLLBACK opt_transaction_chain ';'
    2223             :                     {
    2224             :                         PLpgSQL_stmt_rollback *new;
    2225             : 
    2226          30 :                         new = palloc(sizeof(PLpgSQL_stmt_rollback));
    2227          30 :                         new->cmd_type = PLPGSQL_STMT_ROLLBACK;
    2228          30 :                         new->lineno = plpgsql_location_to_lineno(@1);
    2229          30 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
    2230          30 :                         new->chain = $2;
    2231             : 
    2232          30 :                         $$ = (PLpgSQL_stmt *)new;
    2233             :                     }
    2234             :                 ;
    2235             : 
    2236             : opt_transaction_chain:
    2237           4 :             K_AND K_CHAIN           { $$ = true; }
    2238           0 :             | K_AND K_NO K_CHAIN    { $$ = false; }
    2239          86 :             | /* EMPTY */           { $$ = false; }
    2240             :                 ;
    2241             : 
    2242             : stmt_set    : K_SET
    2243             :                     {
    2244             :                         PLpgSQL_stmt_set *new;
    2245             : 
    2246          62 :                         new = palloc0(sizeof(PLpgSQL_stmt_set));
    2247          62 :                         new->cmd_type = PLPGSQL_STMT_SET;
    2248          62 :                         new->lineno = plpgsql_location_to_lineno(@1);
    2249          62 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
    2250             : 
    2251          62 :                         new->expr = read_sql_stmt("SET ");
    2252             : 
    2253          62 :                         $$ = (PLpgSQL_stmt *)new;
    2254             :                     }
    2255             :             | K_RESET
    2256             :                     {
    2257             :                         PLpgSQL_stmt_set *new;
    2258             : 
    2259           2 :                         new = palloc0(sizeof(PLpgSQL_stmt_set));
    2260           2 :                         new->cmd_type = PLPGSQL_STMT_SET;
    2261           2 :                         new->lineno = plpgsql_location_to_lineno(@1);
    2262           2 :                         new->stmtid = ++plpgsql_curr_compile->nstatements;
    2263           2 :                         new->expr = read_sql_stmt("RESET ");
    2264             : 
    2265           2 :                         $$ = (PLpgSQL_stmt *)new;
    2266             :                     }
    2267             :             ;
    2268             : 
    2269             : 
    2270             : cursor_variable : T_DATUM
    2271             :                     {
    2272             :                         /*
    2273             :                          * In principle we should support a cursor_variable
    2274             :                          * that is an array element, but for now we don't, so
    2275             :                          * just throw an error if next token is '['.
    2276             :                          */
    2277         440 :                         if ($1.datum->dtype != PLPGSQL_DTYPE_VAR ||
    2278         220 :                             plpgsql_peek() == '[')
    2279           0 :                             ereport(ERROR,
    2280             :                                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2281             :                                      errmsg("cursor variable must be a simple variable"),
    2282             :                                      parser_errposition(@1)));
    2283             : 
    2284         220 :                         if (((PLpgSQL_var *) $1.datum)->datatype->typoid != REFCURSOROID)
    2285           0 :                             ereport(ERROR,
    2286             :                                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2287             :                                      errmsg("variable \"%s\" must be of type cursor or refcursor",
    2288             :                                             ((PLpgSQL_var *) $1.datum)->refname),
    2289             :                                      parser_errposition(@1)));
    2290         220 :                         $$ = (PLpgSQL_var *) $1.datum;
    2291             :                     }
    2292             :                 | T_WORD
    2293             :                     {
    2294             :                         /* just to give a better message than "syntax error" */
    2295           0 :                         word_is_not_variable(&($1), @1);
    2296             :                     }
    2297             :                 | T_CWORD
    2298             :                     {
    2299             :                         /* just to give a better message than "syntax error" */
    2300           0 :                         cword_is_not_variable(&($1), @1);
    2301             :                     }
    2302             :                 ;
    2303             : 
    2304             : exception_sect  :
    2305        3590 :                     { $$ = NULL; }
    2306             :                 | K_EXCEPTION
    2307             :                     {
    2308             :                         /*
    2309             :                          * We use a mid-rule action to add these
    2310             :                          * special variables to the namespace before
    2311             :                          * parsing the WHEN clauses themselves.  The
    2312             :                          * scope of the names extends to the end of the
    2313             :                          * current block.
    2314             :                          */
    2315         160 :                         int         lineno = plpgsql_location_to_lineno(@1);
    2316         160 :                         PLpgSQL_exception_block *new = palloc(sizeof(PLpgSQL_exception_block));
    2317             :                         PLpgSQL_variable *var;
    2318             : 
    2319         160 :                         var = plpgsql_build_variable("sqlstate", lineno,
    2320             :                                                      plpgsql_build_datatype(TEXTOID,
    2321             :                                                                             -1,
    2322         160 :                                                                             plpgsql_curr_compile->fn_input_collation,
    2323             :                                                                             NULL),
    2324             :                                                      true);
    2325         160 :                         var->isconst = true;
    2326         160 :                         new->sqlstate_varno = var->dno;
    2327             : 
    2328         160 :                         var = plpgsql_build_variable("sqlerrm", lineno,
    2329             :                                                      plpgsql_build_datatype(TEXTOID,
    2330             :                                                                             -1,
    2331         160 :                                                                             plpgsql_curr_compile->fn_input_collation,
    2332             :                                                                             NULL),
    2333             :                                                      true);
    2334         160 :                         var->isconst = true;
    2335         160 :                         new->sqlerrm_varno = var->dno;
    2336             : 
    2337         160 :                         $<exception_block>$ = new;
    2338             :                     }
    2339             :                     proc_exceptions
    2340             :                     {
    2341         160 :                         PLpgSQL_exception_block *new = $<exception_block>2;
    2342         160 :                         new->exc_list = $3;
    2343             : 
    2344         160 :                         $$ = new;
    2345             :                     }
    2346             :                 ;
    2347             : 
    2348             : proc_exceptions : proc_exceptions proc_exception
    2349             :                         {
    2350          10 :                             $$ = lappend($1, $2);
    2351             :                         }
    2352             :                 | proc_exception
    2353             :                         {
    2354         160 :                             $$ = list_make1($1);
    2355             :                         }
    2356             :                 ;
    2357             : 
    2358             : proc_exception  : K_WHEN proc_conditions K_THEN proc_sect
    2359             :                     {
    2360             :                         PLpgSQL_exception *new;
    2361             : 
    2362         170 :                         new = palloc0(sizeof(PLpgSQL_exception));
    2363         170 :                         new->lineno = plpgsql_location_to_lineno(@1);
    2364         170 :                         new->conditions = $2;
    2365         170 :                         new->action = $4;
    2366             : 
    2367         170 :                         $$ = new;
    2368             :                     }
    2369             :                 ;
    2370             : 
    2371             : proc_conditions : proc_conditions K_OR proc_condition
    2372             :                         {
    2373             :                             PLpgSQL_condition   *old;
    2374             : 
    2375          10 :                             for (old = $1; old->next != NULL; old = old->next)
    2376             :                                 /* skip */ ;
    2377          10 :                             old->next = $3;
    2378          10 :                             $$ = $1;
    2379             :                         }
    2380             :                 | proc_condition
    2381             :                         {
    2382         170 :                             $$ = $1;
    2383             :                         }
    2384             :                 ;
    2385             : 
    2386             : proc_condition  : any_identifier
    2387             :                         {
    2388         180 :                             if (strcmp($1, "sqlstate") != 0)
    2389             :                             {
    2390         160 :                                 $$ = plpgsql_parse_err_condition($1);
    2391             :                             }
    2392             :                             else
    2393             :                             {
    2394             :                                 PLpgSQL_condition *new;
    2395             :                                 char   *sqlstatestr;
    2396             : 
    2397             :                                 /* next token should be a string literal */
    2398          20 :                                 if (yylex() != SCONST)
    2399           0 :                                     yyerror("syntax error");
    2400          20 :                                 sqlstatestr = yylval.str;
    2401             : 
    2402          20 :                                 if (strlen(sqlstatestr) != 5)
    2403           0 :                                     yyerror("invalid SQLSTATE code");
    2404          20 :                                 if (strspn(sqlstatestr, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") != 5)
    2405           0 :                                     yyerror("invalid SQLSTATE code");
    2406             : 
    2407          20 :                                 new = palloc(sizeof(PLpgSQL_condition));
    2408          20 :                                 new->sqlerrstate =
    2409          20 :                                     MAKE_SQLSTATE(sqlstatestr[0],
    2410             :                                                   sqlstatestr[1],
    2411             :                                                   sqlstatestr[2],
    2412             :                                                   sqlstatestr[3],
    2413             :                                                   sqlstatestr[4]);
    2414          20 :                                 new->condname = sqlstatestr;
    2415          20 :                                 new->next = NULL;
    2416             : 
    2417          20 :                                 $$ = new;
    2418             :                             }
    2419             :                         }
    2420             :                 ;
    2421             : 
    2422             : expr_until_semi :
    2423        2388 :                     { $$ = read_sql_expression(';', ";"); }
    2424             :                 ;
    2425             : 
    2426             : expr_until_rightbracket :
    2427          50 :                     { $$ = read_sql_expression(']', "]"); }
    2428             :                 ;
    2429             : 
    2430             : expr_until_then :
    2431        2794 :                     { $$ = read_sql_expression(K_THEN, "THEN"); }
    2432             :                 ;
    2433             : 
    2434             : expr_until_loop :
    2435          94 :                     { $$ = read_sql_expression(K_LOOP, "LOOP"); }
    2436             :                 ;
    2437             : 
    2438             : opt_block_label :
    2439             :                     {
    2440        3822 :                         plpgsql_ns_push(NULL, PLPGSQL_LABEL_BLOCK);
    2441        3822 :                         $$ = NULL;
    2442             :                     }
    2443             :                 | LESS_LESS any_identifier GREATER_GREATER
    2444             :                     {
    2445          36 :                         plpgsql_ns_push($2, PLPGSQL_LABEL_BLOCK);
    2446          36 :                         $$ = $2;
    2447             :                     }
    2448             :                 ;
    2449             : 
    2450             : opt_loop_label  :
    2451             :                     {
    2452         618 :                         plpgsql_ns_push(NULL, PLPGSQL_LABEL_LOOP);
    2453         618 :                         $$ = NULL;
    2454             :                     }
    2455             :                 | LESS_LESS any_identifier GREATER_GREATER
    2456             :                     {
    2457          30 :                         plpgsql_ns_push($2, PLPGSQL_LABEL_LOOP);
    2458          30 :                         $$ = $2;
    2459             :                     }
    2460             :                 ;
    2461             : 
    2462             : opt_label   :
    2463             :                     {
    2464        4438 :                         $$ = NULL;
    2465             :                     }
    2466             :                 | any_identifier
    2467             :                     {
    2468             :                         /* label validity will be checked by outer production */
    2469          40 :                         $$ = $1;
    2470             :                     }
    2471             :                 ;
    2472             : 
    2473             : opt_exitcond    : ';'
    2474          54 :                     { $$ = NULL; }
    2475             :                 | K_WHEN expr_until_semi
    2476          46 :                     { $$ = $2; }
    2477             :                 ;
    2478             : 
    2479             : /*
    2480             :  * need to allow DATUM because scanner will have tried to resolve as variable
    2481             :  */
    2482             : any_identifier  : T_WORD
    2483             :                     {
    2484         266 :                         $$ = $1.ident;
    2485             :                     }
    2486             :                 | unreserved_keyword
    2487             :                     {
    2488           0 :                         $$ = pstrdup($1);
    2489             :                     }
    2490             :                 | T_DATUM
    2491             :                     {
    2492          20 :                         if ($1.ident == NULL) /* composite name not OK */
    2493           0 :                             yyerror("syntax error");
    2494          20 :                         $$ = $1.ident;
    2495             :                     }
    2496             :                 ;
    2497             : 
    2498             : unreserved_keyword  :
    2499             :                 K_ABSOLUTE
    2500             :                 | K_ALIAS
    2501             :                 | K_AND
    2502             :                 | K_ARRAY
    2503             :                 | K_ASSERT
    2504             :                 | K_BACKWARD
    2505             :                 | K_CALL
    2506             :                 | K_CHAIN
    2507             :                 | K_CLOSE
    2508             :                 | K_COLLATE
    2509             :                 | K_COLUMN
    2510             :                 | K_COLUMN_NAME
    2511             :                 | K_COMMIT
    2512             :                 | K_CONSTANT
    2513             :                 | K_CONSTRAINT
    2514             :                 | K_CONSTRAINT_NAME
    2515             :                 | K_CONTINUE
    2516             :                 | K_CURRENT
    2517             :                 | K_CURSOR
    2518             :                 | K_DATATYPE
    2519             :                 | K_DEBUG
    2520             :                 | K_DEFAULT
    2521             :                 | K_DETAIL
    2522             :                 | K_DIAGNOSTICS
    2523             :                 | K_DO
    2524             :                 | K_DUMP
    2525             :                 | K_ELSIF
    2526             :                 | K_ERRCODE
    2527             :                 | K_ERROR
    2528             :                 | K_EXCEPTION
    2529             :                 | K_EXIT
    2530             :                 | K_FETCH
    2531             :                 | K_FIRST
    2532             :                 | K_FORWARD
    2533             :                 | K_GET
    2534             :                 | K_HINT
    2535             :                 | K_IMPORT
    2536             :                 | K_INFO
    2537             :                 | K_INSERT
    2538             :                 | K_IS
    2539             :                 | K_LAST
    2540             :                 | K_LOG
    2541             :                 | K_MESSAGE
    2542             :                 | K_MESSAGE_TEXT
    2543             :                 | K_MOVE
    2544             :                 | K_NEXT
    2545             :                 | K_NO
    2546             :                 | K_NOTICE
    2547             :                 | K_OPEN
    2548             :                 | K_OPTION
    2549             :                 | K_PERFORM
    2550             :                 | K_PG_CONTEXT
    2551             :                 | K_PG_DATATYPE_NAME
    2552             :                 | K_PG_EXCEPTION_CONTEXT
    2553             :                 | K_PG_EXCEPTION_DETAIL
    2554             :                 | K_PG_EXCEPTION_HINT
    2555             :                 | K_PRINT_STRICT_PARAMS
    2556             :                 | K_PRIOR
    2557             :                 | K_QUERY
    2558             :                 | K_RAISE
    2559             :                 | K_RELATIVE
    2560             :                 | K_RESET
    2561             :                 | K_RETURN
    2562             :                 | K_RETURNED_SQLSTATE
    2563             :                 | K_REVERSE
    2564             :                 | K_ROLLBACK
    2565             :                 | K_ROW_COUNT
    2566             :                 | K_ROWTYPE
    2567             :                 | K_SCHEMA
    2568             :                 | K_SCHEMA_NAME
    2569             :                 | K_SCROLL
    2570             :                 | K_SET
    2571             :                 | K_SLICE
    2572             :                 | K_SQLSTATE
    2573             :                 | K_STACKED
    2574             :                 | K_TABLE
    2575             :                 | K_TABLE_NAME
    2576             :                 | K_TYPE
    2577             :                 | K_USE_COLUMN
    2578             :                 | K_USE_VARIABLE
    2579             :                 | K_VARIABLE_CONFLICT
    2580             :                 | K_WARNING
    2581             :                 ;
    2582             : 
    2583             : %%
    2584             : 
    2585             : /*
    2586             :  * Check whether a token represents an "unreserved keyword".
    2587             :  * We have various places where we want to recognize a keyword in preference
    2588             :  * to a variable name, but not reserve that keyword in other contexts.
    2589             :  * Hence, this kluge.
    2590             :  */
    2591             : static bool
    2592       18710 : tok_is_keyword(int token, union YYSTYPE *lval,
    2593             :                int kw_token, const char *kw_str)
    2594             : {
    2595       18710 :     if (token == kw_token)
    2596             :     {
    2597             :         /* Normal case, was recognized by scanner (no conflicting variable) */
    2598        3482 :         return true;
    2599             :     }
    2600       15228 :     else if (token == T_DATUM)
    2601             :     {
    2602             :         /*
    2603             :          * It's a variable, so recheck the string name.  Note we will not
    2604             :          * match composite names (hence an unreserved word followed by "."
    2605             :          * will not be recognized).
    2606             :          */
    2607        8688 :         if (!lval->wdatum.quoted && lval->wdatum.ident != NULL &&
    2608        4284 :             strcmp(lval->wdatum.ident, kw_str) == 0)
    2609           4 :             return true;
    2610             :     }
    2611       15224 :     return false;               /* not the keyword */
    2612             : }
    2613             : 
    2614             : /*
    2615             :  * Convenience routine to complain when we expected T_DATUM and got T_WORD,
    2616             :  * ie, unrecognized variable.
    2617             :  */
    2618             : static void
    2619           0 : word_is_not_variable(PLword *word, int location)
    2620             : {
    2621           0 :     ereport(ERROR,
    2622             :             (errcode(ERRCODE_SYNTAX_ERROR),
    2623             :              errmsg("\"%s\" is not a known variable",
    2624             :                     word->ident),
    2625             :              parser_errposition(location)));
    2626             : }
    2627             : 
    2628             : /* Same, for a CWORD */
    2629             : static void
    2630           0 : cword_is_not_variable(PLcword *cword, int location)
    2631             : {
    2632           0 :     ereport(ERROR,
    2633             :             (errcode(ERRCODE_SYNTAX_ERROR),
    2634             :              errmsg("\"%s\" is not a known variable",
    2635             :                     NameListToString(cword->idents)),
    2636             :              parser_errposition(location)));
    2637             : }
    2638             : 
    2639             : /*
    2640             :  * Convenience routine to complain when we expected T_DATUM and got
    2641             :  * something else.  "tok" must be the current token, since we also
    2642             :  * look at yylval and yylloc.
    2643             :  */
    2644             : static void
    2645           0 : current_token_is_not_variable(int tok)
    2646             : {
    2647           0 :     if (tok == T_WORD)
    2648           0 :         word_is_not_variable(&(yylval.word), yylloc);
    2649           0 :     else if (tok == T_CWORD)
    2650           0 :         cword_is_not_variable(&(yylval.cword), yylloc);
    2651             :     else
    2652           0 :         yyerror("syntax error");
    2653           0 : }
    2654             : 
    2655             : /* Convenience routine to read an expression with one possible terminator */
    2656             : static PLpgSQL_expr *
    2657        7624 : read_sql_expression(int until, const char *expected)
    2658             : {
    2659        7624 :     return read_sql_construct(until, 0, 0, expected,
    2660             :                               "SELECT ", true, true, true, NULL, NULL);
    2661             : }
    2662             : 
    2663             : /* Convenience routine to read an expression with two possible terminators */
    2664             : static PLpgSQL_expr *
    2665         570 : read_sql_expression2(int until, int until2, const char *expected,
    2666             :                      int *endtoken)
    2667             : {
    2668         570 :     return read_sql_construct(until, until2, 0, expected,
    2669             :                               "SELECT ", true, true, true, NULL, endtoken);
    2670             : }
    2671             : 
    2672             : /* Convenience routine to read a SQL statement that must end with ';' */
    2673             : static PLpgSQL_expr *
    2674         250 : read_sql_stmt(const char *sqlstart)
    2675             : {
    2676         250 :     return read_sql_construct(';', 0, 0, ";",
    2677             :                               sqlstart, false, true, true, NULL, NULL);
    2678             : }
    2679             : 
    2680             : /*
    2681             :  * Read a SQL construct and build a PLpgSQL_expr for it.
    2682             :  *
    2683             :  * until:       token code for expected terminator
    2684             :  * until2:      token code for alternate terminator (pass 0 if none)
    2685             :  * until3:      token code for another alternate terminator (pass 0 if none)
    2686             :  * expected:    text to use in complaining that terminator was not found
    2687             :  * sqlstart:    text to prefix to the accumulated SQL text
    2688             :  * isexpression: whether to say we're reading an "expression" or a "statement"
    2689             :  * valid_sql:   whether to check the syntax of the expr (prefixed with sqlstart)
    2690             :  * trim:        trim trailing whitespace
    2691             :  * startloc:    if not NULL, location of first token is stored at *startloc
    2692             :  * endtoken:    if not NULL, ending token is stored at *endtoken
    2693             :  *              (this is only interesting if until2 or until3 isn't zero)
    2694             :  */
    2695             : static PLpgSQL_expr *
    2696       14008 : read_sql_construct(int until,
    2697             :                    int until2,
    2698             :                    int until3,
    2699             :                    const char *expected,
    2700             :                    const char *sqlstart,
    2701             :                    bool isexpression,
    2702             :                    bool valid_sql,
    2703             :                    bool trim,
    2704             :                    int *startloc,
    2705             :                    int *endtoken)
    2706             : {
    2707             :     int                 tok;
    2708             :     StringInfoData      ds;
    2709             :     IdentifierLookup    save_IdentifierLookup;
    2710       14008 :     int                 startlocation = -1;
    2711       14008 :     int                 parenlevel = 0;
    2712             :     PLpgSQL_expr        *expr;
    2713             : 
    2714       14008 :     initStringInfo(&ds);
    2715       14008 :     appendStringInfoString(&ds, sqlstart);
    2716             : 
    2717             :     /* special lookup mode for identifiers within the SQL text */
    2718       14008 :     save_IdentifierLookup = plpgsql_IdentifierLookup;
    2719       14008 :     plpgsql_IdentifierLookup = IDENTIFIER_LOOKUP_EXPR;
    2720             : 
    2721             :     for (;;)
    2722             :     {
    2723       98632 :         tok = yylex();
    2724       56320 :         if (startlocation < 0)           /* remember loc of first token */
    2725       14008 :             startlocation = yylloc;
    2726       56320 :         if (tok == until && parenlevel == 0)
    2727       11092 :             break;
    2728       45228 :         if (tok == until2 && parenlevel == 0)
    2729        2800 :             break;
    2730       42428 :         if (tok == until3 && parenlevel == 0)
    2731         116 :             break;
    2732       42312 :         if (tok == '(' || tok == '[')
    2733        3334 :             parenlevel++;
    2734       38978 :         else if (tok == ')' || tok == ']')
    2735             :         {
    2736        3334 :             parenlevel--;
    2737        3334 :             if (parenlevel < 0)
    2738           0 :                 yyerror("mismatched parentheses");
    2739             :         }
    2740             :         /*
    2741             :          * End of function definition is an error, and we don't expect to
    2742             :          * hit a semicolon either (unless it's the until symbol, in which
    2743             :          * case we should have fallen out above).
    2744             :          */
    2745       42312 :         if (tok == 0 || tok == ';')
    2746             :         {
    2747           0 :             if (parenlevel != 0)
    2748           0 :                 yyerror("mismatched parentheses");
    2749           0 :             if (isexpression)
    2750           0 :                 ereport(ERROR,
    2751             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    2752             :                          errmsg("missing \"%s\" at end of SQL expression",
    2753             :                                 expected),
    2754             :                          parser_errposition(yylloc)));
    2755             :             else
    2756           0 :                 ereport(ERROR,
    2757             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    2758             :                          errmsg("missing \"%s\" at end of SQL statement",
    2759             :                                 expected),
    2760             :                          parser_errposition(yylloc)));
    2761             :         }
    2762             :     }
    2763             : 
    2764       14008 :     plpgsql_IdentifierLookup = save_IdentifierLookup;
    2765             : 
    2766       14008 :     if (startloc)
    2767         412 :         *startloc = startlocation;
    2768       14008 :     if (endtoken)
    2769        6118 :         *endtoken = tok;
    2770             : 
    2771             :     /* give helpful complaint about empty input */
    2772       14008 :     if (startlocation >= yylloc)
    2773             :     {
    2774           4 :         if (isexpression)
    2775           4 :             yyerror("missing expression");
    2776             :         else
    2777           0 :             yyerror("missing SQL statement");
    2778             :     }
    2779             : 
    2780       14004 :     plpgsql_append_source_text(&ds, startlocation, yylloc);
    2781             : 
    2782             :     /* trim any trailing whitespace, for neatness */
    2783       14004 :     if (trim)
    2784             :     {
    2785       32348 :         while (ds.len > 0 && scanner_isspace(ds.data[ds.len - 1]))
    2786        4508 :             ds.data[--ds.len] = '\0';
    2787             :     }
    2788             : 
    2789       14004 :     expr = palloc0(sizeof(PLpgSQL_expr));
    2790       14004 :     expr->query          = pstrdup(ds.data);
    2791       14004 :     expr->plan           = NULL;
    2792       14004 :     expr->paramnos       = NULL;
    2793       14004 :     expr->rwparam        = -1;
    2794       14004 :     expr->ns         = plpgsql_ns_top();
    2795       14004 :     pfree(ds.data);
    2796             : 
    2797       14004 :     if (valid_sql)
    2798       13592 :         check_sql_expr(expr->query, startlocation, strlen(sqlstart));
    2799             : 
    2800       14004 :     return expr;
    2801             : }
    2802             : 
    2803             : static PLpgSQL_type *
    2804        2306 : read_datatype(int tok)
    2805             : {
    2806             :     StringInfoData      ds;
    2807             :     char               *type_name;
    2808             :     int                 startlocation;
    2809             :     PLpgSQL_type        *result;
    2810        2306 :     int                 parenlevel = 0;
    2811             : 
    2812             :     /* Should only be called while parsing DECLARE sections */
    2813             :     Assert(plpgsql_IdentifierLookup == IDENTIFIER_LOOKUP_DECLARE);
    2814             : 
    2815             :     /* Often there will be a lookahead token, but if not, get one */
    2816        2306 :     if (tok == YYEMPTY)
    2817         110 :         tok = yylex();
    2818             : 
    2819        2306 :     startlocation = yylloc;
    2820             : 
    2821             :     /*
    2822             :      * If we have a simple or composite identifier, check for %TYPE
    2823             :      * and %ROWTYPE constructs.
    2824             :      */
    2825        2306 :     if (tok == T_WORD)
    2826             :     {
    2827        2290 :         char   *dtname = yylval.word.ident;
    2828             : 
    2829        2290 :         tok = yylex();
    2830        2290 :         if (tok == '%')
    2831             :         {
    2832          40 :             tok = yylex();
    2833          40 :             if (tok_is_keyword(tok, &yylval,
    2834             :                                K_TYPE, "type"))
    2835             :             {
    2836           0 :                 result = plpgsql_parse_wordtype(dtname);
    2837           0 :                 if (result)
    2838           0 :                     return result;
    2839             :             }
    2840          40 :             else if (tok_is_keyword(tok, &yylval,
    2841             :                                     K_ROWTYPE, "rowtype"))
    2842             :             {
    2843          40 :                 result = plpgsql_parse_wordrowtype(dtname);
    2844          40 :                 if (result)
    2845          40 :                     return result;
    2846             :             }
    2847             :         }
    2848             :     }
    2849          16 :     else if (plpgsql_token_is_unreserved_keyword(tok))
    2850             :     {
    2851           0 :         char   *dtname = pstrdup(yylval.keyword);
    2852             : 
    2853           0 :         tok = yylex();
    2854           0 :         if (tok == '%')
    2855             :         {
    2856           0 :             tok = yylex();
    2857           0 :             if (tok_is_keyword(tok, &yylval,
    2858             :                                K_TYPE, "type"))
    2859             :             {
    2860           0 :                 result = plpgsql_parse_wordtype(dtname);
    2861           0 :                 if (result)
    2862           0 :                     return result;
    2863             :             }
    2864           0 :             else if (tok_is_keyword(tok, &yylval,
    2865             :                                     K_ROWTYPE, "rowtype"))
    2866             :             {
    2867           0 :                 result = plpgsql_parse_wordrowtype(dtname);
    2868           0 :                 if (result)
    2869           0 :                     return result;
    2870             :             }
    2871             :         }
    2872             :     }
    2873          16 :     else if (tok == T_CWORD)
    2874             :     {
    2875          16 :         List   *dtnames = yylval.cword.idents;
    2876             : 
    2877          16 :         tok = yylex();
    2878          16 :         if (tok == '%')
    2879             :         {
    2880          16 :             tok = yylex();
    2881          16 :             if (tok_is_keyword(tok, &yylval,
    2882             :                                K_TYPE, "type"))
    2883             :             {
    2884          16 :                 result = plpgsql_parse_cwordtype(dtnames);
    2885          16 :                 if (result)
    2886          16 :                     return result;
    2887             :             }
    2888           0 :             else if (tok_is_keyword(tok, &yylval,
    2889             :                                     K_ROWTYPE, "rowtype"))
    2890             :             {
    2891           0 :                 result = plpgsql_parse_cwordrowtype(dtnames);
    2892           0 :                 if (result)
    2893           0 :                     return result;
    2894             :             }
    2895             :         }
    2896             :     }
    2897             : 
    2898        5028 :     while (tok != ';')
    2899             :     {
    2900        1010 :         if (tok == 0)
    2901             :         {
    2902           0 :             if (parenlevel != 0)
    2903           0 :                 yyerror("mismatched parentheses");
    2904             :             else
    2905           0 :                 yyerror("incomplete data type declaration");
    2906             :         }
    2907             :         /* Possible followers for datatype in a declaration */
    2908        1010 :         if (tok == K_COLLATE || tok == K_NOT ||
    2909         892 :             tok == '=' || tok == COLON_EQUALS || tok == K_DEFAULT)
    2910             :             break;
    2911             :         /* Possible followers for datatype in a cursor_arg list */
    2912         624 :         if ((tok == ',' || tok == ')') && parenlevel == 0)
    2913          96 :             break;
    2914         528 :         if (tok == '(')
    2915          76 :             parenlevel++;
    2916         452 :         else if (tok == ')')
    2917          76 :             parenlevel--;
    2918             : 
    2919         528 :         tok = yylex();
    2920             :     }
    2921             : 
    2922             :     /* set up ds to contain complete typename text */
    2923        2250 :     initStringInfo(&ds);
    2924        2250 :     plpgsql_append_source_text(&ds, startlocation, yylloc);
    2925        2250 :     type_name = ds.data;
    2926             : 
    2927        2250 :     if (type_name[0] == '\0')
    2928           0 :         yyerror("missing data type declaration");
    2929             : 
    2930        2250 :     result = parse_datatype(type_name, startlocation);
    2931             : 
    2932        2248 :     pfree(ds.data);
    2933             : 
    2934        2248 :     plpgsql_push_back_token(tok);
    2935             : 
    2936        2248 :     return result;
    2937             : }
    2938             : 
    2939             : static PLpgSQL_stmt *
    2940        1356 : make_execsql_stmt(int firsttoken, int location)
    2941             : {
    2942             :     StringInfoData      ds;
    2943             :     IdentifierLookup    save_IdentifierLookup;
    2944             :     PLpgSQL_stmt_execsql *execsql;
    2945             :     PLpgSQL_expr        *expr;
    2946        1356 :     PLpgSQL_variable    *target = NULL;
    2947             :     int                 tok;
    2948             :     int                 prev_tok;
    2949        1356 :     bool                have_into = false;
    2950        1356 :     bool                have_strict = false;
    2951        1356 :     int                 into_start_loc = -1;
    2952        1356 :     int                 into_end_loc = -1;
    2953             : 
    2954        1356 :     initStringInfo(&ds);
    2955             : 
    2956             :     /* special lookup mode for identifiers within the SQL text */
    2957        1356 :     save_IdentifierLookup = plpgsql_IdentifierLookup;
    2958        1356 :     plpgsql_IdentifierLookup = IDENTIFIER_LOOKUP_EXPR;
    2959             : 
    2960             :     /*
    2961             :      * Scan to the end of the SQL command.  Identify any INTO-variables
    2962             :      * clause lurking within it, and parse that via read_into_target().
    2963             :      *
    2964             :      * Because INTO is sometimes used in the main SQL grammar, we have to be
    2965             :      * careful not to take any such usage of INTO as a PL/pgSQL INTO clause.
    2966             :      * There are currently three such cases:
    2967             :      *
    2968             :      * 1. SELECT ... INTO.  We don't care, we just override that with the
    2969             :      * PL/pgSQL definition.
    2970             :      *
    2971             :      * 2. INSERT INTO.  This is relatively easy to recognize since the words
    2972             :      * must appear adjacently; but we can't assume INSERT starts the command,
    2973             :      * because it can appear in CREATE RULE or WITH.  Unfortunately, INSERT is
    2974             :      * *not* fully reserved, so that means there is a chance of a false match;
    2975             :      * but it's not very likely.
    2976             :      *
    2977             :      * 3. IMPORT FOREIGN SCHEMA ... INTO.  This is not allowed in CREATE RULE
    2978             :      * or WITH, so we just check for IMPORT as the command's first token.
    2979             :      * (If IMPORT FOREIGN SCHEMA returned data someone might wish to capture
    2980             :      * with an INTO-variables clause, we'd have to work much harder here.)
    2981             :      *
    2982             :      * Fortunately, INTO is a fully reserved word in the main grammar, so
    2983             :      * at least we need not worry about it appearing as an identifier.
    2984             :      *
    2985             :      * Any future additional uses of INTO in the main grammar will doubtless
    2986             :      * break this logic again ... beware!
    2987             :      */
    2988        1356 :     tok = firsttoken;
    2989             :     for (;;)
    2990             :     {
    2991       27944 :         prev_tok = tok;
    2992       14650 :         tok = yylex();
    2993       14650 :         if (have_into && into_end_loc < 0)
    2994         466 :             into_end_loc = yylloc;      /* token after the INTO part */
    2995       14650 :         if (tok == ';')
    2996        1356 :             break;
    2997       13294 :         if (tok == 0)
    2998           0 :             yyerror("unexpected end of function definition");
    2999       13294 :         if (tok == K_INTO)
    3000             :         {
    3001         822 :             if (prev_tok == K_INSERT)
    3002         356 :                 continue;       /* INSERT INTO is not an INTO-target */
    3003         466 :             if (firsttoken == K_IMPORT)
    3004           0 :                 continue;       /* IMPORT ... INTO is not an INTO-target */
    3005         466 :             if (have_into)
    3006           0 :                 yyerror("INTO specified more than once");
    3007         466 :             have_into = true;
    3008         466 :             into_start_loc = yylloc;
    3009         466 :             plpgsql_IdentifierLookup = IDENTIFIER_LOOKUP_NORMAL;
    3010         466 :             read_into_target(&target, &have_strict);
    3011         466 :             plpgsql_IdentifierLookup = IDENTIFIER_LOOKUP_EXPR;
    3012             :         }
    3013             :     }
    3014             : 
    3015        1356 :     plpgsql_IdentifierLookup = save_IdentifierLookup;
    3016             : 
    3017        1356 :     if (have_into)
    3018             :     {
    3019             :         /*
    3020             :          * Insert an appropriate number of spaces corresponding to the
    3021             :          * INTO text, so that locations within the redacted SQL statement
    3022             :          * still line up with those in the original source text.
    3023             :          */
    3024         466 :         plpgsql_append_source_text(&ds, location, into_start_loc);
    3025         466 :         appendStringInfoSpaces(&ds, into_end_loc - into_start_loc);
    3026         466 :         plpgsql_append_source_text(&ds, into_end_loc, yylloc);
    3027             :     }
    3028             :     else
    3029         890 :         plpgsql_append_source_text(&ds, location, yylloc);
    3030             : 
    3031             :     /* trim any trailing whitespace, for neatness */
    3032        4140 :     while (ds.len > 0 && scanner_isspace(ds.data[ds.len - 1]))
    3033        1428 :         ds.data[--ds.len] = '\0';
    3034             : 
    3035        1356 :     expr = palloc0(sizeof(PLpgSQL_expr));
    3036        1356 :     expr->query          = pstrdup(ds.data);
    3037        1356 :     expr->plan           = NULL;
    3038        1356 :     expr->paramnos       = NULL;
    3039        1356 :     expr->rwparam        = -1;
    3040        1356 :     expr->ns         = plpgsql_ns_top();
    3041        1356 :     pfree(ds.data);
    3042             : 
    3043        1356 :     check_sql_expr(expr->query, location, 0);
    3044             : 
    3045        1352 :     execsql = palloc(sizeof(PLpgSQL_stmt_execsql));
    3046        1352 :     execsql->cmd_type = PLPGSQL_STMT_EXECSQL;
    3047        1352 :     execsql->lineno  = plpgsql_location_to_lineno(location);
    3048        1352 :     execsql->stmtid  = ++plpgsql_curr_compile->nstatements;
    3049        1352 :     execsql->sqlstmt = expr;
    3050        1352 :     execsql->into     = have_into;
    3051        1352 :     execsql->strict   = have_strict;
    3052        1352 :     execsql->target   = target;
    3053             : 
    3054        1352 :     return (PLpgSQL_stmt *) execsql;
    3055             : }
    3056             : 
    3057             : 
    3058             : /*
    3059             :  * Read FETCH or MOVE direction clause (everything through FROM/IN).
    3060             :  */
    3061             : static PLpgSQL_stmt_fetch *
    3062          92 : read_fetch_direction(void)
    3063             : {
    3064             :     PLpgSQL_stmt_fetch *fetch;
    3065             :     int         tok;
    3066          92 :     bool        check_FROM = true;
    3067             : 
    3068             :     /*
    3069             :      * We create the PLpgSQL_stmt_fetch struct here, but only fill in
    3070             :      * the fields arising from the optional direction clause
    3071             :      */
    3072          92 :     fetch = (PLpgSQL_stmt_fetch *) palloc0(sizeof(PLpgSQL_stmt_fetch));
    3073          92 :     fetch->cmd_type = PLPGSQL_STMT_FETCH;
    3074          92 :     fetch->stmtid    = ++plpgsql_curr_compile->nstatements;
    3075             :     /* set direction defaults: */
    3076          92 :     fetch->direction = FETCH_FORWARD;
    3077          92 :     fetch->how_many  = 1;
    3078          92 :     fetch->expr       = NULL;
    3079          92 :     fetch->returns_multiple_rows = false;
    3080             : 
    3081          92 :     tok = yylex();
    3082          92 :     if (tok == 0)
    3083           0 :         yyerror("unexpected end of function definition");
    3084             : 
    3085          92 :     if (tok_is_keyword(tok, &yylval,
    3086             :                        K_NEXT, "next"))
    3087             :     {
    3088             :         /* use defaults */
    3089             :     }
    3090          84 :     else if (tok_is_keyword(tok, &yylval,
    3091             :                             K_PRIOR, "prior"))
    3092             :     {
    3093          12 :         fetch->direction = FETCH_BACKWARD;
    3094             :     }
    3095          72 :     else if (tok_is_keyword(tok, &yylval,
    3096             :                             K_FIRST, "first"))
    3097             :     {
    3098           0 :         fetch->direction = FETCH_ABSOLUTE;
    3099             :     }
    3100          72 :     else if (tok_is_keyword(tok, &yylval,
    3101             :                             K_LAST, "last"))
    3102             :     {
    3103          20 :         fetch->direction = FETCH_ABSOLUTE;
    3104          20 :         fetch->how_many  = -1;
    3105             :     }
    3106          52 :     else if (tok_is_keyword(tok, &yylval,
    3107             :                             K_ABSOLUTE, "absolute"))
    3108             :     {
    3109           0 :         fetch->direction = FETCH_ABSOLUTE;
    3110           0 :         fetch->expr = read_sql_expression2(K_FROM, K_IN,
    3111             :                                            "FROM or IN",
    3112             :                                            NULL);
    3113           0 :         check_FROM = false;
    3114             :     }
    3115          52 :     else if (tok_is_keyword(tok, &yylval,
    3116             :                             K_RELATIVE, "relative"))
    3117             :     {
    3118          12 :         fetch->direction = FETCH_RELATIVE;
    3119          12 :         fetch->expr = read_sql_expression2(K_FROM, K_IN,
    3120             :                                            "FROM or IN",
    3121             :                                            NULL);
    3122          12 :         check_FROM = false;
    3123             :     }
    3124          40 :     else if (tok_is_keyword(tok, &yylval,
    3125             :                             K_ALL, "all"))
    3126             :     {
    3127           0 :         fetch->how_many = FETCH_ALL;
    3128           0 :         fetch->returns_multiple_rows = true;
    3129             :     }
    3130          40 :     else if (tok_is_keyword(tok, &yylval,
    3131             :                             K_FORWARD, "forward"))
    3132             :     {
    3133           4 :         complete_direction(fetch, &check_FROM);
    3134             :     }
    3135          36 :     else if (tok_is_keyword(tok, &yylval,
    3136             :                             K_BACKWARD, "backward"))
    3137             :     {
    3138           8 :         fetch->direction = FETCH_BACKWARD;
    3139           8 :         complete_direction(fetch, &check_FROM);
    3140             :     }
    3141          28 :     else if (tok == K_FROM || tok == K_IN)
    3142             :     {
    3143             :         /* empty direction */
    3144           0 :         check_FROM = false;
    3145             :     }
    3146          28 :     else if (tok == T_DATUM)
    3147             :     {
    3148             :         /* Assume there's no direction clause and tok is a cursor name */
    3149          28 :         plpgsql_push_back_token(tok);
    3150          28 :         check_FROM = false;
    3151             :     }
    3152             :     else
    3153             :     {
    3154             :         /*
    3155             :          * Assume it's a count expression with no preceding keyword.
    3156             :          * Note: we allow this syntax because core SQL does, but we don't
    3157             :          * document it because of the ambiguity with the omitted-direction
    3158             :          * case.  For instance, "MOVE n IN c" will fail if n is a variable.
    3159             :          * Perhaps this can be improved someday, but it's hardly worth a
    3160             :          * lot of work.
    3161             :          */
    3162           0 :         plpgsql_push_back_token(tok);
    3163           0 :         fetch->expr = read_sql_expression2(K_FROM, K_IN,
    3164             :                                            "FROM or IN",
    3165             :                                            NULL);
    3166           0 :         fetch->returns_multiple_rows = true;
    3167           0 :         check_FROM = false;
    3168             :     }
    3169             : 
    3170             :     /* check FROM or IN keyword after direction's specification */
    3171          92 :     if (check_FROM)
    3172             :     {
    3173          44 :         tok = yylex();
    3174          44 :         if (tok != K_FROM && tok != K_IN)
    3175           0 :             yyerror("expected FROM or IN");
    3176             :     }
    3177             : 
    3178          92 :     return fetch;
    3179             : }
    3180             : 
    3181             : /*
    3182             :  * Process remainder of FETCH/MOVE direction after FORWARD or BACKWARD.
    3183             :  * Allows these cases:
    3184             :  *   FORWARD expr,  FORWARD ALL,  FORWARD
    3185             :  *   BACKWARD expr, BACKWARD ALL, BACKWARD
    3186             :  */
    3187             : static void
    3188          12 : complete_direction(PLpgSQL_stmt_fetch *fetch,  bool *check_FROM)
    3189             : {
    3190             :     int         tok;
    3191             : 
    3192          12 :     tok = yylex();
    3193          12 :     if (tok == 0)
    3194           0 :         yyerror("unexpected end of function definition");
    3195             : 
    3196          12 :     if (tok == K_FROM || tok == K_IN)
    3197             :     {
    3198           4 :         *check_FROM = false;
    3199           4 :         return;
    3200             :     }
    3201             : 
    3202           8 :     if (tok == K_ALL)
    3203             :     {
    3204           4 :         fetch->how_many = FETCH_ALL;
    3205           4 :         fetch->returns_multiple_rows = true;
    3206           4 :         *check_FROM = true;
    3207           4 :         return;
    3208             :     }
    3209             : 
    3210           4 :     plpgsql_push_back_token(tok);
    3211           4 :     fetch->expr = read_sql_expression2(K_FROM, K_IN,
    3212             :                                        "FROM or IN",
    3213             :                                        NULL);
    3214           4 :     fetch->returns_multiple_rows = true;
    3215           4 :     *check_FROM = false;
    3216             : }
    3217             : 
    3218             : 
    3219             : static PLpgSQL_stmt *
    3220        3822 : make_return_stmt(int location)
    3221             : {
    3222             :     PLpgSQL_stmt_return *new;
    3223             : 
    3224        3822 :     new = palloc0(sizeof(PLpgSQL_stmt_return));
    3225        3822 :     new->cmd_type = PLPGSQL_STMT_RETURN;
    3226        3822 :     new->lineno   = plpgsql_location_to_lineno(location);
    3227        3822 :     new->stmtid    = ++plpgsql_curr_compile->nstatements;
    3228        3822 :     new->expr      = NULL;
    3229        3822 :     new->retvarno = -1;
    3230             : 
    3231        3822 :     if (plpgsql_curr_compile->fn_retset)
    3232             :     {
    3233          24 :         if (yylex() != ';')
    3234           0 :             ereport(ERROR,
    3235             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3236             :                      errmsg("RETURN cannot have a parameter in function returning set"),
    3237             :                      errhint("Use RETURN NEXT or RETURN QUERY."),
    3238             :                      parser_errposition(yylloc)));
    3239             :     }
    3240        3798 :     else if (plpgsql_curr_compile->fn_rettype == VOIDOID)
    3241             :     {
    3242          52 :         if (yylex() != ';')
    3243             :         {
    3244          10 :             if (plpgsql_curr_compile->fn_prokind == PROKIND_PROCEDURE)
    3245           2 :                 ereport(ERROR,
    3246             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    3247             :                          errmsg("RETURN cannot have a parameter in a procedure"),
    3248             :                          parser_errposition(yylloc)));
    3249             :             else
    3250           8 :                 ereport(ERROR,
    3251             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    3252             :                          errmsg("RETURN cannot have a parameter in function returning void"),
    3253             :                          parser_errposition(yylloc)));
    3254             :         }
    3255             :     }
    3256        3746 :     else if (plpgsql_curr_compile->out_param_varno >= 0)
    3257             :     {
    3258          20 :         if (yylex() != ';')
    3259           4 :             ereport(ERROR,
    3260             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3261             :                      errmsg("RETURN cannot have a parameter in function with OUT parameters"),
    3262             :                      parser_errposition(yylloc)));
    3263          16 :         new->retvarno = plpgsql_curr_compile->out_param_varno;
    3264             :     }
    3265             :     else
    3266             :     {
    3267             :         /*
    3268             :          * We want to special-case simple variable references for efficiency.
    3269             :          * So peek ahead to see if that's what we have.
    3270             :          */
    3271        3726 :         int     tok = yylex();
    3272             : 
    3273        5630 :         if (tok == T_DATUM && plpgsql_peek() == ';' &&
    3274        3510 :             (yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_VAR ||
    3275        3212 :              yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_PROMISE ||
    3276        3212 :              yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_ROW ||
    3277        1606 :              yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_REC))
    3278             :         {
    3279        1862 :             new->retvarno = yylval.wdatum.datum->dno;
    3280             :             /* eat the semicolon token that we only peeked at above */
    3281        1862 :             tok = yylex();
    3282        1862 :             Assert(tok == ';');
    3283             :         }
    3284             :         else
    3285             :         {
    3286             :             /*
    3287             :              * Not (just) a variable name, so treat as expression.
    3288             :              *
    3289             :              * Note that a well-formed expression is _required_ here;
    3290             :              * anything else is a compile-time error.
    3291             :              */
    3292        1864 :             plpgsql_push_back_token(tok);
    3293        1864 :             new->expr = read_sql_expression(';', ";");
    3294             :         }
    3295             :     }
    3296             : 
    3297        3804 :     return (PLpgSQL_stmt *) new;
    3298             : }
    3299             : 
    3300             : 
    3301             : static PLpgSQL_stmt *
    3302         162 : make_return_next_stmt(int location)
    3303             : {
    3304             :     PLpgSQL_stmt_return_next *new;
    3305             : 
    3306         162 :     if (!plpgsql_curr_compile->fn_retset)
    3307           0 :         ereport(ERROR,
    3308             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3309             :                  errmsg("cannot use RETURN NEXT in a non-SETOF function"),
    3310             :                  parser_errposition(location)));
    3311             : 
    3312         162 :     new = palloc0(sizeof(PLpgSQL_stmt_return_next));
    3313         162 :     new->cmd_type    = PLPGSQL_STMT_RETURN_NEXT;
    3314         162 :     new->lineno      = plpgsql_location_to_lineno(location);
    3315         162 :     new->stmtid      = ++plpgsql_curr_compile->nstatements;
    3316         162 :     new->expr        = NULL;
    3317         162 :     new->retvarno    = -1;
    3318             : 
    3319         162 :     if (plpgsql_curr_compile->out_param_varno >= 0)
    3320             :     {
    3321          40 :         if (yylex() != ';')
    3322           0 :             ereport(ERROR,
    3323             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3324             :                      errmsg("RETURN NEXT cannot have a parameter in function with OUT parameters"),
    3325             :                      parser_errposition(yylloc)));
    3326          40 :         new->retvarno = plpgsql_curr_compile->out_param_varno;
    3327             :     }
    3328             :     else
    3329             :     {
    3330             :         /*
    3331             :          * We want to special-case simple variable references for efficiency.
    3332             :          * So peek ahead to see if that's what we have.
    3333             :          */
    3334         122 :         int     tok = yylex();
    3335             : 
    3336         218 :         if (tok == T_DATUM && plpgsql_peek() == ';' &&
    3337         144 :             (yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_VAR ||
    3338          96 :              yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_PROMISE ||
    3339          96 :              yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_ROW ||
    3340          48 :              yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_REC))
    3341             :         {
    3342          96 :             new->retvarno = yylval.wdatum.datum->dno;
    3343             :             /* eat the semicolon token that we only peeked at above */
    3344          96 :             tok = yylex();
    3345          96 :             Assert(tok == ';');
    3346             :         }
    3347             :         else
    3348             :         {
    3349             :             /*
    3350             :              * Not (just) a variable name, so treat as expression.
    3351             :              *
    3352             :              * Note that a well-formed expression is _required_ here;
    3353             :              * anything else is a compile-time error.
    3354             :              */
    3355          26 :             plpgsql_push_back_token(tok);
    3356          26 :             new->expr = read_sql_expression(';', ";");
    3357             :         }
    3358             :     }
    3359             : 
    3360         162 :     return (PLpgSQL_stmt *) new;
    3361             : }
    3362             : 
    3363             : 
    3364             : static PLpgSQL_stmt *
    3365          64 : make_return_query_stmt(int location)
    3366             : {
    3367             :     PLpgSQL_stmt_return_query *new;
    3368             :     int         tok;
    3369             : 
    3370          64 :     if (!plpgsql_curr_compile->fn_retset)
    3371           0 :         ereport(ERROR,
    3372             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3373             :                  errmsg("cannot use RETURN QUERY in a non-SETOF function"),
    3374             :                  parser_errposition(location)));
    3375             : 
    3376          64 :     new = palloc0(sizeof(PLpgSQL_stmt_return_query));
    3377          64 :     new->cmd_type = PLPGSQL_STMT_RETURN_QUERY;
    3378          64 :     new->lineno = plpgsql_location_to_lineno(location);
    3379          64 :     new->stmtid = ++plpgsql_curr_compile->nstatements;
    3380             : 
    3381             :     /* check for RETURN QUERY EXECUTE */
    3382          64 :     if ((tok = yylex()) != K_EXECUTE)
    3383             :     {
    3384             :         /* ordinary static query */
    3385          44 :         plpgsql_push_back_token(tok);
    3386          44 :         new->query = read_sql_stmt("");
    3387             :     }
    3388             :     else
    3389             :     {
    3390             :         /* dynamic SQL */
    3391             :         int     term;
    3392             : 
    3393          20 :         new->dynquery = read_sql_expression2(';', K_USING, "; or USING",
    3394             :                                              &term);
    3395          20 :         if (term == K_USING)
    3396             :         {
    3397             :             do
    3398             :             {
    3399             :                 PLpgSQL_expr *expr;
    3400             : 
    3401           8 :                 expr = read_sql_expression2(',', ';', ", or ;", &term);
    3402           8 :                 new->params = lappend(new->params, expr);
    3403           8 :             } while (term == ',');
    3404             :         }
    3405             :     }
    3406             : 
    3407          64 :     return (PLpgSQL_stmt *) new;
    3408             : }
    3409             : 
    3410             : 
    3411             : /* convenience routine to fetch the name of a T_DATUM */
    3412             : static char *
    3413         706 : NameOfDatum(PLwdatum *wdatum)
    3414             : {
    3415         706 :     if (wdatum->ident)
    3416         674 :         return wdatum->ident;
    3417             :     Assert(wdatum->idents != NIL);
    3418          32 :     return NameListToString(wdatum->idents);
    3419             : }
    3420             : 
    3421             : static void
    3422        3640 : check_assignable(PLpgSQL_datum *datum, int location)
    3423             : {
    3424        3640 :     switch (datum->dtype)
    3425             :     {
    3426             :         case PLPGSQL_DTYPE_VAR:
    3427             :         case PLPGSQL_DTYPE_PROMISE:
    3428             :         case PLPGSQL_DTYPE_REC:
    3429        3248 :             if (((PLpgSQL_variable *) datum)->isconst)
    3430          10 :                 ereport(ERROR,
    3431             :                         (errcode(ERRCODE_ERROR_IN_ASSIGNMENT),
    3432             :                          errmsg("variable \"%s\" is declared CONSTANT",
    3433             :                                 ((PLpgSQL_variable *) datum)->refname),
    3434             :                          parser_errposition(location)));
    3435        3238 :             break;
    3436             :         case PLPGSQL_DTYPE_ROW:
    3437             :             /* always assignable; member vars were checked at compile time */
    3438          16 :             break;
    3439             :         case PLPGSQL_DTYPE_RECFIELD:
    3440             :             /* assignable if parent record is */
    3441         376 :             check_assignable(plpgsql_Datums[((PLpgSQL_recfield *) datum)->recparentno],
    3442             :                              location);
    3443         372 :             break;
    3444             :         case PLPGSQL_DTYPE_ARRAYELEM:
    3445             :             /* assignable if parent array is */
    3446           0 :             check_assignable(plpgsql_Datums[((PLpgSQL_arrayelem *) datum)->arrayparentno],
    3447             :                              location);
    3448           0 :             break;
    3449             :         default:
    3450           0 :             elog(ERROR, "unrecognized dtype: %d", datum->dtype);
    3451             :             break;
    3452             :     }
    3453        3626 : }
    3454             : 
    3455             : /*
    3456             :  * Read the argument of an INTO clause.  On entry, we have just read the
    3457             :  * INTO keyword.
    3458             :  */
    3459             : static void
    3460         650 : read_into_target(PLpgSQL_variable **target, bool *strict)
    3461             : {
    3462             :     int         tok;
    3463             : 
    3464             :     /* Set default results */
    3465         650 :     *target = NULL;
    3466         650 :     if (strict)
    3467         570 :         *strict = false;
    3468             : 
    3469         650 :     tok = yylex();
    3470         650 :     if (strict && tok == K_STRICT)
    3471             :     {
    3472          56 :         *strict = true;
    3473          56 :         tok = yylex();
    3474             :     }
    3475             : 
    3476             :     /*
    3477             :      * Currently, a row or record variable can be the single INTO target,
    3478             :      * but not a member of a multi-target list.  So we throw error if there
    3479             :      * is a comma after it, because that probably means the user tried to
    3480             :      * write a multi-target list.  If this ever gets generalized, we should
    3481             :      * probably refactor read_into_scalar_list so it handles all cases.
    3482             :      */
    3483         650 :     switch (tok)
    3484             :     {
    3485             :         case T_DATUM:
    3486        1300 :             if (yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_ROW ||
    3487         650 :                 yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_REC)
    3488             :             {
    3489         384 :                 check_assignable(yylval.wdatum.datum, yylloc);
    3490         384 :                 *target = (PLpgSQL_variable *) yylval.wdatum.datum;
    3491             : 
    3492         384 :                 if ((tok = yylex()) == ',')
    3493           0 :                     ereport(ERROR,
    3494             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3495             :                              errmsg("record variable cannot be part of multiple-item INTO list"),
    3496             :                              parser_errposition(yylloc)));
    3497         384 :                 plpgsql_push_back_token(tok);
    3498             :             }
    3499             :             else
    3500             :             {
    3501         266 :                 *target = (PLpgSQL_variable *)
    3502         266 :                     read_into_scalar_list(NameOfDatum(&(yylval.wdatum)),
    3503             :                                           yylval.wdatum.datum, yylloc);
    3504             :             }
    3505         650 :             break;
    3506             : 
    3507             :         default:
    3508             :             /* just to give a better message than "syntax error" */
    3509           0 :             current_token_is_not_variable(tok);
    3510             :     }
    3511         650 : }
    3512             : 
    3513             : /*
    3514             :  * Given the first datum and name in the INTO list, continue to read
    3515             :  * comma-separated scalar variables until we run out. Then construct
    3516             :  * and return a fake "row" variable that represents the list of
    3517             :  * scalars.
    3518             :  */
    3519             : static PLpgSQL_row *
    3520         286 : read_into_scalar_list(char *initial_name,
    3521             :                       PLpgSQL_datum *initial_datum,
    3522             :                       int initial_location)
    3523             : {
    3524             :     int              nfields;
    3525             :     char            *fieldnames[1024];
    3526             :     int              varnos[1024];
    3527             :     PLpgSQL_row     *row;
    3528             :     int              tok;
    3529             : 
    3530         286 :     check_assignable(initial_datum, initial_location);
    3531         282 :     fieldnames[0] = initial_name;
    3532         282 :     varnos[0]     = initial_datum->dno;
    3533         282 :     nfields       = 1;
    3534             : 
    3535         652 :     while ((tok = yylex()) == ',')
    3536             :     {
    3537             :         /* Check for array overflow */
    3538          88 :         if (nfields >= 1024)
    3539           0 :             ereport(ERROR,
    3540             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    3541             :                      errmsg("too many INTO variables specified"),
    3542             :                      parser_errposition(yylloc)));
    3543             : 
    3544          88 :         tok = yylex();
    3545          88 :         switch (tok)
    3546             :         {
    3547             :             case T_DATUM:
    3548          88 :                 check_assignable(yylval.wdatum.datum, yylloc);
    3549         176 :                 if (yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_ROW ||
    3550          88 :                     yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_REC)
    3551           0 :                     ereport(ERROR,
    3552             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3553             :                              errmsg("\"%s\" is not a scalar variable",
    3554             :                                     NameOfDatum(&(yylval.wdatum))),
    3555             :                              parser_errposition(yylloc)));
    3556          88 :                 fieldnames[nfields] = NameOfDatum(&(yylval.wdatum));
    3557          88 :                 varnos[nfields++]   = yylval.wdatum.datum->dno;
    3558          88 :                 break;
    3559             : 
    3560             :             default:
    3561             :                 /* just to give a better message than "syntax error" */
    3562           0 :                 current_token_is_not_variable(tok);
    3563             :         }
    3564             :     }
    3565             : 
    3566             :     /*
    3567             :      * We read an extra, non-comma token from yylex(), so push it
    3568             :      * back onto the input stream
    3569             :      */
    3570         282 :     plpgsql_push_back_token(tok);
    3571             : 
    3572         282 :     row = palloc0(sizeof(PLpgSQL_row));
    3573         282 :     row->dtype = PLPGSQL_DTYPE_ROW;
    3574         282 :     row->refname = "(unnamed row)";
    3575         282 :     row->lineno = plpgsql_location_to_lineno(initial_location);
    3576         282 :     row->rowtupdesc = NULL;
    3577         282 :     row->nfields = nfields;
    3578         282 :     row->fieldnames = palloc(sizeof(char *) * nfields);
    3579         282 :     row->varnos = palloc(sizeof(int) * nfields);
    3580         934 :     while (--nfields >= 0)
    3581             :     {
    3582         370 :         row->fieldnames[nfields] = fieldnames[nfields];
    3583         370 :         row->varnos[nfields] = varnos[nfields];
    3584             :     }
    3585             : 
    3586         282 :     plpgsql_adddatum((PLpgSQL_datum *)row);
    3587             : 
    3588         282 :     return row;
    3589             : }
    3590             : 
    3591             : /*
    3592             :  * Convert a single scalar into a "row" list.  This is exactly
    3593             :  * like read_into_scalar_list except we never consume any input.
    3594             :  *
    3595             :  * Note: lineno could be computed from location, but since callers
    3596             :  * have it at hand already, we may as well pass it in.
    3597             :  */
    3598             : static PLpgSQL_row *
    3599          94 : make_scalar_list1(char *initial_name,
    3600             :                   PLpgSQL_datum *initial_datum,
    3601             :                   int lineno, int location)
    3602             : {
    3603             :     PLpgSQL_row     *row;
    3604             : 
    3605          94 :     check_assignable(initial_datum, location);
    3606             : 
    3607          94 :     row = palloc0(sizeof(PLpgSQL_row));
    3608          94 :     row->dtype = PLPGSQL_DTYPE_ROW;
    3609          94 :     row->refname = "(unnamed row)";
    3610          94 :     row->lineno = lineno;
    3611          94 :     row->rowtupdesc = NULL;
    3612          94 :     row->nfields = 1;
    3613          94 :     row->fieldnames = palloc(sizeof(char *));
    3614          94 :     row->varnos = palloc(sizeof(int));
    3615          94 :     row->fieldnames[0] = initial_name;
    3616          94 :     row->varnos[0] = initial_datum->dno;
    3617             : 
    3618          94 :     plpgsql_adddatum((PLpgSQL_datum *)row);
    3619             : 
    3620          94 :     return row;
    3621             : }
    3622             : 
    3623             : /*
    3624             :  * When the PL/pgSQL parser expects to see a SQL statement, it is very
    3625             :  * liberal in what it accepts; for example, we often assume an
    3626             :  * unrecognized keyword is the beginning of a SQL statement. This
    3627             :  * avoids the need to duplicate parts of the SQL grammar in the
    3628             :  * PL/pgSQL grammar, but it means we can accept wildly malformed
    3629             :  * input. To try and catch some of the more obviously invalid input,
    3630             :  * we run the strings we expect to be SQL statements through the main
    3631             :  * SQL parser.
    3632             :  *
    3633             :  * We only invoke the raw parser (not the analyzer); this doesn't do
    3634             :  * any database access and does not check any semantic rules, it just
    3635             :  * checks for basic syntactic correctness. We do this here, rather
    3636             :  * than after parsing has finished, because a malformed SQL statement
    3637             :  * may cause the PL/pgSQL parser to become confused about statement
    3638             :  * borders. So it is best to bail out as early as we can.
    3639             :  *
    3640             :  * It is assumed that "stmt" represents a copy of the function source text
    3641             :  * beginning at offset "location", with leader text of length "leaderlen"
    3642             :  * (typically "SELECT ") prefixed to the source text.  We use this assumption
    3643             :  * to transpose any error cursor position back to the function source text.
    3644             :  * If no error cursor is provided, we'll just point at "location".
    3645             :  */
    3646             : static void
    3647       15360 : check_sql_expr(const char *stmt, int location, int leaderlen)
    3648             : {
    3649             :     sql_error_callback_arg cbarg;
    3650             :     ErrorContextCallback  syntax_errcontext;
    3651             :     MemoryContext oldCxt;
    3652             : 
    3653       15360 :     if (!plpgsql_check_syntax)
    3654        7676 :         return;
    3655             : 
    3656        7684 :     cbarg.location = location;
    3657        7684 :     cbarg.leaderlen = leaderlen;
    3658             : 
    3659        7684 :     syntax_errcontext.callback = plpgsql_sql_error_callback;
    3660        7684 :     syntax_errcontext.arg = &cbarg;
    3661        7684 :     syntax_errcontext.previous = error_context_stack;
    3662        7684 :     error_context_stack = &syntax_errcontext;
    3663             : 
    3664        7684 :     oldCxt = MemoryContextSwitchTo(plpgsql_compile_tmp_cxt);
    3665        7684 :     (void) raw_parser(stmt);
    3666        7676 :     MemoryContextSwitchTo(oldCxt);
    3667             : 
    3668             :     /* Restore former ereport callback */
    3669        7676 :     error_context_stack = syntax_errcontext.previous;
    3670             : }
    3671             : 
    3672             : static void
    3673          14 : plpgsql_sql_error_callback(void *arg)
    3674             : {
    3675          14 :     sql_error_callback_arg *cbarg = (sql_error_callback_arg *) arg;
    3676             :     int         errpos;
    3677             : 
    3678             :     /*
    3679             :      * First, set up internalerrposition to point to the start of the
    3680             :      * statement text within the function text.  Note this converts
    3681             :      * location (a byte offset) to a character number.
    3682             :      */
    3683          14 :     parser_errposition(cbarg->location);
    3684             : 
    3685             :     /*
    3686             :      * If the core parser provided an error position, transpose it.
    3687             :      * Note we are dealing with 1-based character numbers at this point.
    3688             :      */
    3689          14 :     errpos = geterrposition();
    3690          14 :     if (errpos > cbarg->leaderlen)
    3691             :     {
    3692          12 :         int     myerrpos = getinternalerrposition();
    3693             : 
    3694          12 :         if (myerrpos > 0)        /* safety check */
    3695          12 :             internalerrposition(myerrpos + errpos - cbarg->leaderlen - 1);
    3696             :     }
    3697             : 
    3698             :     /* In any case, flush errposition --- we want internalerrposition only */
    3699          14 :     errposition(0);
    3700          14 : }
    3701             : 
    3702             : /*
    3703             :  * Parse a SQL datatype name and produce a PLpgSQL_type structure.
    3704             :  *
    3705             :  * The heavy lifting is done elsewhere.  Here we are only concerned
    3706             :  * with setting up an errcontext link that will let us give an error
    3707             :  * cursor pointing into the plpgsql function source, if necessary.
    3708             :  * This is handled the same as in check_sql_expr(), and we likewise
    3709             :  * expect that the given string is a copy from the source text.
    3710             :  */
    3711             : static PLpgSQL_type *
    3712        2250 : parse_datatype(const char *string, int location)
    3713             : {
    3714             :     TypeName   *typeName;
    3715             :     Oid         type_id;
    3716             :     int32       typmod;
    3717             :     sql_error_callback_arg cbarg;
    3718             :     ErrorContextCallback  syntax_errcontext;
    3719             : 
    3720        2250 :     cbarg.location = location;
    3721        2250 :     cbarg.leaderlen = 0;
    3722             : 
    3723        2250 :     syntax_errcontext.callback = plpgsql_sql_error_callback;
    3724        2250 :     syntax_errcontext.arg = &cbarg;
    3725        2250 :     syntax_errcontext.previous = error_context_stack;
    3726        2250 :     error_context_stack = &syntax_errcontext;
    3727             : 
    3728             :     /* Let the main parser try to parse it under standard SQL rules */
    3729        2250 :     typeName = typeStringToTypeName(string);
    3730        2250 :     typenameTypeIdAndMod(NULL, typeName, &type_id, &typmod);
    3731             : 
    3732             :     /* Restore former ereport callback */
    3733        2248 :     error_context_stack = syntax_errcontext.previous;
    3734             : 
    3735             :     /* Okay, build a PLpgSQL_type data structure for it */
    3736        2248 :     return plpgsql_build_datatype(type_id, typmod,
    3737        2248 :                                   plpgsql_curr_compile->fn_input_collation,
    3738             :                                   typeName);
    3739             : }
    3740             : 
    3741             : /*
    3742             :  * Check block starting and ending labels match.
    3743             :  */
    3744             : static void
    3745        4378 : check_labels(const char *start_label, const char *end_label, int end_location)
    3746             : {
    3747        4378 :     if (end_label)
    3748             :     {
    3749          10 :         if (!start_label)
    3750           4 :             ereport(ERROR,
    3751             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    3752             :                      errmsg("end label \"%s\" specified for unlabelled block",
    3753             :                             end_label),
    3754             :                      parser_errposition(end_location)));
    3755             : 
    3756           6 :         if (strcmp(start_label, end_label) != 0)
    3757           2 :             ereport(ERROR,
    3758             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    3759             :                      errmsg("end label \"%s\" differs from block's label \"%s\"",
    3760             :                             end_label, start_label),
    3761             :                      parser_errposition(end_location)));
    3762             :     }
    3763        4372 : }
    3764             : 
    3765             : /*
    3766             :  * Read the arguments (if any) for a cursor, followed by the until token
    3767             :  *
    3768             :  * If cursor has no args, just swallow the until token and return NULL.
    3769             :  * If it does have args, we expect to see "( arg [, arg ...] )" followed
    3770             :  * by the until token, where arg may be a plain expression, or a named
    3771             :  * parameter assignment of the form argname := expr. Consume all that and
    3772             :  * return a SELECT query that evaluates the expression(s) (without the outer
    3773             :  * parens).
    3774             :  */
    3775             : static PLpgSQL_expr *
    3776          80 : read_cursor_args(PLpgSQL_var *cursor, int until, const char *expected)
    3777             : {
    3778             :     PLpgSQL_expr *expr;
    3779             :     PLpgSQL_row *row;
    3780             :     int         tok;
    3781             :     int         argc;
    3782             :     char      **argv;
    3783             :     StringInfoData ds;
    3784          80 :     char       *sqlstart = "SELECT ";
    3785          80 :     bool        any_named = false;
    3786             : 
    3787          80 :     tok = yylex();
    3788          80 :     if (cursor->cursor_explicit_argrow < 0)
    3789             :     {
    3790             :         /* No arguments expected */
    3791          32 :         if (tok == '(')
    3792           0 :             ereport(ERROR,
    3793             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    3794             :                      errmsg("cursor \"%s\" has no arguments",
    3795             :                             cursor->refname),
    3796             :                      parser_errposition(yylloc)));
    3797             : 
    3798          32 :         if (tok != until)
    3799           0 :             yyerror("syntax error");
    3800             : 
    3801          32 :         return NULL;
    3802             :     }
    3803             : 
    3804             :     /* Else better provide arguments */
    3805          48 :     if (tok != '(')
    3806           0 :         ereport(ERROR,
    3807             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    3808             :                  errmsg("cursor \"%s\" has arguments",
    3809             :                         cursor->refname),
    3810             :                  parser_errposition(yylloc)));
    3811             : 
    3812             :     /*
    3813             :      * Read the arguments, one by one.
    3814             :      */
    3815          48 :     row = (PLpgSQL_row *) plpgsql_Datums[cursor->cursor_explicit_argrow];
    3816          48 :     argv = (char **) palloc0(row->nfields * sizeof(char *));
    3817             : 
    3818         128 :     for (argc = 0; argc < row->nfields; argc++)
    3819             :     {
    3820             :         PLpgSQL_expr *item;
    3821             :         int     endtoken;
    3822             :         int     argpos;
    3823             :         int     tok1,
    3824             :                 tok2;
    3825             :         int     arglocation;
    3826             : 
    3827             :         /* Check if it's a named parameter: "param := value" */
    3828          96 :         plpgsql_peek2(&tok1, &tok2, &arglocation, NULL);
    3829          96 :         if (tok1 == IDENT && tok2 == COLON_EQUALS)
    3830          52 :         {
    3831             :             char   *argname;
    3832             :             IdentifierLookup save_IdentifierLookup;
    3833             : 
    3834             :             /* Read the argument name, ignoring any matching variable */
    3835          52 :             save_IdentifierLookup = plpgsql_IdentifierLookup;
    3836          52 :             plpgsql_IdentifierLookup = IDENTIFIER_LOOKUP_DECLARE;
    3837          52 :             yylex();
    3838          52 :             argname = yylval.str;
    3839          52 :             plpgsql_IdentifierLookup = save_IdentifierLookup;
    3840             : 
    3841             :             /* Match argument name to cursor arguments */
    3842          88 :             for (argpos = 0; argpos < row->nfields; argpos++)
    3843             :             {
    3844          88 :                 if (strcmp(row->fieldnames[argpos], argname) == 0)
    3845          52 :                     break;
    3846             :             }
    3847          52 :             if (argpos == row->nfields)
    3848           0 :                 ereport(ERROR,
    3849             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    3850             :                          errmsg("cursor \"%s\" has no argument named \"%s\"",
    3851             :                                 cursor->refname, argname),
    3852             :                          parser_errposition(yylloc)));
    3853             : 
    3854             :             /*
    3855             :              * Eat the ":=". We already peeked, so the error should never
    3856             :              * happen.
    3857             :              */
    3858          52 :             tok2 = yylex();
    3859          52 :             if (tok2 != COLON_EQUALS)
    3860           0 :                 yyerror("syntax error");
    3861             : 
    3862          52 :             any_named = true;
    3863             :         }
    3864             :         else
    3865          44 :             argpos = argc;
    3866             : 
    3867          96 :         if (argv[argpos] != NULL)
    3868          12 :             ereport(ERROR,
    3869             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    3870             :                      errmsg("value for parameter \"%s\" of cursor \"%s\" specified more than once",
    3871             :                             row->fieldnames[argpos], cursor->refname),
    3872             :                      parser_errposition(arglocation)));
    3873             : 
    3874             :         /*
    3875             :          * Read the value expression. To provide the user with meaningful
    3876             :          * parse error positions, we check the syntax immediately, instead of
    3877             :          * checking the final expression that may have the arguments
    3878             :          * reordered. Trailing whitespace must not be trimmed, because
    3879             :          * otherwise input of the form (param -- comment\n, param) would be
    3880             :          * translated into a form where the second parameter is commented
    3881             :          * out.
    3882             :          */
    3883          84 :         item = read_sql_construct(',', ')', 0,
    3884             :                                   ",\" or \")",
    3885             :                                   sqlstart,
    3886             :                                   true, true,
    3887             :                                   false, /* do not trim */
    3888             :                                   NULL, &endtoken);
    3889             : 
    3890          84 :         argv[argpos] = item->query + strlen(sqlstart);
    3891             : 
    3892          84 :         if (endtoken == ')' && !(argc == row->nfields - 1))
    3893           4 :             ereport(ERROR,
    3894             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    3895             :                      errmsg("not enough arguments for cursor \"%s\"",
    3896             :                             cursor->refname),
    3897             :                      parser_errposition(yylloc)));
    3898             : 
    3899          80 :         if (endtoken == ',' && (argc == row->nfields - 1))
    3900           0 :             ereport(ERROR,
    3901             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    3902             :                      errmsg("too many arguments for cursor \"%s\"",
    3903             :                             cursor->refname),
    3904             :                      parser_errposition(yylloc)));
    3905             :     }
    3906             : 
    3907             :     /* Make positional argument list */
    3908          32 :     initStringInfo(&ds);
    3909          32 :     appendStringInfoString(&ds, sqlstart);
    3910         100 :     for (argc = 0; argc < row->nfields; argc++)
    3911             :     {
    3912             :         Assert(argv[argc] != NULL);
    3913             : 
    3914             :         /*
    3915             :          * Because named notation allows permutated argument lists, include
    3916             :          * the parameter name for meaningful runtime errors.
    3917             :          */
    3918          68 :         appendStringInfoString(&ds, argv[argc]);
    3919          68 :         if (any_named)
    3920          36 :             appendStringInfo(&ds, " AS %s",
    3921          36 :                              quote_identifier(row->fieldnames[argc]));
    3922          68 :         if (argc < row->nfields - 1)
    3923          36 :             appendStringInfoString(&ds, ", ");
    3924             :     }
    3925          32 :     appendStringInfoChar(&ds, ';');
    3926             : 
    3927          32 :     expr = palloc0(sizeof(PLpgSQL_expr));
    3928          32 :     expr->query          = pstrdup(ds.data);
    3929          32 :     expr->plan           = NULL;
    3930          32 :     expr->paramnos       = NULL;
    3931          32 :     expr->rwparam        = -1;
    3932          32 :     expr->ns            = plpgsql_ns_top();
    3933          32 :     pfree(ds.data);
    3934             : 
    3935             :     /* Next we'd better find the until token */
    3936          32 :     tok = yylex();
    3937          32 :     if (tok != until)
    3938           0 :         yyerror("syntax error");
    3939             : 
    3940          32 :     return expr;
    3941             : }
    3942             : 
    3943             : /*
    3944             :  * Parse RAISE ... USING options
    3945             :  */
    3946             : static List *
    3947         140 : read_raise_options(void)
    3948             : {
    3949         140 :     List       *result = NIL;
    3950             : 
    3951             :     for (;;)
    3952          68 :     {
    3953             :         PLpgSQL_raise_option *opt;
    3954             :         int     tok;
    3955             : 
    3956         208 :         if ((tok = yylex()) == 0)
    3957           0 :             yyerror("unexpected end of function definition");
    3958             : 
    3959         208 :         opt = (PLpgSQL_raise_option *) palloc(sizeof(PLpgSQL_raise_option));
    3960             : 
    3961         208 :         if (tok_is_keyword(tok, &yylval,
    3962             :                            K_ERRCODE, "errcode"))
    3963          32 :             opt->opt_type = PLPGSQL_RAISEOPTION_ERRCODE;
    3964         176 :         else if (tok_is_keyword(tok, &yylval,
    3965             :                                 K_MESSAGE, "message"))
    3966         104 :             opt->opt_type = PLPGSQL_RAISEOPTION_MESSAGE;
    3967          72 :         else if (tok_is_keyword(tok, &yylval,
    3968             :                                 K_DETAIL, "detail"))
    3969          32 :             opt->opt_type = PLPGSQL_RAISEOPTION_DETAIL;
    3970          40 :         else if (tok_is_keyword(tok, &yylval,
    3971             :                                 K_HINT, "hint"))
    3972          10 :             opt->opt_type = PLPGSQL_RAISEOPTION_HINT;
    3973          30 :         else if (tok_is_keyword(tok, &yylval,
    3974             :                                 K_COLUMN, "column"))
    3975           6 :             opt->opt_type = PLPGSQL_RAISEOPTION_COLUMN;
    3976          24 :         else if (tok_is_keyword(tok, &yylval,
    3977             :                                 K_CONSTRAINT, "constraint"))
    3978           6 :             opt->opt_type = PLPGSQL_RAISEOPTION_CONSTRAINT;
    3979          18 :         else if (tok_is_keyword(tok, &yylval,
    3980             :                                 K_DATATYPE, "datatype"))
    3981           6 :             opt->opt_type = PLPGSQL_RAISEOPTION_DATATYPE;
    3982          12 :         else if (tok_is_keyword(tok, &yylval,
    3983             :                                 K_TABLE, "table"))
    3984           6 :             opt->opt_type = PLPGSQL_RAISEOPTION_TABLE;
    3985           6 :         else if (tok_is_keyword(tok, &yylval,
    3986             :                                 K_SCHEMA, "schema"))
    3987           6 :             opt->opt_type = PLPGSQL_RAISEOPTION_SCHEMA;
    3988             :         else
    3989           0 :             yyerror("unrecognized RAISE statement option");
    3990             : 
    3991         208 :         tok = yylex();
    3992         208 :         if (tok != '=' && tok != COLON_EQUALS)
    3993           0 :             yyerror("syntax error, expected \"=\"");
    3994             : 
    3995         208 :         opt->expr = read_sql_expression2(',', ';', ", or ;", &tok);
    3996             : 
    3997         208 :         result = lappend(result, opt);
    3998             : 
    3999         208 :         if (tok == ';')
    4000         140 :             break;
    4001             :     }
    4002             : 
    4003         280 :     return result;
    4004             : }
    4005             : 
    4006             : /*
    4007             :  * Check that the number of parameter placeholders in the message matches the
    4008             :  * number of parameters passed to it, if a message was given.
    4009             :  */
    4010             : static void
    4011        2878 : check_raise_parameters(PLpgSQL_stmt_raise *stmt)
    4012             : {
    4013             :     char       *cp;
    4014        2878 :     int         expected_nparams = 0;
    4015             : 
    4016        2878 :     if (stmt->message == NULL)
    4017         154 :         return;
    4018             : 
    4019       53632 :     for (cp = stmt->message; *cp; cp++)
    4020             :     {
    4021       50908 :         if (cp[0] == '%')
    4022             :         {
    4023             :             /* ignore literal % characters */
    4024        4840 :             if (cp[1] == '%')
    4025           4 :                 cp++;
    4026             :             else
    4027        4836 :                 expected_nparams++;
    4028             :         }
    4029             :     }
    4030             : 
    4031        2724 :     if (expected_nparams < list_length(stmt->params))
    4032           4 :         ereport(ERROR,
    4033             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    4034             :                 errmsg("too many parameters specified for RAISE")));
    4035        2720 :     if (expected_nparams > list_length(stmt->params))
    4036           4 :         ereport(ERROR,
    4037             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    4038             :                 errmsg("too few parameters specified for RAISE")));
    4039             : }
    4040             : 
    4041             : /*
    4042             :  * Fix up CASE statement
    4043             :  */
    4044             : static PLpgSQL_stmt *
    4045           4 : make_case(int location, PLpgSQL_expr *t_expr,
    4046             :           List *case_when_list, List *else_stmts)
    4047             : {
    4048             :     PLpgSQL_stmt_case   *new;
    4049             : 
    4050           4 :     new = palloc(sizeof(PLpgSQL_stmt_case));
    4051           4 :     new->cmd_type = PLPGSQL_STMT_CASE;
    4052           4 :     new->lineno = plpgsql_location_to_lineno(location);
    4053           4 :     new->stmtid = ++plpgsql_curr_compile->nstatements;
    4054           4 :     new->t_expr = t_expr;
    4055           4 :     new->t_varno = 0;
    4056           4 :     new->case_when_list = case_when_list;
    4057           4 :     new->have_else = (else_stmts != NIL);
    4058             :     /* Get rid of list-with-NULL hack */
    4059           4 :     if (list_length(else_stmts) == 1 && linitial(else_stmts) == NULL)
    4060           0 :         new->else_stmts = NIL;
    4061             :     else
    4062           4 :         new->else_stmts = else_stmts;
    4063             : 
    4064             :     /*
    4065             :      * When test expression is present, we create a var for it and then
    4066             :      * convert all the WHEN expressions to "VAR IN (original_expression)".
    4067             :      * This is a bit klugy, but okay since we haven't yet done more than
    4068             :      * read the expressions as text.  (Note that previous parsing won't
    4069             :      * have complained if the WHEN ... THEN expression contained multiple
    4070             :      * comma-separated values.)
    4071             :      */
    4072           4 :     if (t_expr)
    4073             :     {
    4074             :         char    varname[32];
    4075             :         PLpgSQL_var *t_var;
    4076             :         ListCell *l;
    4077             : 
    4078             :         /* use a name unlikely to collide with any user names */
    4079           2 :         snprintf(varname, sizeof(varname), "__Case__Variable_%d__",
    4080             :                  plpgsql_nDatums);
    4081             : 
    4082             :         /*
    4083             :          * We don't yet know the result datatype of t_expr.  Build the
    4084             :          * variable as if it were INT4; we'll fix this at runtime if needed.
    4085             :          */
    4086           2 :         t_var = (PLpgSQL_var *)
    4087           2 :             plpgsql_build_variable(varname, new->lineno,
    4088             :                                    plpgsql_build_datatype(INT4OID,
    4089             :                                                           -1,
    4090             :                                                           InvalidOid,
    4091             :                                                           NULL),
    4092             :                                    true);
    4093           2 :         new->t_varno = t_var->dno;
    4094             : 
    4095          12 :         foreach(l, case_when_list)
    4096             :         {
    4097          10 :             PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
    4098          10 :             PLpgSQL_expr *expr = cwt->expr;
    4099             :             StringInfoData  ds;
    4100             : 
    4101             :             /* copy expression query without SELECT keyword (expr->query + 7) */
    4102             :             Assert(strncmp(expr->query, "SELECT ", 7) == 0);
    4103             : 
    4104             :             /* And do the string hacking */
    4105          10 :             initStringInfo(&ds);
    4106             : 
    4107          10 :             appendStringInfo(&ds, "SELECT \"%s\" IN (%s)",
    4108          10 :                              varname, expr->query + 7);
    4109             : 
    4110          10 :             pfree(expr->query);
    4111          10 :             expr->query = pstrdup(ds.data);
    4112             :             /* Adjust expr's namespace to include the case variable */
    4113          10 :             expr->ns = plpgsql_ns_top();
    4114             : 
    4115          10 :             pfree(ds.data);
    4116             :         }
    4117             :     }
    4118             : 
    4119           4 :     return (PLpgSQL_stmt *) new;
    4120             : }

Generated by: LCOV version 1.13