From 718bcf8e347f4f0ca282b286c49996ae39a7937e Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <lic@highgo.com>
Date: Tue, 2 Dec 2025 09:32:58 +0800
Subject: [PATCH v6 02/13] cleanup: rename inner variables to avoid shadowing
 by outer locals

This commit fixes several cases where a variable declared in an inner
scope was shadowed by an existing local variable in the outer scope. The
changes rename the inner variables so each identifier is distinct within
its respective block.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Peter Smith <smithpb2250@gmail.com>
Discussion: https://postgr.es/m/CAEoWx2kQ2x5gMaj8tHLJ3=jfC+p5YXHkJyHrDTiQw2nn2FJTmQ@mail.gmail.com
---
 src/backend/access/brin/brin.c             |  8 ++--
 src/backend/access/gist/gistbuild.c        | 13 +++----
 src/backend/commands/extension.c           |  8 ++--
 src/backend/commands/schemacmds.c          |  6 +--
 src/backend/commands/statscmds.c           |  6 +--
 src/backend/commands/tablecmds.c           | 28 +++++++-------
 src/backend/commands/trigger.c             | 14 +++----
 src/backend/commands/wait.c                | 12 +++---
 src/backend/executor/nodeAgg.c             | 16 ++++----
 src/backend/executor/nodeValuesscan.c      |  6 +--
 src/backend/optimizer/plan/createplan.c    | 44 +++++++++++-----------
 src/backend/statistics/dependencies.c      | 26 ++++++-------
 src/backend/storage/buffer/bufmgr.c        |  6 +--
 src/backend/utils/adt/jsonpath_exec.c      | 30 +++++++--------
 src/backend/utils/adt/pg_upgrade_support.c |  4 +-
 src/backend/utils/adt/varlena.c            | 20 +++++-----
 src/backend/utils/mmgr/freepage.c          |  6 +--
 src/bin/pgbench/pgbench.c                  |  6 +--
 src/bin/psql/describe.c                    | 18 ++++-----
 src/bin/psql/prompt.c                      | 12 +++---
 src/fe_utils/print.c                       | 10 ++---
 src/interfaces/libpq/fe-connect.c          |  8 ++--
 22 files changed, 151 insertions(+), 156 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index 9cd563fd0c3..46627638176 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -696,15 +696,15 @@ bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
 		 */
 		if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
 		{
-			FmgrInfo   *tmp;
+			FmgrInfo   *tmpfi;
 
 			/* First time we see this attribute, so no key/null keys. */
 			Assert(nkeys[keyattno - 1] == 0);
 			Assert(nnullkeys[keyattno - 1] == 0);
 
-			tmp = index_getprocinfo(idxRel, keyattno,
-									BRIN_PROCNUM_CONSISTENT);
-			fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
+			tmpfi = index_getprocinfo(idxRel, keyattno,
+									  BRIN_PROCNUM_CONSISTENT);
+			fmgr_info_copy(&consistentFn[keyattno - 1], tmpfi,
 						   CurrentMemoryContext);
 		}
 
diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index 7f57c787f4c..4dba76be23d 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -1129,7 +1129,6 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		int			ndownlinks,
 					i;
 		Buffer		parentBuffer;
-		ListCell   *lc;
 
 		/* Parent may have changed since we memorized this path. */
 		parentBuffer =
@@ -1156,10 +1155,8 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		ndownlinks = list_length(splitinfo);
 		downlinks = palloc_array(IndexTuple, ndownlinks);
 		i = 0;
-		foreach(lc, splitinfo)
+		foreach_ptr(GISTPageSplitInfo, si, splitinfo)
 		{
-			GISTPageSplitInfo *splitinfo = lfirst(lc);
-
 			/*
 			 * Remember the parent of each new child page in our parent map.
 			 * This assumes that the downlinks fit on the parent page. If the
@@ -1169,7 +1166,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 */
 			if (level > 0)
 				gistMemorizeParent(buildstate,
-								   BufferGetBlockNumber(splitinfo->buf),
+								   BufferGetBlockNumber(si->buf),
 								   BufferGetBlockNumber(parentBuffer));
 
 			/*
@@ -1179,14 +1176,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 * harm).
 			 */
 			if (level > 1)
-				gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+				gistMemorizeAllDownlinks(buildstate, si->buf);
 
 			/*
 			 * Since there's no concurrent access, we can release the lower
 			 * level buffers immediately. This includes the original page.
 			 */
-			UnlockReleaseBuffer(splitinfo->buf);
-			downlinks[i++] = splitinfo->downlink;
+			UnlockReleaseBuffer(si->buf);
+			downlinks[i++] = si->downlink;
 		}
 
 		/* Insert them into parent. */
