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

Generated by: LCOV version 1.13