diff --git a/src/backend/commands/extension.c b/src/backend/commands/extension.c
index 963618a64c4..ae47fd5d480 100644
--- a/src/backend/commands/extension.c
+++ b/src/backend/commands/extension.c
@@ -1452,8 +1452,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 			Datum		old = t_sql;
 			char	   *reqextname = (char *) lfirst(lc);
 			Oid			reqschema = lfirst_oid(lc2);
-			char	   *schemaName = get_namespace_name(reqschema);
-			const char *qSchemaName = quote_identifier(schemaName);
+			char	   *reqSchemaName = get_namespace_name(reqschema);
+			const char *qReqSchemaName = quote_identifier(reqSchemaName);
 			char	   *repltoken;
 
 			repltoken = psprintf("@extschema:%s@", reqextname);
@@ -1461,8 +1461,8 @@ execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
 											C_COLLATION_OID,
 											t_sql,
 											CStringGetTextDatum(repltoken),
-											CStringGetTextDatum(qSchemaName));
-			if (t_sql != old && strpbrk(schemaName, quoting_relevant_chars))
+											CStringGetTextDatum(qReqSchemaName));
+			if (t_sql != old && strpbrk(reqSchemaName, quoting_relevant_chars))
 				ereport(ERROR,
 						(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
 						 errmsg("invalid character in extension \"%s\" schema: must not contain any of \"%s\"",
diff --git a/src/backend/commands/schemacmds.c b/src/backend/commands/schemacmds.c
index 4c51e920626..bcfd6562386 100644
--- a/src/backend/commands/schemacmds.c
+++ b/src/backend/commands/schemacmds.c
@@ -55,7 +55,6 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	const char *schemaName = stmt->schemaname;
 	Oid			namespaceId;
 	List	   *parsetree_list;
-	ListCell   *parsetree_item;
 	Oid			owner_uid;
 	Oid			saved_uid;
 	int			save_sec_context;
@@ -203,16 +202,15 @@ CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
 	 * them through parse_analyze_*() or the rewriter; we can just hand them
 	 * straight to ProcessUtility.
 	 */
-	foreach(parsetree_item, parsetree_list)
+	foreach_ptr(Node, substmt, parsetree_list)
 	{
-		Node	   *stmt = (Node *) lfirst(parsetree_item);
 		PlannedStmt *wrapper;
 
 		/* need to make a wrapper PlannedStmt */
 		wrapper = makeNode(PlannedStmt);
 		wrapper->commandType = CMD_UTILITY;
 		wrapper->canSetTag = false;
-		wrapper->utilityStmt = stmt;
+		wrapper->utilityStmt = substmt;
 		wrapper->stmt_location = stmt_location;
 		wrapper->stmt_len = stmt_len;
 		wrapper->planOrigin = PLAN_STMT_INTERNAL;
diff --git a/src/backend/commands/statscmds.c b/src/backend/commands/statscmds.c
index c1da79f36ba..2ea8370e69e 100644
--- a/src/backend/commands/statscmds.c
+++ b/src/backend/commands/statscmds.c
@@ -319,15 +319,15 @@ CreateStatistics(CreateStatsStmt *stmt, bool check_rights)
 			Node	   *expr = selem->expr;
 			Oid			atttype;
 			TypeCacheEntry *type;
-			Bitmapset  *attnums = NULL;
+			Bitmapset  *attnums_bms = NULL;
 			int			k;
 
 			Assert(expr != NULL);
 
-			pull_varattnos(expr, 1, &attnums);
+			pull_varattnos(expr, 1, &attnums_bms);
 
 			k = -1;
-			while ((k = bms_next_member(attnums, k)) >= 0)
+			while ((k = bms_next_member(attnums_bms, k)) >= 0)
 			{
 				AttrNumber	attnum = k + FirstLowInvalidHeapAttributeNumber;
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index b04b0dbd2a0..d2fb3d1a23b 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -15743,14 +15743,14 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 
 			foreach(lcmd, stmt->cmds)
 			{
-				AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
+				AlterTableCmd *subcmd = lfirst_node(AlterTableCmd, lcmd);
 
-				if (cmd->subtype == AT_AddIndex)
+				if (subcmd->subtype == AT_AddIndex)
 				{
 					IndexStmt  *indstmt;
 					Oid			indoid;
 
-					indstmt = castNode(IndexStmt, cmd->def);
+					indstmt = castNode(IndexStmt, subcmd->def);
 					indoid = get_constraint_index(oldId);
 
 					if (!rewrite)
@@ -15760,9 +15760,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 													 RelationRelationId, 0);
 					indstmt->reset_default_tblspc = true;
 
-					cmd->subtype = AT_ReAddIndex;
+					subcmd->subtype = AT_ReAddIndex;
 					tab->subcmds[AT_PASS_OLD_INDEX] =
-						lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_INDEX], subcmd);
 
 					/* recreate any comment on the constraint */
 					RebuildConstraintComment(tab,
@@ -15772,9 +15772,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 											 NIL,
 											 indstmt->idxname);
 				}
-				else if (cmd->subtype == AT_AddConstraint)
+				else if (subcmd->subtype == AT_AddConstraint)
 				{
-					Constraint *con = castNode(Constraint, cmd->def);
+					Constraint *con = castNode(Constraint, subcmd->def);
 
 					con->old_pktable_oid = refRelId;
 					/* rewriting neither side of a FK */
@@ -15782,9 +15782,9 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 						!rewrite && tab->rewrite == 0)
 						TryReuseForeignKey(oldId, con);
 					con->reset_default_tblspc = true;
-					cmd->subtype = AT_ReAddConstraint;
+					subcmd->subtype = AT_ReAddConstraint;
 					tab->subcmds[AT_PASS_OLD_CONSTR] =
-						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+						lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 					/*
 					 * Recreate any comment on the constraint.  If we have
@@ -15804,7 +15804,7 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 				}
 				else
 					elog(ERROR, "unexpected statement subtype: %d",
-						 (int) cmd->subtype);
+						 (int) subcmd->subtype);
 			}
 		}
 		else if (IsA(stm, AlterDomainStmt))
@@ -15814,12 +15814,12 @@ ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
 			if (stmt->subtype == AD_AddConstraint)
 			{
 				Constraint *con = castNode(Constraint, stmt->def);
-				AlterTableCmd *cmd = makeNode(AlterTableCmd);
+				AlterTableCmd *subcmd = makeNode(AlterTableCmd);
 
-				cmd->subtype = AT_ReAddDomainConstraint;
-				cmd->def = (Node *) stmt;
+				subcmd->subtype = AT_ReAddDomainConstraint;
+				subcmd->def = (Node *) stmt;
 				tab->subcmds[AT_PASS_OLD_CONSTR] =
-					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+					lappend(tab->subcmds[AT_PASS_OLD_CONSTR], subcmd);
 
 				/* recreate any comment on the constraint */
 				RebuildConstraintComment(tab,
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 98d402c0a3b..a51e3ccb331 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -1165,7 +1165,7 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 		{
 			CreateTrigStmt *childStmt;
 			Relation	childTbl;
-			Node	   *qual;
+			Node	   *partqual;
 
 			childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
 
@@ -1178,18 +1178,18 @@ CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
 			childStmt->whenClause = NULL;
 
 			/* If there is a WHEN clause, create a modified copy of it */
-			qual = copyObject(whenClause);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
+			partqual = copyObject(whenClause);
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_OLD_VARNO,
 										childTbl, rel);
-			qual = (Node *)
-				map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
+			partqual = (Node *)
+				map_partition_varattnos((List *) partqual, PRS2_NEW_VARNO,
 										childTbl, rel);
 
 			CreateTriggerFiringOn(childStmt, queryString,
 								  partdesc->oids[i], refRelOid,
 								  InvalidOid, InvalidOid,
-								  funcoid, trigoid, qual,
+								  funcoid, trigoid, partqual,
 								  isInternal, true, trigger_fires_when);
 
 			table_close(childTbl, NoLock);
diff --git a/src/backend/commands/wait.c b/src/backend/commands/wait.c
index 1290df10c6f..c2a0dac4899 100644
--- a/src/backend/commands/wait.c
+++ b/src/backend/commands/wait.c
@@ -79,7 +79,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 		{
 			char	   *timeout_str;
 			const char *hintmsg;
-			double		result;
+			double		timeout_val;
 
 			if (timeout_specified)
 				errorConflictingDefElem(defel, pstate);
@@ -87,7 +87,7 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 
 			timeout_str = defGetString(defel);
 
-			if (!parse_real(timeout_str, &result, GUC_UNIT_MS, &hintmsg))
+			if (!parse_real(timeout_str, &timeout_val, GUC_UNIT_MS, &hintmsg))
 			{
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
@@ -100,20 +100,20 @@ ExecWaitStmt(ParseState *pstate, WaitStmt *stmt, DestReceiver *dest)
 			 * don't fail on just-out-of-range values that would round into
 			 * range.
 			 */
-			result = rint(result);
+			timeout_val = rint(timeout_val);
 
 			/* Range check */
-			if (unlikely(isnan(result) || !FLOAT8_FITS_IN_INT64(result)))
+			if (unlikely(isnan(timeout_val) || !FLOAT8_FITS_IN_INT64(timeout_val)))
 				ereport(ERROR,
 						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 						errmsg("timeout value is out of range"));
 
-			if (result < 0)
+			if (timeout_val < 0)
 				ereport(ERROR,
 						errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 						errmsg("timeout cannot be negative"));
 
-			timeout = (int64) result;
+			timeout = (int64) timeout_val;
 		}
 		else if (strcmp(defel->defname, "no_throw") == 0)
 		{
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 7d487a165fa..a4f6765142a 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -4065,12 +4065,12 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 	 */
 	for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
 	{
-		AggStatePerPhase phase = &aggstate->phases[phaseidx];
+		AggStatePerPhase curphase = &aggstate->phases[phaseidx];
 		bool		dohash = false;
 		bool		dosort = false;
 
 		/* phase 0 doesn't necessarily exist */
-		if (!phase->aggnode)
+		if (!curphase->aggnode)
 			continue;
 
 		if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
@@ -4091,13 +4091,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 			 */
 			continue;
 		}
-		else if (phase->aggstrategy == AGG_PLAIN ||
-				 phase->aggstrategy == AGG_SORTED)
+		else if (curphase->aggstrategy == AGG_PLAIN ||
+				 curphase->aggstrategy == AGG_SORTED)
 		{
 			dohash = false;
 			dosort = true;
 		}
-		else if (phase->aggstrategy == AGG_HASHED)
+		else if (curphase->aggstrategy == AGG_HASHED)
 		{
 			dohash = true;
 			dosort = false;
@@ -4105,11 +4105,11 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
 		else
 			Assert(false);
 
-		phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
-											 false);
+		curphase->evaltrans = ExecBuildAggTrans(aggstate, curphase, dosort, dohash,
+												false);
 
 		/* cache compiled expression for outer slot without NULL check */
-		phase->evaltrans_cache[0][0] = phase->evaltrans;
+		curphase->evaltrans_cache[0][0] = curphase->evaltrans;
 	}
 
 	return aggstate;
diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c
index e663fb68cfc..8347cae5a6e 100644
--- a/src/backend/executor/nodeValuesscan.c
+++ b/src/backend/executor/nodeValuesscan.c
@@ -90,7 +90,6 @@ ValuesNext(ValuesScanState *node)
 		MemoryContext oldContext;
 		Datum	   *values;
 		bool	   *isnull;
-		ListCell   *lc;
 		int			resind;
 
 		/*
@@ -139,13 +138,12 @@ ValuesNext(ValuesScanState *node)
 		isnull = slot->tts_isnull;
 
 		resind = 0;
-		foreach(lc, exprstatelist)
+		foreach_ptr(ExprState, exprstate, exprstatelist)
 		{
-			ExprState  *estate = (ExprState *) lfirst(lc);
 			CompactAttribute *attr = TupleDescCompactAttr(slot->tts_tupleDescriptor,
 														  resind);
 
-			values[resind] = ExecEvalExpr(estate,
+			values[resind] = ExecEvalExpr(exprstate,
 										  econtext,
 										  &isnull[resind]);
 
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 50b0e10308b..4a567d333b9 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1235,16 +1235,16 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
 	if (best_path->subpaths == NIL)
 	{
 		/* Generate a Result plan with constant-FALSE gating qual */
-		Plan	   *plan;
+		Plan	   *resplan;
 
-		plan = (Plan *) make_one_row_result(tlist,
-											(Node *) list_make1(makeBoolConst(false,
-																			  false)),
-											best_path->path.parent);
+		resplan = (Plan *) make_one_row_result(tlist,
+											   (Node *) list_make1(makeBoolConst(false,
+																				 false)),
+											   best_path->path.parent);
 
-		copy_generic_path_info(plan, (Path *) best_path);
+		copy_generic_path_info(resplan, (Path *) best_path);
 
-		return plan;
+		return resplan;
 	}
 
 	/*
@@ -2407,7 +2407,7 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
 		PlannerInfo *subroot = mminfo->subroot;
 		Query	   *subparse = subroot->parse;
-		Plan	   *plan;
+		Plan	   *initplan;
 
 		/*
 		 * Generate the plan for the subquery. We already have a Path, but we
@@ -2415,25 +2415,25 @@ create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
 		 * Since we are entering a different planner context (subroot),
 		 * recurse to create_plan not create_plan_recurse.
 		 */
-		plan = create_plan(subroot, mminfo->path);
+		initplan = create_plan(subroot, mminfo->path);
 
-		plan = (Plan *) make_limit(plan,
-								   subparse->limitOffset,
-								   subparse->limitCount,
-								   subparse->limitOption,
-								   0, NULL, NULL, NULL);
+		initplan = (Plan *) make_limit(initplan,
+									   subparse->limitOffset,
+									   subparse->limitCount,
+									   subparse->limitOption,
+									   0, NULL, NULL, NULL);
 
 		/* Must apply correct cost/width data to Limit node */
-		plan->disabled_nodes = mminfo->path->disabled_nodes;
-		plan->startup_cost = mminfo->path->startup_cost;
-		plan->total_cost = mminfo->pathcost;
-		plan->plan_rows = 1;
-		plan->plan_width = mminfo->path->pathtarget->width;
-		plan->parallel_aware = false;
-		plan->parallel_safe = mminfo->path->parallel_safe;
+		initplan->disabled_nodes = mminfo->path->disabled_nodes;
+		initplan->startup_cost = mminfo->path->startup_cost;
+		initplan->total_cost = mminfo->pathcost;
+		initplan->plan_rows = 1;
+		initplan->plan_width = mminfo->path->pathtarget->width;
+		initplan->parallel_aware = false;
+		initplan->parallel_safe = mminfo->path->parallel_safe;
 
 		/* Convert the plan into an InitPlan in the outer query. */
-		SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
+		SS_make_initplan_from_plan(root, subroot, initplan, mminfo->param);
 	}
 
 	/* Generate the output plan --- basically just a Result */
diff --git a/src/backend/statistics/dependencies.c b/src/backend/statistics/dependencies.c
index e3a2f5817e0..62e2ea122e9 100644
--- a/src/backend/statistics/dependencies.c
+++ b/src/backend/statistics/dependencies.c
@@ -1173,17 +1173,17 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	if (is_opclause(clause))
 	{
 		/* If it's an opclause, check for Var = Const or Const = Var. */
-		OpExpr	   *expr = (OpExpr *) clause;
+		OpExpr	   *op_expr = (OpExpr *) clause;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(op_expr->args) != 2)
 			return false;
 
 		/* Make sure non-selected argument is a pseudoconstant. */
-		if (is_pseudo_constant_clause(lsecond(expr->args)))
-			clause_expr = linitial(expr->args);
-		else if (is_pseudo_constant_clause(linitial(expr->args)))
-			clause_expr = lsecond(expr->args);
+		if (is_pseudo_constant_clause(lsecond(op_expr->args)))
+			clause_expr = linitial(op_expr->args);
+		else if (is_pseudo_constant_clause(linitial(op_expr->args)))
+			clause_expr = lsecond(op_expr->args);
 		else
 			return false;
 
@@ -1199,7 +1199,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity functions, and to be more consistent with decisions
 		 * elsewhere in the planner.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(op_expr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
@@ -1207,7 +1207,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 	else if (IsA(clause, ScalarArrayOpExpr))
 	{
 		/* If it's a scalar array operator, check for Var IN Const. */
-		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
+		ScalarArrayOpExpr *op_expr = (ScalarArrayOpExpr *) clause;
 
 		/*
 		 * Reject ALL() variant, we only care about ANY/IN.
@@ -1215,21 +1215,21 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * FIXME Maybe we should check if all the values are the same, and
 		 * allow ALL in that case? Doesn't seem very practical, though.
 		 */
-		if (!expr->useOr)
+		if (!op_expr->useOr)
 			return false;
 
 		/* Only expressions with two arguments are candidates. */
-		if (list_length(expr->args) != 2)
+		if (list_length(op_expr->args) != 2)
 			return false;
 
 		/*
 		 * We know it's always (Var IN Const), so we assume the var is the
 		 * first argument, and pseudoconstant is the second one.
 		 */
-		if (!is_pseudo_constant_clause(lsecond(expr->args)))
+		if (!is_pseudo_constant_clause(lsecond(op_expr->args)))
 			return false;
 
-		clause_expr = linitial(expr->args);
+		clause_expr = linitial(op_expr->args);
 
 		/*
 		 * If it's not an "=" operator, just ignore the clause, as it's not
@@ -1238,7 +1238,7 @@ dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, N
 		 * selectivity. That's a bit strange, but it's what other similar
 		 * places do.
 		 */
-		if (get_oprrest(expr->opno) != F_EQSEL)
+		if (get_oprrest(op_expr->opno) != F_EQSEL)
 			return false;
 
 		/* OK to proceed with checking "var" */
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index d1babaff023..1434c7ee2ef 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -1308,7 +1308,7 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 	 */
 	if (unlikely(blockNum == P_NEW))
 	{
-		uint32		flags = EB_SKIP_EXTENSION_LOCK;
+		uint32		uflags = EB_SKIP_EXTENSION_LOCK;
 
 		/*
 		 * Since no-one else can be looking at the page contents yet, there is
@@ -1316,9 +1316,9 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 		 * lock.
 		 */
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-			flags |= EB_LOCK_FIRST;
+			uflags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
+		return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, uflags);
 	}
 
 	if (rel)
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 52ae0ba4cf7..32a635c3bda 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -536,7 +536,7 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 		MemoryContext oldcontext;
 		Jsonb	   *vars;
 		bool		silent;
-		JsonValueList found = {0};
+		JsonValueList vals = {0};
 
 		funcctx = SRF_FIRSTCALL_INIT();
 		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
@@ -548,9 +548,9 @@ jsonb_path_query_internal(FunctionCallInfo fcinfo, bool tz)
 
 		(void) executeJsonPath(jp, vars, getJsonPathVariableFromJsonb,
 							   countVariablesFromJsonb,
-							   jb, !silent, &found, tz);
+							   jb, !silent, &vals, tz);
 
-		funcctx->user_fctx = JsonValueListGetList(&found);
+		funcctx->user_fctx = JsonValueListGetList(&vals);
 
 		MemoryContextSwitchTo(oldcontext);
 	}
@@ -1879,25 +1879,25 @@ executeBoolItem(JsonPathExecContext *cxt, JsonPathItem *jsp,
 				 * check that there are no errors at all.
 				 */
 				JsonValueList vals = {0};
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, &vals);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
 				return JsonValueListIsEmpty(&vals) ? jpbFalse : jpbTrue;
 			}
 			else
 			{
-				JsonPathExecResult res =
+				JsonPathExecResult execres =
 					executeItemOptUnwrapResultNoThrow(cxt, &larg, jb,
 													  false, NULL);
 
-				if (jperIsError(res))
+				if (jperIsError(execres))
 					return jpbUnknown;
 
-				return res == jperOk ? jpbTrue : jpbFalse;
+				return execres == jperOk ? jpbTrue : jpbFalse;
 			}
 
 		default:
@@ -2066,16 +2066,16 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 		/* Loop over right arg sequence or do single pass otherwise */
 		while (rarg ? (rval != NULL) : first)
 		{
-			JsonPathBool res = exec(pred, lval, rval, param);
+			JsonPathBool boolres = exec(pred, lval, rval, param);
 
-			if (res == jpbUnknown)
+			if (boolres == jpbUnknown)
 			{
 				if (jspStrictAbsenceOfErrors(cxt))
 					return jpbUnknown;
 
 				error = true;
 			}
-			else if (res == jpbTrue)
+			else if (boolres == jpbTrue)
 			{
 				if (!jspStrictAbsenceOfErrors(cxt))
 					return jpbTrue;
@@ -4138,20 +4138,20 @@ JsonTableInitOpaque(TableFuncScanState *state, int natts)
 		forboth(exprlc, state->passingvalexprs,
 				namelc, je->passing_names)
 		{
-			ExprState  *state = lfirst_node(ExprState, exprlc);
+			ExprState  *exprstate = lfirst_node(ExprState, exprlc);
 			String	   *name = lfirst_node(String, namelc);
 			JsonPathVariable *var = palloc_object(JsonPathVariable);
 
 			var->name = pstrdup(name->sval);
 			var->namelen = strlen(var->name);
-			var->typid = exprType((Node *) state->expr);
-			var->typmod = exprTypmod((Node *) state->expr);
+			var->typid = exprType((Node *) exprstate->expr);
+			var->typmod = exprTypmod((Node *) exprstate->expr);
 
 			/*
 			 * Evaluate the expression and save the value to be returned by
 			 * GetJsonPathVar().
 			 */
-			var->value = ExecEvalExpr(state, ps->ps_ExprContext,
+			var->value = ExecEvalExpr(exprstate, ps->ps_ExprContext,
 									  &var->isnull);
 
 			args = lappend(args, var);
diff --git a/src/backend/utils/adt/pg_upgrade_support.c b/src/backend/utils/adt/pg_upgrade_support.c
index b505a6b4fee..b813e65746a 100644
--- a/src/backend/utils/adt/pg_upgrade_support.c
+++ b/src/backend/utils/adt/pg_upgrade_support.c
@@ -227,8 +227,8 @@ binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS)
 		deconstruct_array_builtin(textArray, TEXTOID, &textDatums, NULL, &ndatums);
 		for (i = 0; i < ndatums; i++)
 		{
-			char	   *extName = TextDatumGetCString(textDatums[i]);
-			Oid			extOid = get_extension_oid(extName, false);
+			char	   *extNameStr = TextDatumGetCString(textDatums[i]);
+			Oid			extOid = get_extension_oid(extNameStr, false);
 
 			requiredExtensions = lappend_oid(requiredExtensions, extOid);
 		}
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index 7caf700fd61..a3e02ea2d95 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -3304,14 +3304,14 @@ appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
 			 * Copy the text that is back reference of regexp.  Note so and eo
 			 * are counted in characters not bytes.
 			 */
-			char	   *chunk_start;
-			int			chunk_len;
+			char	   *start;
+			int			len;
 
 			Assert(so >= data_pos);
-			chunk_start = start_ptr;
-			chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
-			chunk_len = charlen_to_bytelen(chunk_start, eo - so);
-			appendBinaryStringInfo(str, chunk_start, chunk_len);
+			start = start_ptr;
+			start += charlen_to_bytelen(start, so - data_pos);
+			len = charlen_to_bytelen(start, eo - so);
+			appendBinaryStringInfo(str, start, len);
 		}
 	}
 }
@@ -4935,7 +4935,7 @@ text_format(PG_FUNCTION_ARGS)
 			else
 			{
 				/* For less-usual datatypes, convert to text then to int */
-				char	   *str;
+				char	   *s;
 
 				if (typid != prev_width_type)
 				{
@@ -4947,12 +4947,12 @@ text_format(PG_FUNCTION_ARGS)
 					prev_width_type = typid;
 				}
 
-				str = OutputFunctionCall(&typoutputinfo_width, value);
+				s = OutputFunctionCall(&typoutputinfo_width, value);
 
 				/* pg_strtoint32 will complain about bad data or overflow */
-				width = pg_strtoint32(str);
+				width = pg_strtoint32(s);
 
-				pfree(str);
+				pfree(s);
 			}
 		}
 
diff --git a/src/backend/utils/mmgr/freepage.c b/src/backend/utils/mmgr/freepage.c
index d7195685f69..7488a3d547a 100644
--- a/src/backend/utils/mmgr/freepage.c
+++ b/src/backend/utils/mmgr/freepage.c
@@ -1586,7 +1586,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 	if (prevkey != NULL && prevkey->first_page + prevkey->npages >= first_page)
 	{
 		bool		remove_next = false;
-		Size		result;
+		Size		nprevpages;
 
 		Assert(prevkey->first_page + prevkey->npages == first_page);
 		prevkey->npages = (first_page - prevkey->first_page) + npages;
@@ -1606,7 +1606,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		/* Put the span on the correct freelist and save size. */
 		FreePagePopSpanLeader(fpm, prevkey->first_page);
 		FreePagePushSpanLeader(fpm, prevkey->first_page, prevkey->npages);
-		result = prevkey->npages;
+		nprevpages = prevkey->npages;
 
 		/*
 		 * If we consolidated with both the preceding and following entries,
@@ -1621,7 +1621,7 @@ FreePageManagerPutInternal(FreePageManager *fpm, Size first_page, Size npages,
 		if (remove_next)
 			FreePageBtreeRemove(fpm, np, nindex);
 
-		return result;
+		return nprevpages;
 	}
 
 	/* Consolidate with the next entry if possible. */
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 1dae918cc09..43a9627fad4 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -4661,7 +4661,7 @@ doLog(TState *thread, CState *st,
 			double		lag_sum2 = 0.0;
 			double		lag_min = 0.0;
 			double		lag_max = 0.0;
-			int64		skipped = 0;
+			int64		skips = 0;
 			int64		serialization_failures = 0;
 			int64		deadlock_failures = 0;
 			int64		other_sql_failures = 0;
@@ -4691,8 +4691,8 @@ doLog(TState *thread, CState *st,
 					lag_max);
 
 			if (latency_limit)
-				skipped = agg->skipped;
-			fprintf(logfile, " " INT64_FORMAT, skipped);
+				skips = agg->skipped;
+			fprintf(logfile, " " INT64_FORMAT, skips);
 
 			if (max_tries != 1)
 			{
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index ab13c90ed33..0e408026183 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1758,7 +1758,7 @@ describeOneTableDetails(const char *schemaname,
 	if (tableinfo.relkind == RELKIND_SEQUENCE)
 	{
 		PGresult   *result = NULL;
-		printQueryOpt myopt = pset.popt;
+		printQueryOpt popt = pset.popt;
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		if (pset.sversion >= 100000)
@@ -1895,12 +1895,12 @@ describeOneTableDetails(const char *schemaname,
 			printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
 							  schemaname, relationname);
 
-		myopt.footers = footers;
-		myopt.topt.default_footer = false;
-		myopt.title = title.data;
-		myopt.translate_header = true;
+		popt.footers = footers;
+		popt.topt.default_footer = false;
+		popt.title = title.data;
+		popt.translate_header = true;
 
-		printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
+		printQuery(res, &popt, pset.queryFout, false, pset.logfile);
 
 		free(footers[0]);
 		free(footers[1]);
@@ -2318,11 +2318,11 @@ describeOneTableDetails(const char *schemaname,
 
 		if (PQntuples(result) == 1)
 		{
-			char	   *schemaname = PQgetvalue(result, 0, 0);
-			char	   *relname = PQgetvalue(result, 0, 1);
+			const char *schema = PQgetvalue(result, 0, 0);
+			const char *relname = PQgetvalue(result, 0, 1);
 
 			printfPQExpBuffer(&tmpbuf, _("Owning table: \"%s.%s\""),
-							  schemaname, relname);
+							  schema, relname);
 			printTableAddFooter(&cont, tmpbuf.data);
 		}
 		PQclear(result);
diff --git a/src/bin/psql/prompt.c b/src/bin/psql/prompt.c
index 9725d53dfe7..151b9bc1e56 100644
--- a/src/bin/psql/prompt.c
+++ b/src/bin/psql/prompt.c
@@ -203,11 +203,11 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 				case 'P':
 					if (pset.db)
 					{
-						PGpipelineStatus status = PQpipelineStatus(pset.db);
+						PGpipelineStatus pipelinestatus = PQpipelineStatus(pset.db);
 
-						if (status == PQ_PIPELINE_ON)
+						if (pipelinestatus == PQ_PIPELINE_ON)
 							strlcpy(buf, "on", sizeof(buf));
-						else if (status == PQ_PIPELINE_ABORTED)
+						else if (pipelinestatus == PQ_PIPELINE_ABORTED)
 							strlcpy(buf, "abort", sizeof(buf));
 						else
 							strlcpy(buf, "off", sizeof(buf));
@@ -390,10 +390,12 @@ get_prompt(promptStatus_t status, ConditionalStack cstack)
 	/* Compute the visible width of PROMPT1, for PROMPT2's %w */
 	if (prompt_string == pset.prompt1)
 	{
-		char	   *p = destination;
-		char	   *end = p + strlen(p);
+		const char *end;
 		bool		visible = true;
 
+		p = (const char *) destination;
+		end = p + strlen(p);
+
 		last_prompt1_width = 0;
 		while (*p)
 		{
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 12d969e8666..ebb3d62f187 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -933,7 +933,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 		if (!opt_tuples_only)
 		{
 			int			more_col_wrapping;
-			int			curr_nl_line;
+			int			curr_line;
 
 			if (opt_border == 2)
 				_print_horizontal_line(col_count, width_wrap, opt_border,
@@ -945,7 +945,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 							 col_lineptrs[i], max_nl_lines[i]);
 
 			more_col_wrapping = col_count;
-			curr_nl_line = 0;
+			curr_line = 0;
 			if (col_count > 0)
 				memset(header_done, false, col_count * sizeof(bool));
 			while (more_col_wrapping)
@@ -955,12 +955,12 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 
 				for (i = 0; i < cont->ncolumns; i++)
 				{
-					struct lineptr *this_line = col_lineptrs[i] + curr_nl_line;
+					struct lineptr *this_line = col_lineptrs[i] + curr_line;
 					unsigned int nbspace;
 
 					if (opt_border != 0 ||
 						(!format->wrap_right_border && i > 0))
-						fputs(curr_nl_line ? format->header_nl_left : " ",
+						fputs(curr_line ? format->header_nl_left : " ",
 							  fout);
 
 					if (!header_done[i])
@@ -987,7 +987,7 @@ print_aligned_text(const printTableContent *cont, FILE *fout, bool is_pager)
 					if (opt_border != 0 && col_count > 0 && i < col_count - 1)
 						fputs(dformat->midvrule, fout);
 				}
-				curr_nl_line++;
+				curr_line++;
 
 				if (opt_border == 2)
 					fputs(dformat->rightvrule, fout);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index b42a0cb4c78..514049a56a1 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -3998,7 +3998,7 @@ keep_going:						/* We will come back to here until there is
 				int			msgLength;
 				int			avail;
 				AuthRequest areq;
-				int			res;
+				int			status;
 				bool		async;
 
 				/*
@@ -4223,9 +4223,9 @@ keep_going:						/* We will come back to here until there is
 				 * Note that conn->pghost must be non-NULL if we are going to
 				 * avoid the Kerberos code doing a hostname look-up.
 				 */
-				res = pg_fe_sendauth(areq, msgLength, conn, &async);
+				status = pg_fe_sendauth(areq, msgLength, conn, &async);
 
-				if (async && (res == STATUS_OK))
+				if (async && (status == STATUS_OK))
 				{
 					/*
 					 * We'll come back later once we're ready to respond.
@@ -4242,7 +4242,7 @@ keep_going:						/* We will come back to here until there is
 				 */
 				conn->inStart = conn->inCursor;
 
-				if (res != STATUS_OK)
+				if (status != STATUS_OK)
 				{
 					/*
 					 * OAuth connections may perform two-step discovery, where
-- 
2.50.1 (Apple Git-155)

