[Proposal] Level4 Warnings show many shadow vars

Started by Ranier Vilelaabout 6 years ago57 messages
#1Ranier Vilela
ranier_gyn@hotmail.com

Hi,
I believe PostgreSQL can benefit from changing the alert level of compilation warnings.
The current Level3 level for windows does not show any alerts, but that does not mean that there are no problems.
Changing the level to Level4 and its equivalent for GCC in Unix environments will show many warnings for shadow variables, including global variables.
True, there will also be many silly alerts that can be safely disabled.
Shadow variables, although they may not currently represent bugs, may be hiding errors, or at the very least, it is a waste of variable declaration.
With the current Level3 level, development is no longer checking and correcting shadow variables.

Any comments?

Best regards,
Ranier Vilela

#2Robert Haas
robertmhaas@gmail.com
In reply to: Ranier Vilela (#1)
Re: [Proposal] Level4 Warnings show many shadow vars

On Tue, Dec 3, 2019 at 8:24 PM Ranier Vilela <ranier_gyn@hotmail.com> wrote:

I believe PostgreSQL can benefit from changing the alert level of compilation warnings.
The current Level3 level for windows does not show any alerts, but that does not mean that there are no problems.
Changing the level to Level4 and its equivalent for GCC in Unix environments will show many warnings for shadow variables, including global variables.
True, there will also be many silly alerts that can be safely disabled.
Shadow variables, although they may not currently represent bugs, may be hiding errors, or at the very least, it is a waste of variable declaration.
With the current Level3 level, development is no longer checking and correcting shadow variables.

Any comments?

Most of us don't develop on Windows, so changing warning levels on
Windows won't really affect what developers see on their own machines,
and thus probably doesn't have much value. It might be a good idea to
try to clean up some/many cases of shadowed variables, though.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

#3Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Robert Haas (#2)
RE: [Proposal] Level4 Warnings show many shadow vars

Robert wrote:

Most of us don't develop on Windows, so changing warning levels on
Windows won't really affect what developers see on their own machines,
and thus probably doesn't have much value.

Yes the report is from msvc 2017.
Even so, there is some failure to review or compile in Unix environment, because there are so many cases.
-Wshadow with GCC can show the alerts.

It might be a good idea to>try to clean up some/many cases of shadowed >variables, though.

Interested in submitting the msvc 2017 report?

Ranier Vilela

#4Robert Haas
robertmhaas@gmail.com
In reply to: Ranier Vilela (#3)
Re: [Proposal] Level4 Warnings show many shadow vars

On Thu, Dec 5, 2019 at 11:26 AM Ranier Vilela <ranier_gyn@hotmail.com> wrote:

Even so, there is some failure to review or compile in Unix environment, because there are so many cases.
-Wshadow with GCC can show the alerts.

I mean, compiler warnings are not errors, and there's no requirement
that we fix every warning. I compile with -Wall -Werror regularly and
that works fine. I don't necessarily feel like I have to turn on more
warnings that aren't shown by default on the platforms I use. One way
of looking at it: if a warning isn't enabled by -Wall, it's probably
something that either isn't that important or would generate too many
false positives.

Interested in submitting the msvc 2017 report?

I think if this is an issue you care about, it's up to you to think of
doing something about it, like going through the report and submitting
patches for whichever cases you think need to be addressed. Cleaning
up stuff like this is potentially a lot of work, and I struggle to
keep up with all the work I've already got.

If you do decide to work on this, I recommend against preparing a
single giant patch that changes every single one blindly. Try to think
about which cases are the most egregious/dangerous and propose patches
for those first. If those are accepted then you can move on to other
cases.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

#5Mark Dilger
hornschnorter@gmail.com
In reply to: Ranier Vilela (#1)
Re: [Proposal] Level4 Warnings show many shadow vars

On 12/3/19 5:24 PM, Ranier Vilela wrote:

Hi,
I believe PostgreSQL can benefit from changing the alert level of compilation warnings.
The current Level3 level for windows does not show any alerts, but that does not mean that there are no problems.
Changing the level to Level4 and its equivalent for GCC in Unix environments will show many warnings for shadow variables, including global variables.
True, there will also be many silly alerts that can be safely disabled.
Shadow variables, although they may not currently represent bugs, may be hiding errors, or at the very least, it is a waste of variable declaration.
With the current Level3 level, development is no longer checking and correcting shadow variables.

Any comments?

I suggested increasing the default warnings in an email some time ago,
to which Tom made reasonable objections. You might want to take a
look at his comments, and consider if you can overcome the concerns
he had:

/messages/by-id/25938.1487367117@sss.pgh.pa.us

and

/messages/by-id/30007.1487374499@sss.pgh.pa.us

--
Mark Dilger

#6Tom Lane
tgl@sss.pgh.pa.us
In reply to: Mark Dilger (#5)
Re: [Proposal] Level4 Warnings show many shadow vars

Mark Dilger <hornschnorter@gmail.com> writes:

On 12/3/19 5:24 PM, Ranier Vilela wrote:

Any comments?

I suggested increasing the default warnings in an email some time ago,
to which Tom made reasonable objections.

Yes, that whole thread is worth a read in this context:

/messages/by-id/CAEepm=15e9L695yVCO-_OkBVbsPupyXqzYWzzDmj-bdJ6o2+Pw@mail.gmail.com

The original concern about --disable-integer-datetimes is history
now, but I think the variability of error reports between compilers
is still instructive and relevant.

regards, tom lane

#7Michael Paquier
michael@paquier.xyz
In reply to: Robert Haas (#4)
Re: [Proposal] Level4 Warnings show many shadow vars

On Thu, Dec 05, 2019 at 01:41:20PM -0500, Robert Haas wrote:

If you do decide to work on this, I recommend against preparing a
single giant patch that changes every single one blindly. Try to think
about which cases are the most egregious/dangerous and propose patches
for those first. If those are accepted then you can move on to other
cases.

+1.  An case-by-case analysis is key here because it depends on the
context of the code.  I am ready to bet that we don't care about most
of them, still that there are cases which actually matter a lot.
--
Michael
#8Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Mark Dilger (#5)
RE: [Proposal] Level4 Warnings show many shadow vars

De: Mark Dilger <hornschnorter@gmail.com>
Enviado: quinta-feira, 5 de dezembro de 2019 21:06

I suggested increasing the default warnings in an email some time ago,
to which Tom made reasonable objections. You might want to take a
look at his comments, and consider if you can overcome the concerns
he had:

I understand Tom's considerations.
What I mean is, everyone already knows, it's easier and safer to fix this kind of mistake early.
I'll do as Robert asked, but as with global variables, it's hard to fix.
What did the original author want, use the global variable or not use it by overriding the name.
If it was to use the global variable, it will affect the behavior of the function, I believe.

regards,
Ranier Vilela

#9Robert Haas
robertmhaas@gmail.com
In reply to: Ranier Vilela (#8)
Re: [Proposal] Level4 Warnings show many shadow vars

On Fri, Dec 6, 2019 at 7:59 AM Ranier Vilela <ranier_gyn@hotmail.com> wrote:

What did the original author want, use the global variable or not use it by overriding the name.
If it was to use the global variable, it will affect the behavior of the function, I believe.

Well, you haven't provided any examples, so it's hard to be sure, but
I suspect that the vast majority of these are not actually bugs, but
just name collisions that don't really matter. Some of them could even
be Windows-specific things. For example, if Windows - or any other
platform - happened to have a variable declared in a library header
file someplace that is relatively commonly used within PostgreSQL as a
local variable name (e.g. "lc"), it would produce tons of name
collisions, none of which would be bugs.

The thing is, it's well-known that this is not good programming
practice, and I doubt that any committer would intentionally commit
code that used the same variable name for a file-level global and a
local variable in that same file. Perhaps a few such cases have crept
in by accident, but I bet they are rare. What's probably more likely
is that somebody - either a PostgreSQL developer or a Microsoft
developer - carelessly exposed a global name that's not very
distinctive, and it then collided -- either then or later -- with some
local variables in various places within the PostgreSQL code. If those
are names exposed by PostgreSQL, we should just rename the global
variables we exposed to have more distinctive names. If they're
exposed by Microsoft, we don't have that option, so we either have to
rename the local variables that shadow them, or decide that we don't
care.

Based on previous discussion in this forum, my guess is that popular
sentiment will depend quite a bit on how reasonable it seems that
Microsoft chose to use the name in the first place. If there's an
"extern int i;" declaration someplace in a Windows header file, we are
not for that reason going to abandon our practice of using "i" for
loop variables; we're (probably) just going to say nasty things about
Microsoft and keep doing what we're doing. If there's an "extern int
__msft_ftw;" declaration in a Windows header file and for some reason
we've used that same name in our code, we're going to decide we were
dumb to use that as a name and change it. The amount of code churn
also plays a role. People will be reluctant to change thousands of
lines of PostgreSQL code to work around Microsoft-specific problems,
but if it's only a little bit of code then people won't mind very
much.

Maybe you want to post a few examples. It's hard to discuss in the abstract.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

#10Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Robert Haas (#9)
RE: [Proposal] Level4 Warnings show many shadow vars

Robert Haas wrote:

Maybe you want to post a few examples. It's hard to discuss in the abstract.

I am working on the patch.
I think this is a great example.
I do not know if it is better to rename the local parameter, or if it should be renamed the global variable.

line: 68
var char **synchronous_commit
backend/commands/subscriptioncmds.c

global var declared here:
/include/access/xact.h(82)

One question, is it better to submit the patch on this topic, or create a new one?

regards,
Ranier Vilela

#11Mark Dilger
hornschnorter@gmail.com
In reply to: Ranier Vilela (#10)
Re: [Proposal] Level4 Warnings show many shadow vars

On 12/6/19 3:18 PM, Ranier Vilela wrote:

Robert Haas wrote:

Maybe you want to post a few examples. It's hard to discuss in the abstract.

I am working on the patch.
I think this is a great example.
I do not know if it is better to rename the local parameter, or if it should be renamed the global variable.

line: 68
var char **synchronous_commit
backend/commands/subscriptioncmds.c

global var declared here:
/include/access/xact.h(82)

The local variables in subscriptioncmds.c named "synchronous_commit"
appear more times in that one file than the global variable appears
in total in the rest of the system, but that doesn't include other
references to the guc in code comments, in user facing strings, etc.

I think it is better to change this just in subscriptioncmds.c than
to change the global variable name everywhere else. I also tend to
agree with you that shadowing the global variable is bad practice.

One question, is it better to submit the patch on this topic, or create a new one?

You appear to be planning to submit lots of patches about lots of
different shadowed variables. If you start a new thread for this
particular variable, it seems you'd probably do that again and again
for the other ones, and that might be tedious for readers of the
-hackers list who aren't interested. To start, I'd prefer to see
the patch on this thread.

--
Mark Dilger

#12Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Mark Dilger (#11)
1 attachment(s)
RE: [Proposal] Level4 Warnings show many shadow vars

This is the first part of the variable shadow fixes.
Basically it consists of renaming the variables in collision with the global ones, with the minimum change in the semantics.

make check pass all the tests.

regards,
Ranier Vilela

Attachments:

shadow_global_v1.patchtext/x-patch; name=shadow_global_v1.patchDownload
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 6bc1a6b46d..55821d513c 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -892,8 +892,8 @@ static int	emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
 static void XLogFileClose(void);
 static void PreallocXlogFiles(XLogRecPtr endptr);
 static void RemoveTempXlogFiles(void);
-static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
-static void RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
+static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr XRedoRecPtr, XLogRecPtr endptr);
+static void RemoveXlogFile(const char *segname, XLogRecPtr XRedoRecPtr, XLogRecPtr endptr);
 static void UpdateLastRemovedPtr(char *filename);
 static void ValidateXLOGDirectoryStructure(void);
 static void CleanupBackupHistory(void);
@@ -2299,7 +2299,7 @@ assign_checkpoint_completion_target(double newval, void *extra)
  * XLOG segments? Returns the highest segment that should be preallocated.
  */
 static XLogSegNo
-XLOGfileslop(XLogRecPtr RedoRecPtr)
+XLOGfileslop(XLogRecPtr XRedoRecPtr)
 {
 	XLogSegNo	minSegNo;
 	XLogSegNo	maxSegNo;
@@ -2311,9 +2311,9 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	 * correspond to. Always recycle enough segments to meet the minimum, and
 	 * remove enough segments to stay below the maximum.
 	 */
-	minSegNo = RedoRecPtr / wal_segment_size +
+	minSegNo = XRedoRecPtr / wal_segment_size +
 		ConvertToXSegs(min_wal_size_mb, wal_segment_size) - 1;
-	maxSegNo = RedoRecPtr / wal_segment_size +
+	maxSegNo = XRedoRecPtr / wal_segment_size +
 		ConvertToXSegs(max_wal_size_mb, wal_segment_size) - 1;
 
 	/*
@@ -2328,7 +2328,7 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	/* add 10% for good measure. */
 	distance *= 1.10;
 
-	recycleSegNo = (XLogSegNo) ceil(((double) RedoRecPtr + distance) /
+	recycleSegNo = (XLogSegNo) ceil(((double) XRedoRecPtr + distance) /
 									wal_segment_size);
 
 	if (recycleSegNo < minSegNo)
@@ -3954,7 +3954,7 @@ RemoveTempXlogFiles(void)
  * whether we want to recycle rather than delete no-longer-wanted log files.
  */
 static void
-RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr XRedoRecPtr, XLogRecPtr endptr)
 {
 	DIR		   *xldir;
 	struct dirent *xlde;
@@ -3997,7 +3997,7 @@ RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 				/* Update the last removed location in shared memory first */
 				UpdateLastRemovedPtr(xlde->d_name);
 
-				RemoveXlogFile(xlde->d_name, RedoRecPtr, endptr);
+				RemoveXlogFile(xlde->d_name, XRedoRecPtr, endptr);
 			}
 		}
 	}
@@ -4078,7 +4078,7 @@ RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
  * somewhat arbitrarily, 10 future segments.
  */
 static void
-RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveXlogFile(const char *segname, XLogRecPtr XRedoRecPtr, XLogRecPtr endptr)
 {
 	char		path[MAXPGPATH];
 #ifdef WIN32
@@ -4094,10 +4094,10 @@ RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 		 * Initialize info about where to try to recycle to.
 		 */
 		XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
-		if (RedoRecPtr == InvalidXLogRecPtr)
+		if (XRedoRecPtr == InvalidXLogRecPtr)
 			recycleSegNo = endlogSegNo + 10;
 		else
-			recycleSegNo = XLOGfileslop(RedoRecPtr);
+			recycleSegNo = XLOGfileslop(XRedoRecPtr);
 	}
 	else
 		recycleSegNo = 0;		/* keep compiler quiet */
@@ -7158,11 +7158,11 @@ StartupXLOG(void)
 
 					if (info == XLOG_CHECKPOINT_SHUTDOWN)
 					{
-						CheckPoint	checkPoint;
+						CheckPoint	xcheckPoint;
 
-						memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
-						newTLI = checkPoint.ThisTimeLineID;
-						prevTLI = checkPoint.PrevTimeLineID;
+						memcpy(&xcheckPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+						newTLI = xcheckPoint.ThisTimeLineID;
+						prevTLI = xcheckPoint.PrevTimeLineID;
 					}
 					else if (info == XLOG_END_OF_RECOVERY)
 					{
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 67418b05f1..bc8156fcd6 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -70,7 +70,7 @@ report_invalid_record(XLogReaderState *state, const char *fmt,...)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wallog_segment_size, const char *waldir,
 				   XLogPageReadCB pagereadfunc, void *private_data)
 {
 	XLogReaderState *state;
@@ -99,7 +99,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, wallog_segment_size,
 					   waldir);
 
 	state->read_page = pagereadfunc;
diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c
index 5408edcfc2..2f17c140c2 100644
--- a/src/backend/commands/subscriptioncmds.c
+++ b/src/backend/commands/subscriptioncmds.c
@@ -57,7 +57,7 @@ static void
 parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 						   bool *enabled, bool *create_slot,
 						   bool *slot_name_given, char **slot_name,
-						   bool *copy_data, char **synchronous_commit,
+						   bool *copy_data, char **synchr_commit,
 						   bool *refresh)
 {
 	ListCell   *lc;
@@ -85,8 +85,8 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 	}
 	if (copy_data)
 		*copy_data = true;
-	if (synchronous_commit)
-		*synchronous_commit = NULL;
+	if (synchr_commit)
+		*synchr_commit = NULL;
 	if (refresh)
 		*refresh = true;
 
@@ -150,17 +150,17 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 			*copy_data = defGetBoolean(defel);
 		}
 		else if (strcmp(defel->defname, "synchronous_commit") == 0 &&
-				 synchronous_commit)
+				 synchr_commit)
 		{
-			if (*synchronous_commit)
+			if (*synchr_commit)
 				ereport(ERROR,
 						(errcode(ERRCODE_SYNTAX_ERROR),
 						 errmsg("conflicting or redundant options")));
 
-			*synchronous_commit = defGetString(defel);
+			*synchr_commit = defGetString(defel);
 
 			/* Test if the given value is valid for synchronous_commit GUC. */
-			(void) set_config_option("synchronous_commit", *synchronous_commit,
+			(void) set_config_option("synchronous_commit", *synchr_commit,
 									 PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
 									 false, 0, false);
 		}
@@ -317,7 +317,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	bool		enabled_given;
 	bool		enabled;
 	bool		copy_data;
-	char	   *synchronous_commit;
+	char	   *synchr_commit;
 	char	   *conninfo;
 	char	   *slotname;
 	bool		slotname_given;
@@ -332,7 +332,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	 */
 	parse_subscription_options(stmt->options, &connect, &enabled_given,
 							   &enabled, &create_slot, &slotname_given,
-							   &slotname, &copy_data, &synchronous_commit,
+							   &slotname, &copy_data, &synchr_commit,
 							   NULL);
 
 	/*
@@ -375,8 +375,8 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 		slotname = stmt->subname;
 
 	/* The default for synchronous_commit of subscriptions is off. */
-	if (synchronous_commit == NULL)
-		synchronous_commit = "off";
+	if (synchr_commit == NULL)
+		synchr_commit = "off";
 
 	conninfo = stmt->conninfo;
 	publications = stmt->publication;
@@ -407,7 +407,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	else
 		nulls[Anum_pg_subscription_subslotname - 1] = true;
 	values[Anum_pg_subscription_subsynccommit - 1] =
-		CStringGetTextDatum(synchronous_commit);
+		CStringGetTextDatum(synchr_commit);
 	values[Anum_pg_subscription_subpublications - 1] =
 		publicationListToArray(publications);
 
@@ -430,14 +430,14 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	{
 		XLogRecPtr	lsn;
 		char	   *err;
-		WalReceiverConn *wrconn;
+		WalReceiverConn *walrconn;
 		List	   *tables;
 		ListCell   *lc;
 		char		table_state;
 
 		/* Try to connect to the publisher. */
-		wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
-		if (!wrconn)
+		walrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
+		if (!walrconn)
 			ereport(ERROR,
 					(errmsg("could not connect to the publisher: %s", err)));
 
@@ -668,11 +668,11 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
 			{
 				char	   *slotname;
 				bool		slotname_given;
-				char	   *synchronous_commit;
+				char	   *synchr_commit;
 
 				parse_subscription_options(stmt->options, NULL, NULL, NULL,
 										   NULL, &slotname_given, &slotname,
-										   NULL, &synchronous_commit, NULL);
+										   NULL, &synchr_commit, NULL);
 
 				if (slotname_given)
 				{
@@ -690,10 +690,10 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
 					replaces[Anum_pg_subscription_subslotname - 1] = true;
 				}
 
-				if (synchronous_commit)
+				if (synchr_commit)
 				{
 					values[Anum_pg_subscription_subsynccommit - 1] =
-						CStringGetTextDatum(synchronous_commit);
+						CStringGetTextDatum(synchr_commit);
 					replaces[Anum_pg_subscription_subsynccommit - 1] = true;
 				}
 
@@ -835,7 +835,7 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	char		originname[NAMEDATALEN];
 	char	   *err = NULL;
 	RepOriginId originid;
-	WalReceiverConn *wrconn = NULL;
+	WalReceiverConn *walrconn = NULL;
 	StringInfoData cmd;
 	Form_pg_subscription form;
 
@@ -982,8 +982,8 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	initStringInfo(&cmd);
 	appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
 
-	wrconn = walrcv_connect(conninfo, true, subname, &err);
-	if (wrconn == NULL)
+	walrconn = walrcv_connect(conninfo, true, subname, &err);
+	if (walrconn == NULL)
 		ereport(ERROR,
 				(errmsg("could not connect to publisher when attempting to "
 						"drop the replication slot \"%s\"", slotname),
@@ -996,7 +996,7 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	{
 		WalRcvExecResult *res;
 
-		res = walrcv_exec(wrconn, cmd.data, 0, NULL);
+		res = walrcv_exec(walrconn, cmd.data, 0, NULL);
 
 		if (res->status != WALRCV_OK_COMMAND)
 			ereport(ERROR,
@@ -1012,7 +1012,7 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	}
 	PG_FINALLY();
 	{
-		walrcv_disconnect(wrconn);
+		walrcv_disconnect(walrconn);
 	}
 	PG_END_TRY();
 
@@ -1124,7 +1124,7 @@ AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
  * publisher connection.
  */
 static List *
-fetch_table_list(WalReceiverConn *wrconn, List *publications)
+fetch_table_list(WalReceiverConn *walrconn, List *publications)
 {
 	WalRcvExecResult *res;
 	StringInfoData cmd;
@@ -1154,7 +1154,7 @@ fetch_table_list(WalReceiverConn *wrconn, List *publications)
 	}
 	appendStringInfoChar(&cmd, ')');
 
-	res = walrcv_exec(wrconn, cmd.data, 2, tableRow);
+	res = walrcv_exec(walrconn, cmd.data, 2, tableRow);
 	pfree(cmd.data);
 
 	if (res->status != WALRCV_OK_TUPLES)
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index a9edbfd4a4..1f5921b6e7 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -225,7 +225,7 @@ main(int argc, char *argv[])
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *prog_name)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -244,7 +244,7 @@ startup_hacks(const char *progname)
 		if (err != 0)
 		{
 			write_stderr("%s: WSAStartup failed: %d\n",
-						 progname, err);
+						 prog_name, err);
 			exit(1);
 		}
 
@@ -305,10 +305,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *prog_name)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), prog_name);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), prog_name);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -365,7 +365,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *prog_name)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -388,7 +388,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 prog_name);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 9ff2832c00..29a3a7517d 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -2538,7 +2538,7 @@ ConnFree(Port *conn)
  * the global variable yet when this is called.
  */
 void
-ClosePostmasterPorts(bool am_syslogger)
+ClosePostmasterPorts(bool syslogger)
 {
 	int			i;
 
@@ -2567,7 +2567,7 @@ ClosePostmasterPorts(bool am_syslogger)
 	}
 
 	/* If using syslogger, close the read side of the pipe */
-	if (!am_syslogger)
+	if (!syslogger)
 	{
 #ifndef WIN32
 		if (syslogPipe[0] >= 0)
diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index 709bbaaf5a..63097739c4 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -508,16 +508,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		ndays = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + ndays;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((ndays >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -532,16 +532,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		ndays = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - ndays;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((ndays >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -1810,18 +1810,18 @@ interval_time(PG_FUNCTION_ARGS)
 {
 	Interval   *span = PG_GETARG_INTERVAL_P(0);
 	TimeADT		result;
-	int64		days;
+	int64		ndays;
 
 	result = span->time;
 	if (result >= USECS_PER_DAY)
 	{
-		days = result / USECS_PER_DAY;
-		result -= days * USECS_PER_DAY;
+		ndays = result / USECS_PER_DAY;
+		result -= ndays * USECS_PER_DAY;
 	}
 	else if (result < 0)
 	{
-		days = (-result + USECS_PER_DAY - 1) / USECS_PER_DAY;
-		result += days * USECS_PER_DAY;
+		ndays = (-result + USECS_PER_DAY - 1) / USECS_PER_DAY;
+		result += ndays * USECS_PER_DAY;
 	}
 
 	PG_RETURN_TIMEADT(result);
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 31bdb37c55..2f721ee67e 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -1500,9 +1500,9 @@ Datum
 make_interval(PG_FUNCTION_ARGS)
 {
 	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
+	int32		nmonths = PG_GETARG_INT32(1);
 	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
+	int32		ndays = PG_GETARG_INT32(3);
 	int32		hours = PG_GETARG_INT32(4);
 	int32		mins = PG_GETARG_INT32(5);
 	double		secs = PG_GETARG_FLOAT8(6);
@@ -1518,8 +1518,8 @@ make_interval(PG_FUNCTION_ARGS)
 				 errmsg("interval out of range")));
 
 	result = (Interval *) palloc(sizeof(Interval));
-	result->month = years * MONTHS_PER_YEAR + months;
-	result->day = weeks * 7 + days;
+	result->month = years * MONTHS_PER_YEAR + nmonths;
+	result->day = weeks * 7 + ndays;
 
 	secs = rint(secs * USECS_PER_SEC);
 	result->time = hours * ((int64) SECS_PER_HOUR * USECS_PER_SEC) +
@@ -2343,22 +2343,22 @@ interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
 	int64		dayfraction;
-	int64		days;
+	int64		ndays;
 
 	/*
 	 * Separate time field into days and dayfraction, then add the month and
 	 * day fields to the days part.  We cannot overflow int64 days here.
 	 */
 	dayfraction = interval->time % USECS_PER_DAY;
-	days = interval->time / USECS_PER_DAY;
-	days += interval->month * INT64CONST(30);
-	days += interval->day;
+	ndays = interval->time / USECS_PER_DAY;
+	ndays += interval->month * INT64CONST(30);
+	ndays += interval->day;
 
 	/* Widen dayfraction to 128 bits */
 	span = int64_to_int128(dayfraction);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, ndays, USECS_PER_DAY);
 
 	return span;
 }
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index ba74bf9f7d..1644c66236 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -5389,7 +5389,7 @@ InitializeOneGUCOption(struct config_generic *gconf)
  * to stderr and returns false.
  */
 bool
-SelectConfigFiles(const char *userDoption, const char *progname)
+SelectConfigFiles(const char *userDoption, const char *prog_name)
 {
 	char	   *configdir;
 	char	   *fname;
@@ -5404,7 +5404,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 	if (configdir && stat(configdir, &stat_buf) != 0)
 	{
 		write_stderr("%s: could not access directory \"%s\": %s\n",
-					 progname,
+					 prog_name,
 					 configdir,
 					 strerror(errno));
 		if (errno == ENOENT)
@@ -5431,7 +5431,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 		write_stderr("%s does not know where to find the server configuration file.\n"
 					 "You must specify the --config-file or -D invocation "
 					 "option or set the PGDATA environment variable.\n",
-					 progname);
+					 prog_name);
 		return false;
 	}
 
@@ -5448,7 +5448,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 	if (stat(ConfigFileName, &stat_buf) != 0)
 	{
 		write_stderr("%s: could not access the server configuration file \"%s\": %s\n",
-					 progname, ConfigFileName, strerror(errno));
+					 prog_name, ConfigFileName, strerror(errno));
 		free(configdir);
 		return false;
 	}
@@ -5477,7 +5477,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 					 "This can be specified as \"data_directory\" in \"%s\", "
 					 "or by the -D invocation option, or by the "
 					 "PGDATA environment variable.\n",
-					 progname, ConfigFileName);
+					 prog_name, ConfigFileName);
 		return false;
 	}
 
@@ -5525,7 +5525,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 					 "This can be specified as \"hba_file\" in \"%s\", "
 					 "or by the -D invocation option, or by the "
 					 "PGDATA environment variable.\n",
-					 progname, ConfigFileName);
+					 prog_name, ConfigFileName);
 		return false;
 	}
 	SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
@@ -5548,7 +5548,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 					 "This can be specified as \"ident_file\" in \"%s\", "
 					 "or by the -D invocation option, or by the "
 					 "PGDATA environment variable.\n",
-					 progname, ConfigFileName);
+					 prog_name, ConfigFileName);
 		return false;
 	}
 	SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 1f6d8939be..d49509e7a5 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -266,10 +266,10 @@ static void trapsig(int signum);
 static void check_ok(void);
 static char *escape_quotes(const char *src);
 static char *escape_quotes_bki(const char *src);
-static int	locale_date_order(const char *locale);
-static void check_locale_name(int category, const char *locale,
+static int	locale_date_order(const char *locale_name);
+static void check_locale_name(int category, const char *locale_name,
 							  char **canonname);
-static bool check_locale_encoding(const char *locale, int encoding);
+static bool check_locale_encoding(const char *locale_name, int encoding);
 static void setlocales(void);
 static void usage(const char *progname);
 void		setup_pgdata(void);
@@ -631,7 +631,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user_name;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -644,9 +644,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user_name = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user_name);
 }
 
 static char *
@@ -864,17 +864,17 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *conffile;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+	conffile = fopen(path, PG_BINARY_W);
+	if (conffile == NULL)
 	{
 		pg_log_error("could not open file \"%s\" for writing: %m", path);
 		exit(1);
 	}
-	if (fclose(conf_file))
+	if (fclose(conffile))
 	{
 		pg_log_error("could not write file \"%s\": %m", path);
 		exit(1);
@@ -2107,7 +2107,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *locale_name)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2125,7 +2125,7 @@ locale_date_order(const char *locale)
 		return result;
 	save = pg_strdup(save);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, locale_name);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2170,7 +2170,7 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *locale_name, char **canonname)
 {
 	char	   *save;
 	char	   *res;
@@ -2193,7 +2193,7 @@ check_locale_name(int category, const char *locale, char **canonname)
 		locale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, locale_name);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2210,8 +2210,8 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
-			pg_log_error("invalid locale name \"%s\"", locale);
+		if (*locale_name)
+			pg_log_error("invalid locale name \"%s\"", locale_name);
 		else
 		{
 			/*
@@ -2234,11 +2234,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *locale_name, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(locale_name, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2321,11 +2321,11 @@ setlocales(void)
  * print help text
  */
 static void
-usage(const char *progname)
+usage(const char *prog_name)
 {
-	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), prog_name);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION]... [DATADIR]\n"), prog_name);
 	printf(_("\nOptions:\n"));
 	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
 	printf(_("      --auth-host=METHOD    default authentication method for local TCP/IP connections\n"));
@@ -2393,22 +2393,22 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
+check_need_password(const char *authmethod_local, const char *authmethod_host)
 {
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+	if ((strcmp(authmethod_local, "md5") == 0 ||
+		 strcmp(authmethod_local, "password") == 0 ||
+		 strcmp(authmethod_local, "scram-sha-256") == 0) &&
+		(strcmp(authmethod_host, "md5") == 0 ||
+		 strcmp(authmethod_host, "password") == 0 ||
+		 strcmp(authmethod_host, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 	{
 		pg_log_error("must specify a password for the superuser to enable %s authentication",
-					 (strcmp(authmethodlocal, "md5") == 0 ||
-					  strcmp(authmethodlocal, "password") == 0 ||
-					  strcmp(authmethodlocal, "scram-sha-256") == 0)
-					 ? authmethodlocal
-					 : authmethodhost);
+					 (strcmp(authmethod_local, "md5") == 0 ||
+					  strcmp(authmethod_local, "password") == 0 ||
+					  strcmp(authmethod_local, "scram-sha-256") == 0)
+					 ? authmethod_local
+					 : authmethod_host);
 		exit(1);
 	}
 }
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index 19e21ab491..11784c589b 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -30,11 +30,11 @@
 #include "pg_getopt.h"
 
 static void
-usage(const char *progname)
+usage(const char *prog_name)
 {
-	printf(_("%s displays control information of a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s displays control information of a PostgreSQL database cluster.\n\n"), prog_name);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION] [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION] [DATADIR]\n"), prog_name);
 	printf(_("\nOptions:\n"));
 	printf(_(" [-D, --pgdata=]DATADIR  data directory\n"));
 	printf(_("  -V, --version          output version information, then exit\n"));
@@ -69,9 +69,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel wallevel)
 {
-	switch (wal_level)
+	switch (wallevel)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 65f9fb4c0a..80715bae01 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -742,7 +742,7 @@ read_post_opts(void)
  * waiting for the server to start up, the server launch is aborted.
  */
 static void
-trap_sigint_during_startup(int sig)
+trap_sigint_during_startup(int signal)
 {
 	if (postmasterPID != -1)
 	{
@@ -760,18 +760,18 @@ trap_sigint_during_startup(int sig)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *argv_0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(argv_0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(argv_0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c
index 37432a6f4b..135b9e13de 100644
--- a/src/bin/pg_dump/common.c
+++ b/src/bin/pg_dump/common.c
@@ -64,10 +64,10 @@ static int	numExtensions;
 static ExtensionMemberId *extmembers;
 static int	numextmembers;
 
-static void flagInhTables(Archive *fout, TableInfo *tbinfo, int numTables,
+static void flagInhTables(Archive *fout, TableInfo *tbinfo, int num_Tables,
 						  InhInfo *inhinfo, int numInherits);
-static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int numTables);
-static void flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables);
+static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int num_Tables);
+static void flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int num_Tables);
 static DumpableObject **buildIndexArray(void *objArray, int numObjs,
 										Size objSize);
 static int	DOCatalogIdCompare(const void *p1, const void *p2);
@@ -270,14 +270,14 @@ getSchemaData(Archive *fout, int *numTablesPtr)
  * modifies tblinfo
  */
 static void
-flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
+flagInhTables(Archive *fout, TableInfo *tblinfo, int num_Tables,
 			  InhInfo *inhinfo, int numInherits)
 {
 	DumpOptions *dopt = fout->dopt;
 	int			i,
 				j;
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < num_Tables; i++)
 	{
 		bool		find_parents = true;
 		bool		mark_parents = true;
@@ -329,7 +329,7 @@ flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
  *	 appropriate dependency links.
  */
 static void
-flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
+flagInhIndexes(Archive *fout, TableInfo tblinfo[], int num_Tables)
 {
 	int			i,
 				j,
@@ -339,7 +339,7 @@ flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
 	parentIndexArray = (DumpableObject ***)
 		pg_malloc0(getMaxDumpId() * sizeof(DumpableObject **));
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < num_Tables; i++)
 	{
 		TableInfo  *parenttbl;
 		IndexAttachInfo *attachinfo;
@@ -436,13 +436,13 @@ flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
  * modifies tblinfo
  */
 static void
-flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables)
+flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int num_Tables)
 {
 	int			i,
 				j,
 				k;
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < num_Tables; i++)
 	{
 		TableInfo  *tbinfo = &(tblinfo[i]);
 		int			numParents;
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 08658c8e86..5cfa243ad4 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -147,7 +147,7 @@ static int	extra_float_digits;
 	fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
 				   (obj)->dobj.name)
 
-static void help(const char *progname);
+static void help(const char *prog_name);
 static void setup_connection(Archive *AH,
 							 const char *dumpencoding, const char *dumpsnapshot,
 							 char *use_role);
@@ -155,11 +155,11 @@ static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
 static void expand_schema_name_patterns(Archive *fout,
 										SimpleStringList *patterns,
 										SimpleOidList *oids,
-										bool strict_names);
+										bool strictnames);
 static void expand_table_name_patterns(Archive *fout,
 									   SimpleStringList *patterns,
 									   SimpleOidList *oids,
-									   bool strict_names);
+									   bool strictnames);
 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
@@ -972,11 +972,11 @@ main(int argc, char **argv)
 
 
 static void
-help(const char *progname)
+help(const char *prog_name)
 {
-	printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
+	printf(_("%s dumps a database as a text file or to other formats.\n\n"), prog_name);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), prog_name);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -f, --file=FILENAME          output file or directory name\n"));
@@ -1293,7 +1293,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool strictnames)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1318,7 +1318,7 @@ expand_schema_name_patterns(Archive *fout,
 							  false, NULL, "n.nspname", NULL, NULL);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strictnames && PQntuples(res) == 0)
 			fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1341,7 +1341,7 @@ expand_schema_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names)
+						   bool strictnames)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1383,7 +1383,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (strictnames && PQntuples(res) == 0)
 			fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index d1a36b1495..67fa5e8975 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -50,7 +50,7 @@
 #include "parallel.h"
 #include "pg_backup_utils.h"
 
-static void usage(const char *progname);
+static void usage(const char *prog_name);
 
 int
 main(int argc, char **argv)
@@ -456,11 +456,11 @@ main(int argc, char **argv)
 }
 
 static void
-usage(const char *progname)
+usage(const char *prog_name)
 {
-	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), progname);
+	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), prog_name);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [FILE]\n"), progname);
+	printf(_("  %s [OPTION]... [FILE]\n"), prog_name);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -d, --dbname=NAME        connect to database name\n"));
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 2e286f6339..7fb590ffb8 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -738,9 +738,9 @@ GuessControlValues(void)
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool guessed_control)
 {
-	if (guessed)
+	if (guessed_control)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 2ca1608bd2..0023c67938 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -91,7 +91,7 @@ static void signal_cleanup(int sig);
 #ifdef HAVE_FSYNC_WRITETHROUGH
 static int	pg_fsync_writethrough(int fd);
 #endif
-static void print_elapse(struct timeval start_t, struct timeval stop_t, int ops);
+static void print_elapse(struct timeval startt, struct timeval stopt, int ops);
 
 #define die(msg) do { pg_log_error("%s: %m", _(msg)); exit(1); } while(0)
 
@@ -576,10 +576,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval startt, struct timeval stopt, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-	(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stopt.tv_sec - startt.tv_sec) +
+	(stopt.tv_usec - startt.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
diff --git a/src/include/access/xlogreader.h b/src/include/access/xlogreader.h
index 0193611b7f..d8991d1a79 100644
--- a/src/include/access/xlogreader.h
+++ b/src/include/access/xlogreader.h
@@ -209,7 +209,7 @@ struct XLogReaderState
 };
 
 /* Get a new XLogReader */
-extern XLogReaderState *XLogReaderAllocate(int wal_segment_size,
+extern XLogReaderState *XLogReaderAllocate(int wallog_segment_size,
 										   const char *waldir,
 										   XLogPageReadCB pagereadfunc,
 										   void *private_data);
diff --git a/src/include/utils/guc.h b/src/include/utils/guc.h
index 50098e63fe..809f043ba1 100644
--- a/src/include/utils/guc.h
+++ b/src/include/utils/guc.h
@@ -354,7 +354,7 @@ extern const char *GetConfigOptionResetString(const char *name);
 extern int	GetConfigOptionFlags(const char *name, bool missing_ok);
 extern void ProcessConfigFile(GucContext context);
 extern void InitializeGUCOptions(void);
-extern bool SelectConfigFiles(const char *userDoption, const char *progname);
+extern bool SelectConfigFiles(const char *userDoption, const char *prog_name);
 extern void ResetAllOptions(void);
 extern void AtStart_GUC(void);
 extern int	NewGUCNestLevel(void);
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index a29f530327..7568d1c1a9 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -73,7 +73,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(char *name, char *connection)
+add_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *new;
 
@@ -87,16 +87,16 @@ add_descriptor(char *name, char *connection)
 	strcpy(new->name, name);
 	if (connection)
 	{
-		new->connection = mm_alloc(strlen(connection) + 1);
-		strcpy(new->connection, connection);
+		new->connection = mm_alloc(strlen(conn_str) + 1);
+		strcpy(new->connection, conn_str);
 	}
 	else
-		new->connection = connection;
+		new->connection = conn_str;
 	descriptors = new;
 }
 
 void
-drop_descriptor(char *name, char *connection)
+drop_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -108,9 +108,9 @@ drop_descriptor(char *name, char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				if (i->connection)
@@ -126,7 +126,7 @@ drop_descriptor(char *name, char *connection)
 
 struct descriptor
 		   *
-lookup_descriptor(char *name, char *connection)
+lookup_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *i;
 
@@ -137,9 +137,9 @@ lookup_descriptor(char *name, char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
 		}
 	}
#13Mark Dilger
hornschnorter@gmail.com
In reply to: Ranier Vilela (#12)
Re: [Proposal] Level4 Warnings show many shadow vars

On 12/7/19 3:42 PM, Ranier Vilela wrote:

This is the first part of the variable shadow fixes.
Basically it consists of renaming the variables in collision with the global ones, with the minimum change in the semantics.

make check pass all the tests.

I think it would be better to split this patch into separate files,
one for each global variable that is being shadowed. The reason
I say so is apparent looking at the first one in the patch,
RedoRecPtr. This process global variable is defined in xlog.c:

static XLogRecPtr RedoRecPtr;

and then, somewhat surprisingly, passed around between static
functions defined within that same file, such as:

RemoveOldXlogFiles(...)

which in the current code only ever gets a copy of the global,
which begs the question why it needs this passed as a parameter
at all. All the places calling RemoveOldXlogFiles are within
this file, and all of them pass the global, so why bother?

Another function within xlog.c behaves similarly:

RemoveXlogFile(...)

Only here, the callers sometimes pass the global RedoRecPtr
(though indirectly, since they themselves received it as an
argument) and sometimes they pass in InvalidXLogRecPtr, which
is just a constant:

src/include/access/xlogdefs.h:#define InvalidXLogRecPtr 0

So it might make sense to remove the parameter from this
function, too, and replace it with a flag parameter named
something like "is_valid", or perhaps split the function
into two functions, one for valid and one for invalid.

I'm not trying to redesign xlog.c's functions in this email
thread, but only suggesting that these types of arguments
may ensue for each global variable in your patch, and it will
be easier for a committer to know if there is a consensus
about any one of them than about the entire set. When I
suggested you do this patch set all on this thread, I was
still expecting multiple patches, perhaps named along the
lines of:

unshadow.RedoRecPtr.patch.1
unshadow.wal_segment_size.patch.1
unshadow.synchronous_commit.patch.1
unshadow.wrconn.patch.1
unshadow.progname.patch.1
unshadow.am_syslogger.patch.1
unshadow.days.patch.1
unshadow.months.patch.1

etc. I'm uncomfortable giving you negative feedback of this
sort, since I think you are working hard to improve postgres
and I really appreciate it, so later tonight I'll try to come
back, split your patch for you as described, add an entry to
the commitfest if you haven't already, and mark myself as a
reviewer.

Thanks again for the hard work and the patch!

--
Mark Dilger

#14Tom Lane
tgl@sss.pgh.pa.us
In reply to: Ranier Vilela (#12)
Re: [Proposal] Level4 Warnings show many shadow vars

Ranier Vilela <ranier_gyn@hotmail.com> writes:

This is the first part of the variable shadow fixes.
Basically it consists of renaming the variables in collision with the global ones, with the minimum change in the semantics.

I don't think I'm actually on board with the goal here.

Basically, if we take this seriously, we're throwing away the notion of
nested variable scopes and programming as if we had just a flat namespace.
That wasn't any fun when we had to do it back in assembly-code days, and
I don't see a good reason to revert to that methodology today.

In a few of these cases, like the RedoRecPtr changes, there *might* be
an argument that there's room for confusion about whether the code could
have meant to reference the similarly-named global variable. But it's
just silly to make that argument in places like your substitution of
/days/ndays/ in date.c.

Based on this sample, I reject the idea that we ought to be trying to
eliminate this class of warnings just because somebody's compiler can be
induced to emit them. If you want to make a case-by-case argument that
particular situations of this sort are bad programming style, let's have
that argument by all means. But it needs to be case-by-case, not just
dropping a large patch on us containing a bunch of unrelated changes
and zero specific justification for any of them.

IOW, I don't think you've taken to heart Robert's upthread advice that
this needs to be case-by-case and based on literary not mechanical
considerations.

BTW, if we do go forward with changing the RedoRecPtr uses, I'm not
in love with "XRedoRecPtr" as a replacement parameter name; it conveys
nothing much, and the "X" prefix is already overused in that area of
the code. Perhaps "pRedoRecPtr" would be a better choice? Or maybe
make the local variables be all-lower-case "redorecptr", which would
fit well in context in places like

-RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveXlogFile(const char *segname, XLogRecPtr XRedoRecPtr, XLogRecPtr endptr)

regards, tom lane

#15Tom Lane
tgl@sss.pgh.pa.us
In reply to: Mark Dilger (#13)
Re: [Proposal] Level4 Warnings show many shadow vars

Mark Dilger <hornschnorter@gmail.com> writes:

I think it would be better to split this patch into separate files,
one for each global variable that is being shadowed. The reason
I say so is apparent looking at the first one in the patch,
RedoRecPtr. This process global variable is defined in xlog.c:
static XLogRecPtr RedoRecPtr;
and then, somewhat surprisingly, passed around between static
functions defined within that same file, such as:
RemoveOldXlogFiles(...)
which in the current code only ever gets a copy of the global,
which begs the question why it needs this passed as a parameter
at all. All the places calling RemoveOldXlogFiles are within
this file, and all of them pass the global, so why bother?

I was wondering about that too. A look in the git history seems
to say that it is the fault of the fairly-recent commit d9fadbf13,
which did things like this:

 /*
  * Recycle or remove all log files older or equal to passed segno.
  *
- * endptr is current (or recent) end of xlog, and PriorRedoRecPtr is the
- * redo pointer of the previous checkpoint. These are used to determine
+ * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
  */
 static void
-RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr PriorRedoPtr, XLogRecPtr endptr)
+RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 {
    DIR        *xldir;
    struct dirent *xlde;

That is, these arguments *used* to be a different LSN pointer, and that
commit changed them to be mostly equal to RedoRecPtr, and made what
seems like a not very well-advised renaming to go with that.

So it might make sense to remove the parameter from this
function, too, and replace it with a flag parameter named
something like "is_valid", or perhaps split the function
into two functions, one for valid and one for invalid.

Don't think I buy that. The fact that these arguments were until recently
different from RedoRecPtr suggests that they might someday be different
again, whereupon we'd have to laboriously revert such a parameter redesign.
I think I'd just go for names that don't have a hard implication that
the parameter values are the same as any particular global variable.

I'm not trying to redesign xlog.c's functions in this email
thread, but only suggesting that these types of arguments
may ensue for each global variable in your patch,

Indeed. Once again, these are case-by-case issues, not something
that can be improved by a global search-and-replace without much
consideration for the details of each case.

regards, tom lane

#16Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Mark Dilger (#13)
RE: [Proposal] Level4 Warnings show many shadow vars

I think it would be better to split this patch into separate files,
one for each global variable that is being shadowed.

Ok, I agree.

The reasonI say so is apparent looking at the first one in the patch,
RedoRecPtr. This process global variable is defined in xlog.c:
static XLogRecPtr RedoRecPtr;
and then, somewhat surprisingly, passed around between static
functions defined within that same file, such as:
RemoveOldXlogFiles(...)
which in the current code only ever gets a copy of the global,
which begs the question why it needs this passed as a parameter
at all. All the places calling RemoveOldXlogFiles are within
this file, and all of them pass the global, so why bother?

In general I do not agree to use global variables. But I understand when you use it, I believe it is a necessary evil.
So I think that maybe the original author, has the same thought and when using a local parameter to pass the variable, and there is a way to further eliminate the use of the global variable, maybe it was unfortunate in choosing the name.
And what it would do in this case, with the aim of eliminating the global variable in the future.
In my own systems, I make use of only one global variable, and in many functions I pass as a parameter, with another name.

Another function within xlog.c behaves similarly:
RemoveXlogFile(...)
Only here, the callers sometimes pass the global RedoRecPtr
(tough indirectly, since they themselves received it as an
argument) and sometimes they pass in InvalidXLogRecPtr, which
is just a constant:
src/include/access/xlogdefs.h:#define InvalidXLogRecPtr 0
So it might make sense to remove the parameter from this
function, too, and replace it with a flag parameter named
something like "is_valid", or perhaps split the function
into two functions, one for valid and one for invalid.

Again in this case, it would have to be checked whether postgres really will make use of the global variable forever.
Which for me is a bad design.

Another complicated case of global variable is PGconn * conn. It is defined as global somewhere, but there is widespread use of the name "conn" in many places in the code, many in / bin, so if it is in the interest of postgres to correct this, it would be better to rename the global variable to something like pg_conn, or gconn.

I'm not trying to redesign xlog.c's functions in this email
thread, but only suggesting that these types of arguments
may ensue for each global variable in your patch, and it will
be easier for a committer to know if there is a consensus
about any one of them than about the entire set. When I
suggested you do this patch set all on this thread, I was
still expecting multiple patches, perhaps named along the
lines of:
unshadow.RedoRecPtr.patch.1
unshadow.wal_segment_size.patch.1
unshadow.synchronous_commit.patch.1
unshadow.wrconn.patch.1
unshadow.progname.patch.1
unshadow.am_syslogger.patch.1
unshadow.days.patch.1
unshadow.months.patch.1
etc. I'm uncomfortable giving you negative feedback of this
sort, since I think you are working hard to improve postgres
and I really appreciate it, so later tonight I'll try to come
back, split your patch for you as described, add an entry to
the commitfest if you haven't already, and mark myself as a
reviewer.

I appreciate your help.

Thanks again for the hard work and the patch!

You are welcome.

regards,
Ranier Vilela

--
Mark Dilger

#17Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Tom Lane (#14)
RE: [Proposal] Level4 Warnings show many shadow vars

I don't think I'm actually on board with the goal here.

Ok, I understand.

Basically, if we take this seriously, we're throwing away the notion of
nested variable scopes and programming as if we had just a flat namespace.
That wasn't any fun when we had to do it back in assembly-code days, and
I don't see a good reason to revert to that methodology today.

In general I think the use global variables its a bad design. But I understand the use.

In a few of these cases, like the RedoRecPtr changes, there *might* be
an argument that there's room for confusion about whether the code could
have meant to reference the similarly-named global variable. But it's
just silly to make that argument in places like your substitution of
/days/ndays/ in date.c.

I would rather fix everything, including days name.

Based on this sample, I reject the idea that we ought to be trying to
eliminate this class of warnings just because somebody's compiler can be
induced to emit them. If you want to make a case-by-case argument that
particular situations of this sort are bad programming style, let's have
that argument by all means. But it needs to be case-by-case, not just
dropping a large patch on us containing a bunch of unrelated changes
and zero specific justification for any of them.

This is why I suggested activating the alert in the development and review process, so that any cases that arose would be corrected very early.

IOW, I don't think you've taken to heart Robert's upthread advice that
this needs to be case-by-case and based on literary not mechanical
considerations.

Ok, right.
But I was working on the second class of shadow variables, which are local variables, within the function itself, where the patch would lead to a removal of the variable declaration, maintaining the same logic and functionality, which would lead to better performance and reduction. of memory usage as well as very small.
In that case, too, would it have to be case by case?
Wow, there are many and many shadow variables ...

BTW, if we do go forward with changing the RedoRecPtr uses, I'm not
in love with "XRedoRecPtr" as a replacement parameter name; it conveys
nothing much, and the "X" prefix is already overused in that area of
the code. Perhaps "pRedoRecPtr" would be a better choice? Or maybe
make the local variables be all-lower-case "redorecptr", which would
fit well in context in places like

pRedoRecPtr, It's perfect for me.

regards,
Ranier Vilela

#18Kyotaro Horiguchi
horikyota.ntt@gmail.com
In reply to: Ranier Vilela (#17)
Re: [Proposal] Level4 Warnings show many shadow vars

Hello.

At Mon, 9 Dec 2019 01:30:33 +0000, Ranier Vilela <ranier_gyn@hotmail.com> wrote in

I don't think I'm actually on board with the goal here.

Ok, I understand.

Basically, if we take this seriously, we're throwing away the notion of
nested variable scopes and programming as if we had just a flat namespace.
That wasn't any fun when we had to do it back in assembly-code days, and
I don't see a good reason to revert to that methodology today.

In general I think the use global variables its a bad design. But I understand the use.

The file-scoped variable is needed to be process-persistent in any
way. If we inhibit them, the upper-modules need to create the
persistent area instead, for example, by calling XLogInitGlobals() or
such, which makes things messier. Globality doens't necessarily mean
evil and there're reasons for -Wall doesn't warn the case. I believe
we, and especially committers are not who should be kept away from
knives for the reason that knives generally have a possibility to
injure someone.

In a few of these cases, like the RedoRecPtr changes, there *might* be
an argument that there's room for confusion about whether the code could
have meant to reference the similarly-named global variable. But it's
just silly to make that argument in places like your substitution of
/days/ndays/ in date.c.

I would rather fix everything, including days name.

I might be too accustomed there, but the functions that define
overriding locals don't modify the local variables and only the
functions that don't override the globals modifies the glboals. I see
no significant confusion here. By the way changes like "conf_file" ->
"conffile" seems really useless as a fix patch.

Based on this sample, I reject the idea that we ought to be trying to
eliminate this class of warnings just because somebody's compiler can be
induced to emit them. If you want to make a case-by-case argument that
particular situations of this sort are bad programming style, let's have
that argument by all means. But it needs to be case-by-case, not just
dropping a large patch on us containing a bunch of unrelated changes
and zero specific justification for any of them.

This is why I suggested activating the alert in the development and review process, so that any cases that arose would be corrected very early.

I don't think it contributes to the argument on programming style in
any way.

IOW, I don't think you've taken to heart Robert's upthread advice that
this needs to be case-by-case and based on literary not mechanical
considerations.

Ok, right.
But I was working on the second class of shadow variables, which are local variables, within the function itself, where the patch would lead to a removal of the variable declaration, maintaining the same logic and functionality, which would lead to better performance and reduction. of memory usage as well as very small.
In that case, too, would it have to be case by case?
Wow, there are many and many shadow variables ...

As Robert said, they are harmless as far as we notice. Actual bugs
caused by variable overriding would be welcomed to fix. I don't
believe "lead to better performance and reduction (of code?)" without
an evidence since modern compilers I think are not so stupid. Even if
any, performance change in such extent doesn't support the proposal to
remove variable overrides that way.

BTW, if we do go forward with changing the RedoRecPtr uses, I'm not
in love with "XRedoRecPtr" as a replacement parameter name; it conveys
nothing much, and the "X" prefix is already overused in that area of
the code. Perhaps "pRedoRecPtr" would be a better choice? Or maybe
make the local variables be all-lower-case "redorecptr", which would
fit well in context in places like

pRedoRecPtr, It's perfect for me.

Anyway I strongly object to the name 'pRedoRecPtr', which suggests as
if it is a C-pointer to some variable. (And I believe we use Hungarian
notation only if we don't have a better way...) LatestRedoRecPtr
looks better to me.

regards.

--
Kyotaro Horiguchi
NTT Open Source Software Center

#19Mark Dilger
hornschnorter@gmail.com
In reply to: Mark Dilger (#13)
6 attachment(s)
Re: [Proposal] Level4 Warnings show many shadow vars

On 12/8/19 10:25 AM, Mark Dilger wrote:

I was
still expecting multiple patches, perhaps named along the
lines of:

� unshadow.RedoRecPtr.patch.1
� unshadow.wal_segment_size.patch.1
� unshadow.synchronous_commit.patch.1
� unshadow.wrconn.patch.1
� unshadow.progname.patch.1
� unshadow.am_syslogger.patch.1
� unshadow.days.patch.1
� unshadow.months.patch.1

etc.� I'm uncomfortable giving you negative feedback of this
sort, since I think you are working hard to improve postgres
and I really appreciate it, so later tonight I'll try to come
back, split your patch for you as described, add an entry to
the commitfest if you haven't already, and mark myself as a
reviewer.

To start off, I've taken just six of the 22 or so variables
that you renamed and created patches for them. I'm not
endorsing these in any way. I chose these mostly based on
which ones showed up first in your patch file, with one
exception.

I stopped when I got to 'progname' => 'prog_name' as the
whole exercise was getting too absurd even for me. That
clearly looks like one where the structure of the code
needs to be reconsidered, rather than just renaming stuff.

I'll create the commitfest entry based on this email once
this has been sent.

Patches attached.

--
Mark Dilger

Attachments:

unshadow.checkPoint.patch.1text/plain; charset=UTF-8; name=unshadow.checkPoint.patch.1Download
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index e4e9ce7398..ae6f6261f5 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -7158,11 +7158,11 @@ StartupXLOG(void)
 
 					if (info == XLOG_CHECKPOINT_SHUTDOWN)
 					{
-						CheckPoint	checkPoint;
+						CheckPoint	xcheckPoint;
 
-						memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
-						newTLI = checkPoint.ThisTimeLineID;
-						prevTLI = checkPoint.PrevTimeLineID;
+						memcpy(&xcheckPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+						newTLI = xcheckPoint.ThisTimeLineID;
+						prevTLI = xcheckPoint.PrevTimeLineID;
 					}
 					else if (info == XLOG_END_OF_RECOVERY)
 					{
unshadow.connection.patch.1text/plain; charset=UTF-8; name=unshadow.connection.patch.1Download
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index a29f530327..da3291baca 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -73,7 +73,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(char *name, char *connection)
+add_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *new;
 
@@ -85,18 +85,18 @@ add_descriptor(char *name, char *connection)
 	new->next = descriptors;
 	new->name = mm_alloc(strlen(name) + 1);
 	strcpy(new->name, name);
-	if (connection)
+	if (conn_str)
 	{
-		new->connection = mm_alloc(strlen(connection) + 1);
-		strcpy(new->connection, connection);
+		new->connection = mm_alloc(strlen(conn_str) + 1);
+		strcpy(new->connection, conn_str);
 	}
 	else
-		new->connection = connection;
+		new->connection = conn_str;
 	descriptors = new;
 }
 
 void
-drop_descriptor(char *name, char *connection)
+drop_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -108,9 +108,9 @@ drop_descriptor(char *name, char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				if (i->connection)
@@ -126,7 +126,7 @@ drop_descriptor(char *name, char *connection)
 
 struct descriptor
 		   *
-lookup_descriptor(char *name, char *connection)
+lookup_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *i;
 
@@ -137,9 +137,9 @@ lookup_descriptor(char *name, char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
 		}
 	}
unshadow.RedoRecPtr.patch.1text/plain; charset=UTF-8; name=unshadow.RedoRecPtr.patch.1Download
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 6bc1a6b46d..e4e9ce7398 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -892,8 +892,8 @@ static int	emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
 static void XLogFileClose(void);
 static void PreallocXlogFiles(XLogRecPtr endptr);
 static void RemoveTempXlogFiles(void);
-static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
-static void RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
+static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr pRedoRecPtr, XLogRecPtr endptr);
+static void RemoveXlogFile(const char *segname, XLogRecPtr pRedoRecPtr, XLogRecPtr endptr);
 static void UpdateLastRemovedPtr(char *filename);
 static void ValidateXLOGDirectoryStructure(void);
 static void CleanupBackupHistory(void);
@@ -2299,7 +2299,7 @@ assign_checkpoint_completion_target(double newval, void *extra)
  * XLOG segments? Returns the highest segment that should be preallocated.
  */
 static XLogSegNo
-XLOGfileslop(XLogRecPtr RedoRecPtr)
+XLOGfileslop(XLogRecPtr pRedoRecPtr)
 {
 	XLogSegNo	minSegNo;
 	XLogSegNo	maxSegNo;
@@ -2311,9 +2311,9 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	 * correspond to. Always recycle enough segments to meet the minimum, and
 	 * remove enough segments to stay below the maximum.
 	 */
-	minSegNo = RedoRecPtr / wal_segment_size +
+	minSegNo = pRedoRecPtr / wal_segment_size +
 		ConvertToXSegs(min_wal_size_mb, wal_segment_size) - 1;
-	maxSegNo = RedoRecPtr / wal_segment_size +
+	maxSegNo = pRedoRecPtr / wal_segment_size +
 		ConvertToXSegs(max_wal_size_mb, wal_segment_size) - 1;
 
 	/*
@@ -2328,7 +2328,7 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	/* add 10% for good measure. */
 	distance *= 1.10;
 
-	recycleSegNo = (XLogSegNo) ceil(((double) RedoRecPtr + distance) /
+	recycleSegNo = (XLogSegNo) ceil(((double) pRedoRecPtr + distance) /
 									wal_segment_size);
 
 	if (recycleSegNo < minSegNo)
@@ -3954,7 +3954,7 @@ RemoveTempXlogFiles(void)
  * whether we want to recycle rather than delete no-longer-wanted log files.
  */
 static void
-RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr pRedoRecPtr, XLogRecPtr endptr)
 {
 	DIR		   *xldir;
 	struct dirent *xlde;
@@ -3997,7 +3997,7 @@ RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 				/* Update the last removed location in shared memory first */
 				UpdateLastRemovedPtr(xlde->d_name);
 
-				RemoveXlogFile(xlde->d_name, RedoRecPtr, endptr);
+				RemoveXlogFile(xlde->d_name, pRedoRecPtr, endptr);
 			}
 		}
 	}
@@ -4078,7 +4078,7 @@ RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
  * somewhat arbitrarily, 10 future segments.
  */
 static void
-RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveXlogFile(const char *segname, XLogRecPtr pRedoRecPtr, XLogRecPtr endptr)
 {
 	char		path[MAXPGPATH];
 #ifdef WIN32
@@ -4094,10 +4094,10 @@ RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 		 * Initialize info about where to try to recycle to.
 		 */
 		XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
-		if (RedoRecPtr == InvalidXLogRecPtr)
+		if (pRedoRecPtr == InvalidXLogRecPtr)
 			recycleSegNo = endlogSegNo + 10;
 		else
-			recycleSegNo = XLOGfileslop(RedoRecPtr);
+			recycleSegNo = XLOGfileslop(pRedoRecPtr);
 	}
 	else
 		recycleSegNo = 0;		/* keep compiler quiet */
unshadow.synchronous_commit.patch.1text/plain; charset=UTF-8; name=unshadow.synchronous_commit.patch.1Download
diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c
index 5408edcfc2..681d208f81 100644
--- a/src/backend/commands/subscriptioncmds.c
+++ b/src/backend/commands/subscriptioncmds.c
@@ -57,7 +57,7 @@ static void
 parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 						   bool *enabled, bool *create_slot,
 						   bool *slot_name_given, char **slot_name,
-						   bool *copy_data, char **synchronous_commit,
+						   bool *copy_data, char **synchr_commit,
 						   bool *refresh)
 {
 	ListCell   *lc;
@@ -85,8 +85,8 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 	}
 	if (copy_data)
 		*copy_data = true;
-	if (synchronous_commit)
-		*synchronous_commit = NULL;
+	if (synchr_commit)
+		*synchr_commit = NULL;
 	if (refresh)
 		*refresh = true;
 
@@ -150,17 +150,17 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 			*copy_data = defGetBoolean(defel);
 		}
 		else if (strcmp(defel->defname, "synchronous_commit") == 0 &&
-				 synchronous_commit)
+				 synchr_commit)
 		{
-			if (*synchronous_commit)
+			if (*synchr_commit)
 				ereport(ERROR,
 						(errcode(ERRCODE_SYNTAX_ERROR),
 						 errmsg("conflicting or redundant options")));
 
-			*synchronous_commit = defGetString(defel);
+			*synchr_commit = defGetString(defel);
 
 			/* Test if the given value is valid for synchronous_commit GUC. */
-			(void) set_config_option("synchronous_commit", *synchronous_commit,
+			(void) set_config_option("synchronous_commit", *synchr_commit,
 									 PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
 									 false, 0, false);
 		}
@@ -317,7 +317,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	bool		enabled_given;
 	bool		enabled;
 	bool		copy_data;
-	char	   *synchronous_commit;
+	char	   *synchr_commit;
 	char	   *conninfo;
 	char	   *slotname;
 	bool		slotname_given;
@@ -332,7 +332,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	 */
 	parse_subscription_options(stmt->options, &connect, &enabled_given,
 							   &enabled, &create_slot, &slotname_given,
-							   &slotname, &copy_data, &synchronous_commit,
+							   &slotname, &copy_data, &synchr_commit,
 							   NULL);
 
 	/*
@@ -375,8 +375,8 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 		slotname = stmt->subname;
 
 	/* The default for synchronous_commit of subscriptions is off. */
-	if (synchronous_commit == NULL)
-		synchronous_commit = "off";
+	if (synchr_commit == NULL)
+		synchr_commit = "off";
 
 	conninfo = stmt->conninfo;
 	publications = stmt->publication;
@@ -407,7 +407,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	else
 		nulls[Anum_pg_subscription_subslotname - 1] = true;
 	values[Anum_pg_subscription_subsynccommit - 1] =
-		CStringGetTextDatum(synchronous_commit);
+		CStringGetTextDatum(synchr_commit);
 	values[Anum_pg_subscription_subpublications - 1] =
 		publicationListToArray(publications);
 
@@ -668,11 +668,11 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
 			{
 				char	   *slotname;
 				bool		slotname_given;
-				char	   *synchronous_commit;
+				char	   *synchr_commit;
 
 				parse_subscription_options(stmt->options, NULL, NULL, NULL,
 										   NULL, &slotname_given, &slotname,
-										   NULL, &synchronous_commit, NULL);
+										   NULL, &synchr_commit, NULL);
 
 				if (slotname_given)
 				{
@@ -690,10 +690,10 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
 					replaces[Anum_pg_subscription_subslotname - 1] = true;
 				}
 
-				if (synchronous_commit)
+				if (synchr_commit)
 				{
 					values[Anum_pg_subscription_subsynccommit - 1] =
-						CStringGetTextDatum(synchronous_commit);
+						CStringGetTextDatum(synchr_commit);
 					replaces[Anum_pg_subscription_subsynccommit - 1] = true;
 				}
 
unshadow.wal_segment_size.patch.1text/plain; charset=UTF-8; name=unshadow.wal_segment_size.patch.1Download
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 67418b05f1..bc8156fcd6 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -70,7 +70,7 @@ report_invalid_record(XLogReaderState *state, const char *fmt,...)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wallog_segment_size, const char *waldir,
 				   XLogPageReadCB pagereadfunc, void *private_data)
 {
 	XLogReaderState *state;
@@ -99,7 +99,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, wallog_segment_size,
 					   waldir);
 
 	state->read_page = pagereadfunc;
diff --git a/src/include/access/xlogreader.h b/src/include/access/xlogreader.h
index 0193611b7f..d8991d1a79 100644
--- a/src/include/access/xlogreader.h
+++ b/src/include/access/xlogreader.h
@@ -209,7 +209,7 @@ struct XLogReaderState
 };
 
 /* Get a new XLogReader */
-extern XLogReaderState *XLogReaderAllocate(int wal_segment_size,
+extern XLogReaderState *XLogReaderAllocate(int wallog_segment_size,
 										   const char *waldir,
 										   XLogPageReadCB pagereadfunc,
 										   void *private_data);
unshadow.wrconn.patch.1text/plain; charset=UTF-8; name=unshadow.wrconn.patch.1Download
diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c
index 681d208f81..61ed59d4f1 100644
--- a/src/backend/commands/subscriptioncmds.c
+++ b/src/backend/commands/subscriptioncmds.c
@@ -44,7 +44,7 @@
 #include "utils/memutils.h"
 #include "utils/syscache.h"
 
-static List *fetch_table_list(WalReceiverConn *wrconn, List *publications);
+static List *fetch_table_list(WalReceiverConn *walrconn, List *publications);
 
 /*
  * Common option parsing function for CREATE and ALTER SUBSCRIPTION commands.
@@ -430,14 +430,14 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	{
 		XLogRecPtr	lsn;
 		char	   *err;
-		WalReceiverConn *wrconn;
+		WalReceiverConn *walrconn;
 		List	   *tables;
 		ListCell   *lc;
 		char		table_state;
 
 		/* Try to connect to the publisher. */
-		wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
-		if (!wrconn)
+		walrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
+		if (!walrconn)
 			ereport(ERROR,
 					(errmsg("could not connect to the publisher: %s", err)));
 
@@ -453,7 +453,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 			 * Get the table list from publisher and build local table status
 			 * info.
 			 */
-			tables = fetch_table_list(wrconn, publications);
+			tables = fetch_table_list(walrconn, publications);
 			foreach(lc, tables)
 			{
 				RangeVar   *rv = (RangeVar *) lfirst(lc);
@@ -478,7 +478,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 			{
 				Assert(slotname);
 
-				walrcv_create_slot(wrconn, slotname, false,
+				walrcv_create_slot(walrconn, slotname, false,
 								   CRS_NOEXPORT_SNAPSHOT, &lsn);
 				ereport(NOTICE,
 						(errmsg("created replication slot \"%s\" on publisher",
@@ -487,7 +487,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 		}
 		PG_FINALLY();
 		{
-			walrcv_disconnect(wrconn);
+			walrcv_disconnect(walrconn);
 		}
 		PG_END_TRY();
 	}
@@ -835,7 +835,7 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	char		originname[NAMEDATALEN];
 	char	   *err = NULL;
 	RepOriginId originid;
-	WalReceiverConn *wrconn = NULL;
+	WalReceiverConn *walrconn = NULL;
 	StringInfoData cmd;
 	Form_pg_subscription form;
 
@@ -982,8 +982,8 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	initStringInfo(&cmd);
 	appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
 
-	wrconn = walrcv_connect(conninfo, true, subname, &err);
-	if (wrconn == NULL)
+	walrconn = walrcv_connect(conninfo, true, subname, &err);
+	if (walrconn == NULL)
 		ereport(ERROR,
 				(errmsg("could not connect to publisher when attempting to "
 						"drop the replication slot \"%s\"", slotname),
@@ -996,7 +996,7 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	{
 		WalRcvExecResult *res;
 
-		res = walrcv_exec(wrconn, cmd.data, 0, NULL);
+		res = walrcv_exec(walrconn, cmd.data, 0, NULL);
 
 		if (res->status != WALRCV_OK_COMMAND)
 			ereport(ERROR,
@@ -1012,7 +1012,7 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	}
 	PG_FINALLY();
 	{
-		walrcv_disconnect(wrconn);
+		walrcv_disconnect(walrconn);
 	}
 	PG_END_TRY();
 
@@ -1124,7 +1124,7 @@ AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
  * publisher connection.
  */
 static List *
-fetch_table_list(WalReceiverConn *wrconn, List *publications)
+fetch_table_list(WalReceiverConn *walrconn, List *publications)
 {
 	WalRcvExecResult *res;
 	StringInfoData cmd;
@@ -1154,7 +1154,7 @@ fetch_table_list(WalReceiverConn *wrconn, List *publications)
 	}
 	appendStringInfoChar(&cmd, ')');
 
-	res = walrcv_exec(wrconn, cmd.data, 2, tableRow);
+	res = walrcv_exec(walrconn, cmd.data, 2, tableRow);
 	pfree(cmd.data);
 
 	if (res->status != WALRCV_OK_TUPLES)
#20Mark Dilger
hornschnorter@gmail.com
In reply to: Mark Dilger (#19)
Re: [Proposal] Level4 Warnings show many shadow vars

On 12/8/19 8:50 PM, Mark Dilger wrote:

On 12/8/19 10:25 AM, Mark Dilger wrote:

I was
still expecting multiple patches, perhaps named along the
lines of:

�� unshadow.RedoRecPtr.patch.1
�� unshadow.wal_segment_size.patch.1
�� unshadow.synchronous_commit.patch.1
�� unshadow.wrconn.patch.1
�� unshadow.progname.patch.1
�� unshadow.am_syslogger.patch.1
�� unshadow.days.patch.1
�� unshadow.months.patch.1

etc.� I'm uncomfortable giving you negative feedback of this
sort, since I think you are working hard to improve postgres
and I really appreciate it, so later tonight I'll try to come
back, split your patch for you as described, add an entry to
the commitfest if you haven't already, and mark myself as a
reviewer.

To start off, I've taken just six of the 22 or so variables
that you renamed and created patches for them.� I'm not
endorsing these in any way.� I chose these mostly based on
which ones showed up first in your patch file, with one
exception.

I stopped when I got to 'progname' => 'prog_name' as the
whole exercise was getting too absurd even for me.� That
clearly looks like one where the structure of the code
needs to be reconsidered, rather than just renaming stuff.

I'll create the commitfest entry based on this email once
this has been sent.

Patches attached.

The commitfest item now exists at

https://commitfest.postgresql.org/26/2371/

--
Mark Dilger

#21Michael Paquier
michael@paquier.xyz
In reply to: Tom Lane (#15)
1 attachment(s)
Re: [Proposal] Level4 Warnings show many shadow vars

On Sun, Dec 08, 2019 at 02:14:03PM -0500, Tom Lane wrote:

That is, these arguments *used* to be a different LSN pointer, and that
commit changed them to be mostly equal to RedoRecPtr, and made what
seems like a not very well-advised renaming to go with that.

Indeed. That part was ill-thought.

So it might make sense to remove the parameter from this
function, too, and replace it with a flag parameter named
something like "is_valid", or perhaps split the function
into two functions, one for valid and one for invalid.

Don't think I buy that. The fact that these arguments were until recently
different from RedoRecPtr suggests that they might someday be different
again, whereupon we'd have to laboriously revert such a parameter redesign.
I think I'd just go for names that don't have a hard implication that
the parameter values are the same as any particular global variable.

Yeah, those APIs may have a slightly different meaning in the future,
so I agree that it makes the most sense to rename the variables of the
functions from RedoRecPtr to lastRedoPtr to outline the fact that we
are referring to the redo LSN of the last checkpoint. Attached is a
patch for that. I'd rather back-patch that to avoid any conflicts
when working on bug fixes for stable branches. Thoughts?
--
Michael

Attachments:

xlog-fix-varnames.patchtext/x-diff; charset=us-asciiDownload
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 6bc1a6b46d..8e1f8612df 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -892,8 +892,8 @@ static int	emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
 static void XLogFileClose(void);
 static void PreallocXlogFiles(XLogRecPtr endptr);
 static void RemoveTempXlogFiles(void);
-static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
-static void RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
+static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastRedoPtr, XLogRecPtr endptr);
+static void RemoveXlogFile(const char *segname, XLogRecPtr lastRedoPtr, XLogRecPtr endptr);
 static void UpdateLastRemovedPtr(char *filename);
 static void ValidateXLOGDirectoryStructure(void);
 static void CleanupBackupHistory(void);
@@ -2299,7 +2299,7 @@ assign_checkpoint_completion_target(double newval, void *extra)
  * XLOG segments? Returns the highest segment that should be preallocated.
  */
 static XLogSegNo
-XLOGfileslop(XLogRecPtr RedoRecPtr)
+XLOGfileslop(XLogRecPtr lastRedoPtr)
 {
 	XLogSegNo	minSegNo;
 	XLogSegNo	maxSegNo;
@@ -2311,9 +2311,9 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	 * correspond to. Always recycle enough segments to meet the minimum, and
 	 * remove enough segments to stay below the maximum.
 	 */
-	minSegNo = RedoRecPtr / wal_segment_size +
+	minSegNo = lastRedoPtr / wal_segment_size +
 		ConvertToXSegs(min_wal_size_mb, wal_segment_size) - 1;
-	maxSegNo = RedoRecPtr / wal_segment_size +
+	maxSegNo = lastRedoPtr / wal_segment_size +
 		ConvertToXSegs(max_wal_size_mb, wal_segment_size) - 1;
 
 	/*
@@ -2328,7 +2328,7 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	/* add 10% for good measure. */
 	distance *= 1.10;
 
-	recycleSegNo = (XLogSegNo) ceil(((double) RedoRecPtr + distance) /
+	recycleSegNo = (XLogSegNo) ceil(((double) lastRedoPtr + distance) /
 									wal_segment_size);
 
 	if (recycleSegNo < minSegNo)
@@ -3949,12 +3949,12 @@ RemoveTempXlogFiles(void)
 /*
  * Recycle or remove all log files older or equal to passed segno.
  *
- * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * endptr is current (or recent) end of xlog, and lastRedoPtr is the
  * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
  */
 static void
-RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastRedoPtr, XLogRecPtr endptr)
 {
 	DIR		   *xldir;
 	struct dirent *xlde;
@@ -3997,7 +3997,7 @@ RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 				/* Update the last removed location in shared memory first */
 				UpdateLastRemovedPtr(xlde->d_name);
 
-				RemoveXlogFile(xlde->d_name, RedoRecPtr, endptr);
+				RemoveXlogFile(xlde->d_name, lastRedoPtr, endptr);
 			}
 		}
 	}
@@ -4071,14 +4071,14 @@ RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
 /*
  * Recycle or remove a log file that's no longer needed.
  *
- * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * endptr is current (or recent) end of xlog, and lastRedoPtr is the
  * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
- * If RedoRecPtr is not known, pass invalid, and the function will recycle,
+ * If lastRedoPtr is not known, pass invalid, and the function will recycle,
  * somewhat arbitrarily, 10 future segments.
  */
 static void
-RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveXlogFile(const char *segname, XLogRecPtr lastRedoPtr, XLogRecPtr endptr)
 {
 	char		path[MAXPGPATH];
 #ifdef WIN32
@@ -4094,10 +4094,10 @@ RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 		 * Initialize info about where to try to recycle to.
 		 */
 		XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
-		if (RedoRecPtr == InvalidXLogRecPtr)
+		if (lastRedoPtr == InvalidXLogRecPtr)
 			recycleSegNo = endlogSegNo + 10;
 		else
-			recycleSegNo = XLOGfileslop(RedoRecPtr);
+			recycleSegNo = XLOGfileslop(lastRedoPtr);
 	}
 	else
 		recycleSegNo = 0;		/* keep compiler quiet */
#22Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Kyotaro Horiguchi (#18)
1 attachment(s)
RE: [Proposal] Level4 Warnings show many shadow vars

De: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Enviado: segunda-feira, 9 de dezembro de 2019 03:40

The file-scoped variable is needed to be process-persistent in any
way. If we inhibit them, the upper-modules need to create the
persistent area instead, for example, by calling XLogInitGlobals() or
such, which makes things messier. Globality doens't necessarily mean
evil and there're reasons for -Wall doesn't warn the case. I believe
we, and especially committers are not who should be kept away from
knives for the reason that knives generally have a possibility to
injure someone.

Which harms the reusability of the code anyway.

I might be too accustomed there, but the functions that define
overriding locals don't modify the local variables and only the
functions that don't override the globals modifies the glboals. I see
no significant confusion here. By the way changes like "conf_file" ->
"conffile" seems really useless as a fix patch.

Well i was trying to fix everything.

As Robert said, they are harmless as far as we notice. Actual bugs
caused by variable overriding would be welcomed to fix. I don't
believe "lead to better performance and reduction (of code?)" without
an evidence since modern compilers I think are not so stupid. Even if
any, performance change in such extent doesn't support the proposal to
remove variable overrides that way.

It's clear to me now that unless "the thing" is clearly a bug, don't touch it.
I love C, so for me it's very hard to resist getting stupid things like:
foo ()
{
int i, n;
for (i-0; i < n; i ++);
{
int i;
for (i=0; i < n; i ++);
}
{
int i;
for (i=0; i < n; i ++);
}
return;

I don't know how you can do it.

Of course, there are cases and cases, let's look at the example of multixact.c
diff --git a / src / backend / access / transam / multixact.c b / src / backend / access / transam / multixact.c
index 7b2448e05b..6364014fb3 100644
--- a / src / backend / access / transam / multixact.c
+++ b / src / backend / access / transam / multixact.c
@@ -1589.10 +1589.10 @@ mXactCachePut (MultiXactId multi, int nmembers, MultiXactMember * members)
 qsort (entry-> members, nmembers, sizeof (MultiXactMember), mxactMemberComparator);
 dlist_push_head (& MXactCache, & entry-> node);
+ pfree (entry); // <- is it really necessary?
 if (MXactCacheMembers ++> = MAX_CACHE_ENTRIES)
 {
 dlist_node * node;
- mXactCacheEnt * entry;

node = dlist_tail_node (& MXactCache);
dlist_delete (node);

I still can't decide if it's a bug or not.

If it is a bug the correct function here is pfree or what is the equivalent function to free memory?

Anyway I strongly object to the name 'pRedoRecPtr', which suggests as
if it is a C-pointer to some variable. (And I believe we use Hungarian
notation only if we don't have a better way...) LatestRedoRecPtr
looks better to me.

I don't have enough information to decide if the lastest is the proper name, so I tried to change the nomenclature as little as possible.

I'll submit a patch sample, which depending on the answer, will give me if it's worth it or not, keep working on it.

regards,
Ranier Vilela

Attachments:

unshadow_locals_v0.patchtext/x-patch; name=unshadow_locals_v0.patchDownload
diff --git a/src/backend/access/common/reloptions.c b/src/backend/access/common/reloptions.c
index 48377ace24..1bad56991e 100644
--- a/src/backend/access/common/reloptions.c
+++ b/src/backend/access/common/reloptions.c
@@ -1198,7 +1198,6 @@ parseRelOptions(Datum options, bool validate, relopt_kind kind,
 		{
 			char	   *text_str = VARDATA(optiondatums[i]);
 			int			text_len = VARSIZE(optiondatums[i]) - VARHDRSZ;
-			int			j;
 
 			/* Search for a match in reloptions */
 			for (j = 0; j < numoptions; j++)
diff --git a/src/backend/access/gin/ginget.c b/src/backend/access/gin/ginget.c
index b18ae2b3ed..78291fe696 100644
--- a/src/backend/access/gin/ginget.c
+++ b/src/backend/access/gin/ginget.c
@@ -392,7 +392,6 @@ restartScanEntry:
 		{
 			BlockNumber rootPostingTree = GinGetPostingTree(itup);
 			GinBtreeStack *stack;
-			Page		page;
 			ItemPointerData minItem;
 
 			/*
diff --git a/src/backend/access/gist/gist.c b/src/backend/access/gist/gist.c
index 3800f58ce7..43204b61f7 100644
--- a/src/backend/access/gist/gist.c
+++ b/src/backend/access/gist/gist.c
@@ -366,7 +366,6 @@ gistplacetopage(Relation rel, Size freespace, GISTSTATE *giststate,
 		{
 			IndexTuple *downlinks;
 			int			ndownlinks = 0;
-			int			i;
 
 			rootpg.buffer = buffer;
 			rootpg.page = PageGetTempPageCopySpecial(BufferGetPage(rootpg.buffer));
diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index 739846a257..8b721f60cd 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -763,7 +763,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 		i = 0;
 		foreach(lc, splitinfo)
 		{
-			GISTPageSplitInfo *splitinfo = lfirst(lc);
+			GISTPageSplitInfo *split = lfirst(lc);
 
 			/*
 			 * Remember the parent of each new child page in our parent map.
@@ -774,7 +774,7 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 */
 			if (level > 0)
 				gistMemorizeParent(buildstate,
-								   BufferGetBlockNumber(splitinfo->buf),
+								   BufferGetBlockNumber(split->buf),
 								   BufferGetBlockNumber(parentBuffer));
 
 			/*
@@ -784,14 +784,14 @@ gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
 			 * harm).
 			 */
 			if (level > 1)
-				gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
+				gistMemorizeAllDownlinks(buildstate, split->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(split->buf);
+			downlinks[i++] = split->downlink;
 		}
 
 		/* Insert them into parent. */
diff --git a/src/backend/access/gist/gistbuildbuffers.c b/src/backend/access/gist/gistbuildbuffers.c
index 38f786848d..c3990a5fff 100644
--- a/src/backend/access/gist/gistbuildbuffers.c
+++ b/src/backend/access/gist/gistbuildbuffers.c
@@ -635,8 +635,7 @@ gistRelocateBuildBuffersOnSplit(GISTBuildBuffers *gfbb, GISTSTATE *giststate,
 	while (gistPopItupFromNodeBuffer(gfbb, &oldBuf, &itup))
 	{
 		float		best_penalty[INDEX_MAX_KEYS];
-		int			i,
-					which;
+		int			which;
 		IndexTuple	newtup;
 		RelocationBufferInfo *targetBufferInfo;
 
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index c1d248ae5e..98735ab719 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -240,7 +240,6 @@ hash_xlog_add_ovfl_page(XLogReaderState *record)
 		{
 			Page		mappage = (Page) BufferGetPage(mapbuffer);
 			uint32	   *freep = NULL;
-			char	   *data;
 			uint32	   *bitmap_page_bit;
 
 			freep = HashPageGetBitmap(mappage);
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 0128bb34ef..6a101f542b 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -5961,7 +5961,7 @@ FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
 		 */
 		if (ISUPDATE_from_mxstatus(members[i].status))
 		{
-			TransactionId xid = members[i].xid;
+			xid = members[i].xid;
 
 			Assert(TransactionIdIsValid(xid));
 			if (TransactionIdPrecedes(xid, relfrozenxid))
diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index a3c4a1df3b..f6aae66457 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -517,7 +517,7 @@ lazy_scan_heap(Relation onerel, VacuumParams *params, LVRelStats *vacrelstats,
 	BlockNumber next_unskippable_block;
 	bool		skipping_blocks;
 	xl_heap_freeze_tuple *frozen;
-	StringInfoData buf;
+	StringInfoData str;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -918,10 +918,10 @@ lazy_scan_heap(Relation onerel, VacuumParams *params, LVRelStats *vacrelstats,
 
 				if (GetRecordedFreeSpace(onerel, blkno) == 0)
 				{
-					Size		freespace;
+					Size		freesize;
 
-					freespace = BufferGetPageSize(buf) - SizeOfPageHeaderData;
-					RecordPageWithFreeSpace(onerel, blkno, freespace);
+					freesize = BufferGetPageSize(buf) - SizeOfPageHeaderData;
+					RecordPageWithFreeSpace(onerel, blkno, freesize);
 				}
 			}
 			continue;
@@ -1481,33 +1481,33 @@ lazy_scan_heap(Relation onerel, VacuumParams *params, LVRelStats *vacrelstats,
 	 * This is pretty messy, but we split it up so that we can skip emitting
 	 * individual parts of the message when not applicable.
 	 */
-	initStringInfo(&buf);
-	appendStringInfo(&buf,
+	initStringInfo(&str);
+	appendStringInfo(&str,
 					 _("%.0f dead row versions cannot be removed yet, oldest xmin: %u\n"),
 					 nkeep, OldestXmin);
-	appendStringInfo(&buf, _("There were %.0f unused item identifiers.\n"),
+	appendStringInfo(&str, _("There were %.0f unused item identifiers.\n"),
 					 nunused);
-	appendStringInfo(&buf, ngettext("Skipped %u page due to buffer pins, ",
+	appendStringInfo(&str, ngettext("Skipped %u page due to buffer pins, ",
 									"Skipped %u pages due to buffer pins, ",
 									vacrelstats->pinskipped_pages),
 					 vacrelstats->pinskipped_pages);
-	appendStringInfo(&buf, ngettext("%u frozen page.\n",
+	appendStringInfo(&str, ngettext("%u frozen page.\n",
 									"%u frozen pages.\n",
 									vacrelstats->frozenskipped_pages),
 					 vacrelstats->frozenskipped_pages);
-	appendStringInfo(&buf, ngettext("%u page is entirely empty.\n",
+	appendStringInfo(&str, ngettext("%u page is entirely empty.\n",
 									"%u pages are entirely empty.\n",
 									empty_pages),
 					 empty_pages);
-	appendStringInfo(&buf, _("%s."), pg_rusage_show(&ru0));
+	appendStringInfo(&str, _("%s."), pg_rusage_show(&ru0));
 
 	ereport(elevel,
 			(errmsg("\"%s\": found %.0f removable, %.0f nonremovable row versions in %u out of %u pages",
 					RelationGetRelationName(onerel),
 					tups_vacuumed, num_tuples,
 					vacrelstats->scanned_pages, nblocks),
-			 errdetail_internal("%s", buf.data)));
-	pfree(buf.data);
+			 errdetail_internal("%s", str.data)));
+	pfree(str.data);
 }
 
 
diff --git a/src/backend/access/spgist/spgdoinsert.c b/src/backend/access/spgist/spgdoinsert.c
index c34c44cd8b..03f6aa689c 100644
--- a/src/backend/access/spgist/spgdoinsert.c
+++ b/src/backend/access/spgist/spgdoinsert.c
@@ -420,8 +420,6 @@ moveLeafs(Relation index, SpGistState *state,
 	i = current->offnum;
 	while (i != InvalidOffsetNumber)
 	{
-		SpGistLeafTuple it;
-
 		Assert(i >= FirstOffsetNumber &&
 			   i <= PageGetMaxOffsetNumber(current->page));
 		it = (SpGistLeafTuple) PageGetItem(current->page,
diff --git a/src/backend/access/transam/clog.c b/src/backend/access/transam/clog.c
index 7f7eb21b4f..6446748a84 100644
--- a/src/backend/access/transam/clog.c
+++ b/src/backend/access/transam/clog.c
@@ -422,6 +422,7 @@ TransactionGroupUpdateXidStatus(TransactionId xid, XidStatus status,
 {
 	volatile PROC_HDR *procglobal = ProcGlobal;
 	PGPROC	   *proc = MyProc;
+        PGXACT	   *pgxact;
 	uint32		nextidx;
 	uint32		wakeidx;
 
@@ -516,8 +517,8 @@ TransactionGroupUpdateXidStatus(TransactionId xid, XidStatus status,
 	/* Walk the list and update the status of all XIDs. */
 	while (nextidx != INVALID_PGPROCNO)
 	{
-		PGPROC	   *proc = &ProcGlobal->allProcs[nextidx];
-		PGXACT	   *pgxact = &ProcGlobal->allPgXact[nextidx];
+		proc = &ProcGlobal->allProcs[nextidx];
+		pgxact = &ProcGlobal->allPgXact[nextidx];
 
 		/*
 		 * Overflowed transactions should not use group XID status update
@@ -546,7 +547,7 @@ TransactionGroupUpdateXidStatus(TransactionId xid, XidStatus status,
 	 */
 	while (wakeidx != INVALID_PGPROCNO)
 	{
-		PGPROC	   *proc = &ProcGlobal->allProcs[wakeidx];
+		proc = &ProcGlobal->allProcs[wakeidx];
 
 		wakeidx = pg_atomic_read_u32(&proc->clogGroupNext);
 		pg_atomic_write_u32(&proc->clogGroupNext, INVALID_PGPROCNO);
diff --git a/src/backend/access/transam/multixact.c b/src/backend/access/transam/multixact.c
index 7b2448e05b..6364014fb3 100644
--- a/src/backend/access/transam/multixact.c
+++ b/src/backend/access/transam/multixact.c
@@ -1589,10 +1589,10 @@ mXactCachePut(MultiXactId multi, int nmembers, MultiXactMember *members)
 	qsort(entry->members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
 
 	dlist_push_head(&MXactCache, &entry->node);
+        pfree(entry);
 	if (MXactCacheMembers++ >= MAX_CACHE_ENTRIES)
 	{
 		dlist_node *node;
-		mXactCacheEnt *entry;
 
 		node = dlist_tail_node(&MXactCache);
 		dlist_delete(node);
diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index 8404904710..98f6bc6954 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -1878,19 +1878,18 @@ heap_drop_with_catalog(Oid relid)
 	 */
 	if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
 	{
-		Relation	rel;
-		HeapTuple	tuple;
+		Relation	reltp;
 
-		rel = table_open(ForeignTableRelationId, RowExclusiveLock);
+		reltp = table_open(ForeignTableRelationId, RowExclusiveLock);
 
 		tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
 		if (!HeapTupleIsValid(tuple))
 			elog(ERROR, "cache lookup failed for foreign table %u", relid);
 
-		CatalogTupleDelete(rel, &tuple->t_self);
+		CatalogTupleDelete(reltp, &tuple->t_self);
 
 		ReleaseSysCache(tuple);
-		table_close(rel, RowExclusiveLock);
+		table_close(reltp, RowExclusiveLock);
 	}
 
 	/*
diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c
index e251f5a9fd..9c997c1b29 100644
--- a/src/backend/catalog/namespace.c
+++ b/src/backend/catalog/namespace.c
@@ -1103,7 +1103,6 @@ FuncnameGetCandidates(List *names, int nargs, List *argnames,
 		{
 			/* Re-order the argument types into call's logical order */
 			Oid		   *proargtypes = procform->proargtypes.values;
-			int			i;
 
 			for (i = 0; i < pronargs; i++)
 				newResult->args[i] = proargtypes[argnumbers[i]];
@@ -1116,8 +1115,6 @@ FuncnameGetCandidates(List *names, int nargs, List *argnames,
 		}
 		if (variadic)
 		{
-			int			i;
-
 			newResult->nvargs = effective_nargs - pronargs + 1;
 			/* Expand variadic argument into N copies of element type */
 			for (i = pronargs - 1; i < effective_nargs; i++)
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index ae3002bb42..f357d8fa8d 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -2000,7 +2000,7 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	ObjectAddress addr;
 	TupleDesc	tupdesc;
 	Datum		values[3];
-	bool		nulls[3];
+	bool		nullsp[3];
 	HeapTuple	htup;
 	Relation	relation;
 
@@ -2254,11 +2254,11 @@ pg_get_object_address(PG_FUNCTION_ARGS)
 	values[0] = ObjectIdGetDatum(addr.classId);
 	values[1] = ObjectIdGetDatum(addr.objectId);
 	values[2] = Int32GetDatum(addr.objectSubId);
-	nulls[0] = false;
-	nulls[1] = false;
-	nulls[2] = false;
+	nullsp[0] = false;
+	nullsp[1] = false;
+	nullsp[2] = false;
 
-	htup = heap_form_tuple(tupdesc, values, nulls);
+	htup = heap_form_tuple(tupdesc, values, nullsp);
 
 	PG_RETURN_DATUM(HeapTupleGetDatum(htup));
 }
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index 94411b5008..a65286330d 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -115,7 +115,6 @@ compute_return_type(TypeName *returnType, Oid languageOid,
 	{
 		char	   *typnam = TypeNameToString(returnType);
 		Oid			namespaceId;
-		AclResult	aclresult;
 		char	   *typname;
 		ObjectAddress address;
 
@@ -1000,8 +999,6 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
 	if (languageStruct->lanpltrusted)
 	{
 		/* if trusted language, need USAGE privilege */
-		AclResult	aclresult;
-
 		aclresult = pg_language_aclcheck(languageOid, GetUserId(), ACL_USAGE);
 		if (aclresult != ACLCHECK_OK)
 			aclcheck_error(aclresult, OBJECT_LANGUAGE,
diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c
index 374e2d0efe..ea6361ae96 100644
--- a/src/backend/commands/indexcmds.c
+++ b/src/backend/commands/indexcmds.c
@@ -813,7 +813,6 @@ DefineIndex(Oid relationId,
 	if (partitioned && (stmt->unique || stmt->primary))
 	{
 		PartitionKey key = rel->rd_partkey;
-		int			i;
 
 		/*
 		 * A partitioned table can have unique indexes, as long as all the
diff --git a/src/backend/commands/publicationcmds.c b/src/backend/commands/publicationcmds.c
index fbf11c86aa..5b8c6bf0ba 100644
--- a/src/backend/commands/publicationcmds.c
+++ b/src/backend/commands/publicationcmds.c
@@ -60,7 +60,7 @@ parse_publication_options(List *options,
 						  bool *publish_delete,
 						  bool *publish_truncate)
 {
-	ListCell   *lc;
+	ListCell   *l;
 
 	*publish_given = false;
 
@@ -71,9 +71,9 @@ parse_publication_options(List *options,
 	*publish_truncate = true;
 
 	/* Parse options */
-	foreach(lc, options)
+	foreach(l, options)
 	{
-		DefElem    *defel = (DefElem *) lfirst(lc);
+		DefElem    *defel = (DefElem *) lfirst(l);
 
 		if (strcmp(defel->defname, "publish") == 0)
 		{
#23Daniel Gustafsson
daniel@yesql.se
In reply to: Ranier Vilela (#22)
Re: [Proposal] Level4 Warnings show many shadow vars

On 9 Dec 2019, at 12:02, Ranier Vilela <ranier_gyn@hotmail.com> wrote:

diff --git a / src / backend / access / transam / multixact.c b / src / backend / access / transam / multixact.c
index 7b2448e05b..6364014fb3 100644
--- a / src / backend / access / transam / multixact.c
+++ b / src / backend / access / transam / multixact.c
@@ -1589.10 +1589.10 @@ mXactCachePut (MultiXactId multi, int nmembers, MultiXactMember * members)
qsort (entry-> members, nmembers, sizeof (MultiXactMember), mxactMemberComparator);

dlist_push_head (& MXactCache, & entry-> node);
+ pfree (entry); // <- is it really necessary?

Pushing an object to a dlist doesn't copy the object, so freeing entry here
would cause a dangling pointer on the list unless I'm misreading. Note that
entry is allocated in a specific context to ensure it has the correct lifespan.
The README in backend/utils/mmgr is a good primer on how memory contexts work
in postgres.

As a matter of fact, the pfree call in the cache purge if block isn't really
required either since the entire cache will be freed at the end of the
transaction.

if (MXactCacheMembers ++> = MAX_CACHE_ENTRIES)
{
dlist_node * node;
- mXactCacheEnt * entry;

I can agree that reusing the name entry here isn't ideal, as it's so close, but
removing it is worse. I'd prefer to rename it purged, or purged_entry or
something along those lines.

cheers ./daniel

#24Robert Haas
robertmhaas@gmail.com
In reply to: Tom Lane (#14)
Re: [Proposal] Level4 Warnings show many shadow vars

On Sun, Dec 8, 2019 at 1:52 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:

Ranier Vilela <ranier_gyn@hotmail.com> writes:

This is the first part of the variable shadow fixes.
Basically it consists of renaming the variables in collision with the global ones, with the minimum change in the semantics.

I don't think I'm actually on board with the goal here.

I don't know what to do about the RedoRecPtr mess, but surely
subscriptioncmds.c's use of synchronous_commit as a char * when it's
already exists as a global variable of type int is not good practice.
We've been known to do things like reference globals from within macro
definitions, and while static inlining is likely to make that practice
less common in the future, we've got plenty of existing instances,
including one that uses that exact variable name (SyncRepRequested()).

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

#25Tom Lane
tgl@sss.pgh.pa.us
In reply to: Robert Haas (#24)
Re: [Proposal] Level4 Warnings show many shadow vars

Robert Haas <robertmhaas@gmail.com> writes:

On Sun, Dec 8, 2019 at 1:52 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:

I don't think I'm actually on board with the goal here.

I don't know what to do about the RedoRecPtr mess, but surely
subscriptioncmds.c's use of synchronous_commit as a char * when it's
already exists as a global variable of type int is not good practice.

Well, again, this is a case-by-case question. I tend to agree that
changing that usage in subscriptioncmds.c might be a good idea.
That doesn't mean I need to be on board with wholesale removal
of shadowing warnings.

regards, tom lane

#26Robert Haas
robertmhaas@gmail.com
In reply to: Tom Lane (#25)
Re: [Proposal] Level4 Warnings show many shadow vars

On Mon, Dec 9, 2019 at 10:23 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:

Robert Haas <robertmhaas@gmail.com> writes:

On Sun, Dec 8, 2019 at 1:52 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:

I don't think I'm actually on board with the goal here.

I don't know what to do about the RedoRecPtr mess, but surely
subscriptioncmds.c's use of synchronous_commit as a char * when it's
already exists as a global variable of type int is not good practice.

Well, again, this is a case-by-case question. I tend to agree that
changing that usage in subscriptioncmds.c might be a good idea.
That doesn't mean I need to be on board with wholesale removal
of shadowing warnings.

I agree that those things are different, but I'm not sure I understand
the nuances of your view. I think my view is that if something in our
code is shadowing something else in our code, that's probably
something we ought to look at fixing. If you disagree, I'd be curious
to know why; I suspect that, as in this case, such cases are just
creating a risk of confusion without any real benefit. To me, the grey
area is in conflicts between stuff in our code and stuff in system
header files. I'm not sure I'd want to try to have precisely 0
conflicts with every crazy decision by every OS / libc maintainer out
there, and I suspect on that point at least we are in agreement.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

#27Tom Lane
tgl@sss.pgh.pa.us
In reply to: Robert Haas (#26)
Re: [Proposal] Level4 Warnings show many shadow vars

Robert Haas <robertmhaas@gmail.com> writes:

On Mon, Dec 9, 2019 at 10:23 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:

Well, again, this is a case-by-case question. I tend to agree that
changing that usage in subscriptioncmds.c might be a good idea.
That doesn't mean I need to be on board with wholesale removal
of shadowing warnings.

I agree that those things are different, but I'm not sure I understand
the nuances of your view. I think my view is that if something in our
code is shadowing something else in our code, that's probably
something we ought to look at fixing. If you disagree, I'd be curious
to know why; I suspect that, as in this case, such cases are just
creating a risk of confusion without any real benefit.

I think it depends a lot on the particular identifiers in use. You
mentioned examples like "i" and "lc", and I'd add other obviously
nonce variable names like "oldcxt". I'm not particularly concerned
about shadowing arising from somebody writing a five-line loop using
a local "i" inside a much larger loop also using "i" --- yeah, in
theory there could be an issue, but in practice there isn't. Being
picky about that just adds difficulty when writing/reviewing a patch
that adds such a five-line loop.

Your point about risking macro breakage from shadowing of global
variable names is a good one, but again I don't think it holds up
as an argument that we have to get rid of all shadowing.

To me, the grey
area is in conflicts between stuff in our code and stuff in system
header files. I'm not sure I'd want to try to have precisely 0
conflicts with every crazy decision by every OS / libc maintainer out
there, and I suspect on that point at least we are in agreement.

I believe the relevant C standards (and practice) are that random
names exposed by system headers ought to start with some underscores.
If there's a conflict there, it's a bug in the header and cause
for a bug report to the OS vendor, not us.

Now, if a conflict of that sort exists and is causing a live bug in PG
on a popular OS, then I'd likely be on board with adjusting our code
to dodge the problem. But not with doing so just to silence a
compiler warning.

A final point here is that in practice, we've had way more problems
with conflicts against system headers' definitions of functions,
macros, and typedefs than global variables, which is unsurprising
considering how few of the latter are actually exported by typical
C library APIs. So I'm not sure that there is any big problem to
be solved there in the first place.

The only thing I think is really a substantial bug risk here is your
point about our own macros referencing our own global variables.
We might be better off fixing that in a localized way by establishing
a policy that any such macros should be converted to static inlines.

regards, tom lane

#28Robert Haas
robertmhaas@gmail.com
In reply to: Tom Lane (#27)
Re: [Proposal] Level4 Warnings show many shadow vars

On Mon, Dec 9, 2019 at 11:48 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:

I think it depends a lot on the particular identifiers in use. You
mentioned examples like "i" and "lc", and I'd add other obviously
nonce variable names like "oldcxt". I'm not particularly concerned
about shadowing arising from somebody writing a five-line loop using
a local "i" inside a much larger loop also using "i" --- yeah, in
theory there could be an issue, but in practice there isn't. Being
picky about that just adds difficulty when writing/reviewing a patch
that adds such a five-line loop.

I think I would take the contrary view here. I think reusing the same
variable names in a single function is confusing, and if I noticed it
while reviewing, I would ask for it to be changed. It's not a
five-alarm fire, but it's not good, either.

To me, the grey
area is in conflicts between stuff in our code and stuff in system
header files. I'm not sure I'd want to try to have precisely 0
conflicts with every crazy decision by every OS / libc maintainer out
there, and I suspect on that point at least we are in agreement.

I believe the relevant C standards (and practice) are that random
names exposed by system headers ought to start with some underscores.
If there's a conflict there, it's a bug in the header and cause
for a bug report to the OS vendor, not us.

Sure. I mean we'd have to look at individual cases, but in general I agree.

Now, if a conflict of that sort exists and is causing a live bug in PG
on a popular OS, then I'd likely be on board with adjusting our code
to dodge the problem. But not with doing so just to silence a
compiler warning.

Sounds reasonable.

A final point here is that in practice, we've had way more problems
with conflicts against system headers' definitions of functions,
macros, and typedefs than global variables, which is unsurprising
considering how few of the latter are actually exported by typical
C library APIs. So I'm not sure that there is any big problem to
be solved there in the first place.

The only thing I think is really a substantial bug risk here is your
point about our own macros referencing our own global variables.
We might be better off fixing that in a localized way by establishing
a policy that any such macros should be converted to static inlines.

That would be a lot of work, but it would probably have some side
benefits, like making things more type-safe.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

#29Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Ranier Vilela (#12)
1 attachment(s)
RE: [Proposal] Level4 Warnings show many shadow vars

This the second version of the global unshadow patch.
Taking into consideration made. In case anyone else revises.

regards
Ranier Vilela

Attachments:

shadow_global_v2.patchtext/x-patch; name=shadow_global_v2.patchDownload
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 6bc1a6b46d..83be23d77b 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -892,8 +892,8 @@ static int	emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
 static void XLogFileClose(void);
 static void PreallocXlogFiles(XLogRecPtr endptr);
 static void RemoveTempXlogFiles(void);
-static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
-static void RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
+static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr);
+static void RemoveXlogFile(const char *segname, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr);
 static void UpdateLastRemovedPtr(char *filename);
 static void ValidateXLOGDirectoryStructure(void);
 static void CleanupBackupHistory(void);
@@ -2299,7 +2299,7 @@ assign_checkpoint_completion_target(double newval, void *extra)
  * XLOG segments? Returns the highest segment that should be preallocated.
  */
 static XLogSegNo
-XLOGfileslop(XLogRecPtr RedoRecPtr)
+XLOGfileslop(XLogRecPtr lastRedoRecPtr)
 {
 	XLogSegNo	minSegNo;
 	XLogSegNo	maxSegNo;
@@ -2311,9 +2311,9 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	 * correspond to. Always recycle enough segments to meet the minimum, and
 	 * remove enough segments to stay below the maximum.
 	 */
-	minSegNo = RedoRecPtr / wal_segment_size +
+	minSegNo = lastRedoRecPtr / wal_segment_size +
 		ConvertToXSegs(min_wal_size_mb, wal_segment_size) - 1;
-	maxSegNo = RedoRecPtr / wal_segment_size +
+	maxSegNo = lastRedoRecPtr / wal_segment_size +
 		ConvertToXSegs(max_wal_size_mb, wal_segment_size) - 1;
 
 	/*
@@ -2328,7 +2328,7 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	/* add 10% for good measure. */
 	distance *= 1.10;
 
-	recycleSegNo = (XLogSegNo) ceil(((double) RedoRecPtr + distance) /
+	recycleSegNo = (XLogSegNo) ceil(((double) lastRedoRecPtr + distance) /
 									wal_segment_size);
 
 	if (recycleSegNo < minSegNo)
@@ -3949,12 +3949,12 @@ RemoveTempXlogFiles(void)
 /*
  * Recycle or remove all log files older or equal to passed segno.
  *
- * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * endptr is current (or recent) end of xlog, and lastRedoRecPtr is the
  * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
  */
 static void
-RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr)
 {
 	DIR		   *xldir;
 	struct dirent *xlde;
@@ -3997,7 +3997,7 @@ RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 				/* Update the last removed location in shared memory first */
 				UpdateLastRemovedPtr(xlde->d_name);
 
-				RemoveXlogFile(xlde->d_name, RedoRecPtr, endptr);
+				RemoveXlogFile(xlde->d_name, lastRedoRecPtr, endptr);
 			}
 		}
 	}
@@ -4071,14 +4071,14 @@ RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
 /*
  * Recycle or remove a log file that's no longer needed.
  *
- * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * endptr is current (or recent) end of xlog, and lastRedoRecPtr is the
  * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
- * If RedoRecPtr is not known, pass invalid, and the function will recycle,
+ * If lastRedoRecPtr is not known, pass invalid, and the function will recycle,
  * somewhat arbitrarily, 10 future segments.
  */
 static void
-RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveXlogFile(const char *segname, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr)
 {
 	char		path[MAXPGPATH];
 #ifdef WIN32
@@ -4094,10 +4094,10 @@ RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 		 * Initialize info about where to try to recycle to.
 		 */
 		XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
-		if (RedoRecPtr == InvalidXLogRecPtr)
+		if (lastRedoRecPtr == InvalidXLogRecPtr)
 			recycleSegNo = endlogSegNo + 10;
 		else
-			recycleSegNo = XLOGfileslop(RedoRecPtr);
+			recycleSegNo = XLOGfileslop(lastRedoRecPtr);
 	}
 	else
 		recycleSegNo = 0;		/* keep compiler quiet */
@@ -7158,11 +7158,11 @@ StartupXLOG(void)
 
 					if (info == XLOG_CHECKPOINT_SHUTDOWN)
 					{
-						CheckPoint	checkPoint;
+						CheckPoint	xcheckPoint;
 
-						memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
-						newTLI = checkPoint.ThisTimeLineID;
-						prevTLI = checkPoint.PrevTimeLineID;
+						memcpy(&xcheckPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+						newTLI = xcheckPoint.ThisTimeLineID;
+						prevTLI = xcheckPoint.PrevTimeLineID;
 					}
 					else if (info == XLOG_END_OF_RECOVERY)
 					{
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 67418b05f1..bc8156fcd6 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -70,7 +70,7 @@ report_invalid_record(XLogReaderState *state, const char *fmt,...)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wallog_segment_size, const char *waldir,
 				   XLogPageReadCB pagereadfunc, void *private_data)
 {
 	XLogReaderState *state;
@@ -99,7 +99,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, wallog_segment_size,
 					   waldir);
 
 	state->read_page = pagereadfunc;
diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c
index 5408edcfc2..2f17c140c2 100644
--- a/src/backend/commands/subscriptioncmds.c
+++ b/src/backend/commands/subscriptioncmds.c
@@ -57,7 +57,7 @@ static void
 parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 						   bool *enabled, bool *create_slot,
 						   bool *slot_name_given, char **slot_name,
-						   bool *copy_data, char **synchronous_commit,
+						   bool *copy_data, char **synchr_commit,
 						   bool *refresh)
 {
 	ListCell   *lc;
@@ -85,8 +85,8 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 	}
 	if (copy_data)
 		*copy_data = true;
-	if (synchronous_commit)
-		*synchronous_commit = NULL;
+	if (synchr_commit)
+		*synchr_commit = NULL;
 	if (refresh)
 		*refresh = true;
 
@@ -150,17 +150,17 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 			*copy_data = defGetBoolean(defel);
 		}
 		else if (strcmp(defel->defname, "synchronous_commit") == 0 &&
-				 synchronous_commit)
+				 synchr_commit)
 		{
-			if (*synchronous_commit)
+			if (*synchr_commit)
 				ereport(ERROR,
 						(errcode(ERRCODE_SYNTAX_ERROR),
 						 errmsg("conflicting or redundant options")));
 
-			*synchronous_commit = defGetString(defel);
+			*synchr_commit = defGetString(defel);
 
 			/* Test if the given value is valid for synchronous_commit GUC. */
-			(void) set_config_option("synchronous_commit", *synchronous_commit,
+			(void) set_config_option("synchronous_commit", *synchr_commit,
 									 PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
 									 false, 0, false);
 		}
@@ -317,7 +317,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	bool		enabled_given;
 	bool		enabled;
 	bool		copy_data;
-	char	   *synchronous_commit;
+	char	   *synchr_commit;
 	char	   *conninfo;
 	char	   *slotname;
 	bool		slotname_given;
@@ -332,7 +332,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	 */
 	parse_subscription_options(stmt->options, &connect, &enabled_given,
 							   &enabled, &create_slot, &slotname_given,
-							   &slotname, &copy_data, &synchronous_commit,
+							   &slotname, &copy_data, &synchr_commit,
 							   NULL);
 
 	/*
@@ -375,8 +375,8 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 		slotname = stmt->subname;
 
 	/* The default for synchronous_commit of subscriptions is off. */
-	if (synchronous_commit == NULL)
-		synchronous_commit = "off";
+	if (synchr_commit == NULL)
+		synchr_commit = "off";
 
 	conninfo = stmt->conninfo;
 	publications = stmt->publication;
@@ -407,7 +407,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	else
 		nulls[Anum_pg_subscription_subslotname - 1] = true;
 	values[Anum_pg_subscription_subsynccommit - 1] =
-		CStringGetTextDatum(synchronous_commit);
+		CStringGetTextDatum(synchr_commit);
 	values[Anum_pg_subscription_subpublications - 1] =
 		publicationListToArray(publications);
 
@@ -430,14 +430,14 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	{
 		XLogRecPtr	lsn;
 		char	   *err;
-		WalReceiverConn *wrconn;
+		WalReceiverConn *walrconn;
 		List	   *tables;
 		ListCell   *lc;
 		char		table_state;
 
 		/* Try to connect to the publisher. */
-		wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
-		if (!wrconn)
+		walrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
+		if (!walrconn)
 			ereport(ERROR,
 					(errmsg("could not connect to the publisher: %s", err)));
 
@@ -668,11 +668,11 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
 			{
 				char	   *slotname;
 				bool		slotname_given;
-				char	   *synchronous_commit;
+				char	   *synchr_commit;
 
 				parse_subscription_options(stmt->options, NULL, NULL, NULL,
 										   NULL, &slotname_given, &slotname,
-										   NULL, &synchronous_commit, NULL);
+										   NULL, &synchr_commit, NULL);
 
 				if (slotname_given)
 				{
@@ -690,10 +690,10 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
 					replaces[Anum_pg_subscription_subslotname - 1] = true;
 				}
 
-				if (synchronous_commit)
+				if (synchr_commit)
 				{
 					values[Anum_pg_subscription_subsynccommit - 1] =
-						CStringGetTextDatum(synchronous_commit);
+						CStringGetTextDatum(synchr_commit);
 					replaces[Anum_pg_subscription_subsynccommit - 1] = true;
 				}
 
@@ -835,7 +835,7 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	char		originname[NAMEDATALEN];
 	char	   *err = NULL;
 	RepOriginId originid;
-	WalReceiverConn *wrconn = NULL;
+	WalReceiverConn *walrconn = NULL;
 	StringInfoData cmd;
 	Form_pg_subscription form;
 
@@ -982,8 +982,8 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	initStringInfo(&cmd);
 	appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
 
-	wrconn = walrcv_connect(conninfo, true, subname, &err);
-	if (wrconn == NULL)
+	walrconn = walrcv_connect(conninfo, true, subname, &err);
+	if (walrconn == NULL)
 		ereport(ERROR,
 				(errmsg("could not connect to publisher when attempting to "
 						"drop the replication slot \"%s\"", slotname),
@@ -996,7 +996,7 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	{
 		WalRcvExecResult *res;
 
-		res = walrcv_exec(wrconn, cmd.data, 0, NULL);
+		res = walrcv_exec(walrconn, cmd.data, 0, NULL);
 
 		if (res->status != WALRCV_OK_COMMAND)
 			ereport(ERROR,
@@ -1012,7 +1012,7 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
 	}
 	PG_FINALLY();
 	{
-		walrcv_disconnect(wrconn);
+		walrcv_disconnect(walrconn);
 	}
 	PG_END_TRY();
 
@@ -1124,7 +1124,7 @@ AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
  * publisher connection.
  */
 static List *
-fetch_table_list(WalReceiverConn *wrconn, List *publications)
+fetch_table_list(WalReceiverConn *walrconn, List *publications)
 {
 	WalRcvExecResult *res;
 	StringInfoData cmd;
@@ -1154,7 +1154,7 @@ fetch_table_list(WalReceiverConn *wrconn, List *publications)
 	}
 	appendStringInfoChar(&cmd, ')');
 
-	res = walrcv_exec(wrconn, cmd.data, 2, tableRow);
+	res = walrcv_exec(walrconn, cmd.data, 2, tableRow);
 	pfree(cmd.data);
 
 	if (res->status != WALRCV_OK_TUPLES)
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index a9edbfd4a4..1f5921b6e7 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -225,7 +225,7 @@ main(int argc, char *argv[])
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *prog_name)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -244,7 +244,7 @@ startup_hacks(const char *progname)
 		if (err != 0)
 		{
 			write_stderr("%s: WSAStartup failed: %d\n",
-						 progname, err);
+						 prog_name, err);
 			exit(1);
 		}
 
@@ -305,10 +305,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *prog_name)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), prog_name);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), prog_name);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -365,7 +365,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *prog_name)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -388,7 +388,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 prog_name);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 9ff2832c00..29a3a7517d 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -2538,7 +2538,7 @@ ConnFree(Port *conn)
  * the global variable yet when this is called.
  */
 void
-ClosePostmasterPorts(bool am_syslogger)
+ClosePostmasterPorts(bool syslogger)
 {
 	int			i;
 
@@ -2567,7 +2567,7 @@ ClosePostmasterPorts(bool am_syslogger)
 	}
 
 	/* If using syslogger, close the read side of the pipe */
-	if (!am_syslogger)
+	if (!syslogger)
 	{
 #ifndef WIN32
 		if (syslogPipe[0] >= 0)
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index 8b2a2be1c0..e12f41cea4 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -3223,7 +3223,7 @@ pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
 	for (i = 0; i < max_wal_senders; i++)
 	{
 		WalSnd	   *walsnd = &WalSndCtl->walsnds[i];
-		XLogRecPtr	sentPtr;
+		XLogRecPtr	walsentPtr;
 		XLogRecPtr	write;
 		XLogRecPtr	flush;
 		XLogRecPtr	apply;
@@ -3247,7 +3247,7 @@ pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
 			continue;
 		}
 		pid = walsnd->pid;
-		sentPtr = walsnd->sentPtr;
+		walsentPtr = walsnd->sentPtr;
 		state = walsnd->state;
 		write = walsnd->write;
 		flush = walsnd->flush;
@@ -3278,9 +3278,9 @@ pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
 		{
 			values[1] = CStringGetTextDatum(WalSndGetStateString(state));
 
-			if (XLogRecPtrIsInvalid(sentPtr))
+			if (XLogRecPtrIsInvalid(walsentPtr))
 				nulls[2] = true;
-			values[2] = LSNGetDatum(sentPtr);
+			values[2] = LSNGetDatum(walsentPtr);
 
 			if (XLogRecPtrIsInvalid(write))
 				nulls[3] = true;
diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index 709bbaaf5a..63097739c4 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -508,16 +508,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		ndays = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + ndays;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((ndays >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -532,16 +532,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		ndays = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - ndays;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((ndays >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -1810,18 +1810,18 @@ interval_time(PG_FUNCTION_ARGS)
 {
 	Interval   *span = PG_GETARG_INTERVAL_P(0);
 	TimeADT		result;
-	int64		days;
+	int64		ndays;
 
 	result = span->time;
 	if (result >= USECS_PER_DAY)
 	{
-		days = result / USECS_PER_DAY;
-		result -= days * USECS_PER_DAY;
+		ndays = result / USECS_PER_DAY;
+		result -= ndays * USECS_PER_DAY;
 	}
 	else if (result < 0)
 	{
-		days = (-result + USECS_PER_DAY - 1) / USECS_PER_DAY;
-		result += days * USECS_PER_DAY;
+		ndays = (-result + USECS_PER_DAY - 1) / USECS_PER_DAY;
+		result += ndays * USECS_PER_DAY;
 	}
 
 	PG_RETURN_TIMEADT(result);
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 31bdb37c55..2f721ee67e 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -1500,9 +1500,9 @@ Datum
 make_interval(PG_FUNCTION_ARGS)
 {
 	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
+	int32		nmonths = PG_GETARG_INT32(1);
 	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
+	int32		ndays = PG_GETARG_INT32(3);
 	int32		hours = PG_GETARG_INT32(4);
 	int32		mins = PG_GETARG_INT32(5);
 	double		secs = PG_GETARG_FLOAT8(6);
@@ -1518,8 +1518,8 @@ make_interval(PG_FUNCTION_ARGS)
 				 errmsg("interval out of range")));
 
 	result = (Interval *) palloc(sizeof(Interval));
-	result->month = years * MONTHS_PER_YEAR + months;
-	result->day = weeks * 7 + days;
+	result->month = years * MONTHS_PER_YEAR + nmonths;
+	result->day = weeks * 7 + ndays;
 
 	secs = rint(secs * USECS_PER_SEC);
 	result->time = hours * ((int64) SECS_PER_HOUR * USECS_PER_SEC) +
@@ -2343,22 +2343,22 @@ interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
 	int64		dayfraction;
-	int64		days;
+	int64		ndays;
 
 	/*
 	 * Separate time field into days and dayfraction, then add the month and
 	 * day fields to the days part.  We cannot overflow int64 days here.
 	 */
 	dayfraction = interval->time % USECS_PER_DAY;
-	days = interval->time / USECS_PER_DAY;
-	days += interval->month * INT64CONST(30);
-	days += interval->day;
+	ndays = interval->time / USECS_PER_DAY;
+	ndays += interval->month * INT64CONST(30);
+	ndays += interval->day;
 
 	/* Widen dayfraction to 128 bits */
 	span = int64_to_int128(dayfraction);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, ndays, USECS_PER_DAY);
 
 	return span;
 }
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index ba74bf9f7d..1644c66236 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -5389,7 +5389,7 @@ InitializeOneGUCOption(struct config_generic *gconf)
  * to stderr and returns false.
  */
 bool
-SelectConfigFiles(const char *userDoption, const char *progname)
+SelectConfigFiles(const char *userDoption, const char *prog_name)
 {
 	char	   *configdir;
 	char	   *fname;
@@ -5404,7 +5404,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 	if (configdir && stat(configdir, &stat_buf) != 0)
 	{
 		write_stderr("%s: could not access directory \"%s\": %s\n",
-					 progname,
+					 prog_name,
 					 configdir,
 					 strerror(errno));
 		if (errno == ENOENT)
@@ -5431,7 +5431,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 		write_stderr("%s does not know where to find the server configuration file.\n"
 					 "You must specify the --config-file or -D invocation "
 					 "option or set the PGDATA environment variable.\n",
-					 progname);
+					 prog_name);
 		return false;
 	}
 
@@ -5448,7 +5448,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 	if (stat(ConfigFileName, &stat_buf) != 0)
 	{
 		write_stderr("%s: could not access the server configuration file \"%s\": %s\n",
-					 progname, ConfigFileName, strerror(errno));
+					 prog_name, ConfigFileName, strerror(errno));
 		free(configdir);
 		return false;
 	}
@@ -5477,7 +5477,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 					 "This can be specified as \"data_directory\" in \"%s\", "
 					 "or by the -D invocation option, or by the "
 					 "PGDATA environment variable.\n",
-					 progname, ConfigFileName);
+					 prog_name, ConfigFileName);
 		return false;
 	}
 
@@ -5525,7 +5525,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 					 "This can be specified as \"hba_file\" in \"%s\", "
 					 "or by the -D invocation option, or by the "
 					 "PGDATA environment variable.\n",
-					 progname, ConfigFileName);
+					 prog_name, ConfigFileName);
 		return false;
 	}
 	SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
@@ -5548,7 +5548,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 					 "This can be specified as \"ident_file\" in \"%s\", "
 					 "or by the -D invocation option, or by the "
 					 "PGDATA environment variable.\n",
-					 progname, ConfigFileName);
+					 prog_name, ConfigFileName);
 		return false;
 	}
 	SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 1f6d8939be..88ed6ff44b 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -266,10 +266,10 @@ static void trapsig(int signum);
 static void check_ok(void);
 static char *escape_quotes(const char *src);
 static char *escape_quotes_bki(const char *src);
-static int	locale_date_order(const char *locale);
-static void check_locale_name(int category, const char *locale,
+static int	locale_date_order(const char *locale_name);
+static void check_locale_name(int category, const char *locale_name,
 							  char **canonname);
-static bool check_locale_encoding(const char *locale, int encoding);
+static bool check_locale_encoding(const char *locale_name, int encoding);
 static void setlocales(void);
 static void usage(const char *progname);
 void		setup_pgdata(void);
@@ -631,7 +631,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user_name;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -644,9 +644,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user_name = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user_name);
 }
 
 static char *
@@ -864,17 +864,17 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *file;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+        file = fopen(path, PG_BINARY_W);
+	if (file == NULL)
 	{
 		pg_log_error("could not open file \"%s\" for writing: %m", path);
 		exit(1);
 	}
-	if (fclose(conf_file))
+	if (fclose(file))
 	{
 		pg_log_error("could not write file \"%s\": %m", path);
 		exit(1);
@@ -2107,7 +2107,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *locale_name)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2125,7 +2125,7 @@ locale_date_order(const char *locale)
 		return result;
 	save = pg_strdup(save);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, locale_name);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2170,7 +2170,7 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *locale_name, char **canonname)
 {
 	char	   *save;
 	char	   *res;
@@ -2193,7 +2193,7 @@ check_locale_name(int category, const char *locale, char **canonname)
 		locale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, locale_name);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2210,8 +2210,8 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
-			pg_log_error("invalid locale name \"%s\"", locale);
+		if (*locale_name)
+			pg_log_error("invalid locale name \"%s\"", locale_name);
 		else
 		{
 			/*
@@ -2234,11 +2234,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *locale_name, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(locale_name, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2321,11 +2321,11 @@ setlocales(void)
  * print help text
  */
 static void
-usage(const char *progname)
+usage(const char *prog_name)
 {
-	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), prog_name);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION]... [DATADIR]\n"), prog_name);
 	printf(_("\nOptions:\n"));
 	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
 	printf(_("      --auth-host=METHOD    default authentication method for local TCP/IP connections\n"));
@@ -2393,22 +2393,22 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
+check_need_password(const char *authmethod_local, const char *authmethod_host)
 {
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+	if ((strcmp(authmethod_local, "md5") == 0 ||
+		 strcmp(authmethod_local, "password") == 0 ||
+		 strcmp(authmethod_local, "scram-sha-256") == 0) &&
+		(strcmp(authmethod_host, "md5") == 0 ||
+		 strcmp(authmethod_host, "password") == 0 ||
+		 strcmp(authmethod_host, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 	{
 		pg_log_error("must specify a password for the superuser to enable %s authentication",
-					 (strcmp(authmethodlocal, "md5") == 0 ||
-					  strcmp(authmethodlocal, "password") == 0 ||
-					  strcmp(authmethodlocal, "scram-sha-256") == 0)
-					 ? authmethodlocal
-					 : authmethodhost);
+					 (strcmp(authmethod_local, "md5") == 0 ||
+					  strcmp(authmethod_local, "password") == 0 ||
+					  strcmp(authmethod_local, "scram-sha-256") == 0)
+					 ? authmethod_local
+					 : authmethod_host);
 		exit(1);
 	}
 }
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index 19e21ab491..11784c589b 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -30,11 +30,11 @@
 #include "pg_getopt.h"
 
 static void
-usage(const char *progname)
+usage(const char *prog_name)
 {
-	printf(_("%s displays control information of a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s displays control information of a PostgreSQL database cluster.\n\n"), prog_name);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION] [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION] [DATADIR]\n"), prog_name);
 	printf(_("\nOptions:\n"));
 	printf(_(" [-D, --pgdata=]DATADIR  data directory\n"));
 	printf(_("  -V, --version          output version information, then exit\n"));
@@ -69,9 +69,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel wallevel)
 {
-	switch (wal_level)
+	switch (wallevel)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 65f9fb4c0a..80715bae01 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -742,7 +742,7 @@ read_post_opts(void)
  * waiting for the server to start up, the server launch is aborted.
  */
 static void
-trap_sigint_during_startup(int sig)
+trap_sigint_during_startup(int signal)
 {
 	if (postmasterPID != -1)
 	{
@@ -760,18 +760,18 @@ trap_sigint_during_startup(int sig)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *argv_0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(argv_0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(argv_0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c
index 37432a6f4b..135b9e13de 100644
--- a/src/bin/pg_dump/common.c
+++ b/src/bin/pg_dump/common.c
@@ -64,10 +64,10 @@ static int	numExtensions;
 static ExtensionMemberId *extmembers;
 static int	numextmembers;
 
-static void flagInhTables(Archive *fout, TableInfo *tbinfo, int numTables,
+static void flagInhTables(Archive *fout, TableInfo *tbinfo, int num_Tables,
 						  InhInfo *inhinfo, int numInherits);
-static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int numTables);
-static void flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables);
+static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int num_Tables);
+static void flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int num_Tables);
 static DumpableObject **buildIndexArray(void *objArray, int numObjs,
 										Size objSize);
 static int	DOCatalogIdCompare(const void *p1, const void *p2);
@@ -270,14 +270,14 @@ getSchemaData(Archive *fout, int *numTablesPtr)
  * modifies tblinfo
  */
 static void
-flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
+flagInhTables(Archive *fout, TableInfo *tblinfo, int num_Tables,
 			  InhInfo *inhinfo, int numInherits)
 {
 	DumpOptions *dopt = fout->dopt;
 	int			i,
 				j;
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < num_Tables; i++)
 	{
 		bool		find_parents = true;
 		bool		mark_parents = true;
@@ -329,7 +329,7 @@ flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
  *	 appropriate dependency links.
  */
 static void
-flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
+flagInhIndexes(Archive *fout, TableInfo tblinfo[], int num_Tables)
 {
 	int			i,
 				j,
@@ -339,7 +339,7 @@ flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
 	parentIndexArray = (DumpableObject ***)
 		pg_malloc0(getMaxDumpId() * sizeof(DumpableObject **));
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < num_Tables; i++)
 	{
 		TableInfo  *parenttbl;
 		IndexAttachInfo *attachinfo;
@@ -436,13 +436,13 @@ flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
  * modifies tblinfo
  */
 static void
-flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables)
+flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int num_Tables)
 {
 	int			i,
 				j,
 				k;
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < num_Tables; i++)
 	{
 		TableInfo  *tbinfo = &(tblinfo[i]);
 		int			numParents;
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 08658c8e86..5cfa243ad4 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -147,7 +147,7 @@ static int	extra_float_digits;
 	fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
 				   (obj)->dobj.name)
 
-static void help(const char *progname);
+static void help(const char *prog_name);
 static void setup_connection(Archive *AH,
 							 const char *dumpencoding, const char *dumpsnapshot,
 							 char *use_role);
@@ -155,11 +155,11 @@ static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
 static void expand_schema_name_patterns(Archive *fout,
 										SimpleStringList *patterns,
 										SimpleOidList *oids,
-										bool strict_names);
+										bool strictnames);
 static void expand_table_name_patterns(Archive *fout,
 									   SimpleStringList *patterns,
 									   SimpleOidList *oids,
-									   bool strict_names);
+									   bool strictnames);
 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
@@ -972,11 +972,11 @@ main(int argc, char **argv)
 
 
 static void
-help(const char *progname)
+help(const char *prog_name)
 {
-	printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
+	printf(_("%s dumps a database as a text file or to other formats.\n\n"), prog_name);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), prog_name);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -f, --file=FILENAME          output file or directory name\n"));
@@ -1293,7 +1293,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool strictnames)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1318,7 +1318,7 @@ expand_schema_name_patterns(Archive *fout,
 							  false, NULL, "n.nspname", NULL, NULL);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (strictnames && PQntuples(res) == 0)
 			fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1341,7 +1341,7 @@ expand_schema_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names)
+						   bool strictnames)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1383,7 +1383,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (strictnames && PQntuples(res) == 0)
 			fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index d1a36b1495..67fa5e8975 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -50,7 +50,7 @@
 #include "parallel.h"
 #include "pg_backup_utils.h"
 
-static void usage(const char *progname);
+static void usage(const char *prog_name);
 
 int
 main(int argc, char **argv)
@@ -456,11 +456,11 @@ main(int argc, char **argv)
 }
 
 static void
-usage(const char *progname)
+usage(const char *prog_name)
 {
-	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), progname);
+	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), prog_name);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [FILE]\n"), progname);
+	printf(_("  %s [OPTION]... [FILE]\n"), prog_name);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -d, --dbname=NAME        connect to database name\n"));
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 2e286f6339..7fb590ffb8 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -738,9 +738,9 @@ GuessControlValues(void)
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool guessed_control)
 {
-	if (guessed)
+	if (guessed_control)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 2ca1608bd2..0023c67938 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -91,7 +91,7 @@ static void signal_cleanup(int sig);
 #ifdef HAVE_FSYNC_WRITETHROUGH
 static int	pg_fsync_writethrough(int fd);
 #endif
-static void print_elapse(struct timeval start_t, struct timeval stop_t, int ops);
+static void print_elapse(struct timeval startt, struct timeval stopt, int ops);
 
 #define die(msg) do { pg_log_error("%s: %m", _(msg)); exit(1); } while(0)
 
@@ -576,10 +576,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval startt, struct timeval stopt, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-	(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stopt.tv_sec - startt.tv_sec) +
+	(stopt.tv_usec - startt.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
diff --git a/src/include/access/xlogreader.h b/src/include/access/xlogreader.h
index 0193611b7f..d8991d1a79 100644
--- a/src/include/access/xlogreader.h
+++ b/src/include/access/xlogreader.h
@@ -209,7 +209,7 @@ struct XLogReaderState
 };
 
 /* Get a new XLogReader */
-extern XLogReaderState *XLogReaderAllocate(int wal_segment_size,
+extern XLogReaderState *XLogReaderAllocate(int wallog_segment_size,
 										   const char *waldir,
 										   XLogPageReadCB pagereadfunc,
 										   void *private_data);
diff --git a/src/include/utils/guc.h b/src/include/utils/guc.h
index 50098e63fe..809f043ba1 100644
--- a/src/include/utils/guc.h
+++ b/src/include/utils/guc.h
@@ -354,7 +354,7 @@ extern const char *GetConfigOptionResetString(const char *name);
 extern int	GetConfigOptionFlags(const char *name, bool missing_ok);
 extern void ProcessConfigFile(GucContext context);
 extern void InitializeGUCOptions(void);
-extern bool SelectConfigFiles(const char *userDoption, const char *progname);
+extern bool SelectConfigFiles(const char *userDoption, const char *prog_name);
 extern void ResetAllOptions(void);
 extern void AtStart_GUC(void);
 extern int	NewGUCNestLevel(void);
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index a29f530327..7568d1c1a9 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -73,7 +73,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(char *name, char *connection)
+add_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *new;
 
@@ -87,16 +87,16 @@ add_descriptor(char *name, char *connection)
 	strcpy(new->name, name);
 	if (connection)
 	{
-		new->connection = mm_alloc(strlen(connection) + 1);
-		strcpy(new->connection, connection);
+		new->connection = mm_alloc(strlen(conn_str) + 1);
+		strcpy(new->connection, conn_str);
 	}
 	else
-		new->connection = connection;
+		new->connection = conn_str;
 	descriptors = new;
 }
 
 void
-drop_descriptor(char *name, char *connection)
+drop_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -108,9 +108,9 @@ drop_descriptor(char *name, char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				if (i->connection)
@@ -126,7 +126,7 @@ drop_descriptor(char *name, char *connection)
 
 struct descriptor
 		   *
-lookup_descriptor(char *name, char *connection)
+lookup_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *i;
 
@@ -137,9 +137,9 @@ lookup_descriptor(char *name, char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
 		}
 	}
#30Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Mark Dilger (#19)
1 attachment(s)
RE: [Proposal] Level4 Warnings show many shadow vars

I'll create the commitfest entry based on this email once
this has been sent.

Can you add the patch attached?

regards,
Ranier Vilela

Attachments:

unshadow_walsender_sentPtr.patchtext/x-patch; name=unshadow_walsender_sentPtr.patchDownload
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index 8b2a2be1c0..e12f41cea4 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -3223,7 +3223,7 @@ pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
 	for (i = 0; i < max_wal_senders; i++)
 	{
 		WalSnd	   *walsnd = &WalSndCtl->walsnds[i];
-		XLogRecPtr	sentPtr;
+		XLogRecPtr	walsentPtr;
 		XLogRecPtr	write;
 		XLogRecPtr	flush;
 		XLogRecPtr	apply;
@@ -3247,7 +3247,7 @@ pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
 			continue;
 		}
 		pid = walsnd->pid;
-		sentPtr = walsnd->sentPtr;
+		walsentPtr = walsnd->sentPtr;
 		state = walsnd->state;
 		write = walsnd->write;
 		flush = walsnd->flush;
@@ -3278,9 +3278,9 @@ pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
 		{
 			values[1] = CStringGetTextDatum(WalSndGetStateString(state));
 
-			if (XLogRecPtrIsInvalid(sentPtr))
+			if (XLogRecPtrIsInvalid(walsentPtr))
 				nulls[2] = true;
-			values[2] = LSNGetDatum(sentPtr);
+			values[2] = LSNGetDatum(walsentPtr);
 
 			if (XLogRecPtrIsInvalid(write))
 				nulls[3] = true;

#31Mark Dilger
hornschnorter@gmail.com
In reply to: Ranier Vilela (#30)
Re: [Proposal] Level4 Warnings show many shadow vars

On 12/9/19 9:28 AM, Ranier Vilela wrote:

I'll create the commitfest entry based on this email once
this has been sent.

Can you add the patch attached?

That showed up in the commitfest entry automatically when you
replied to this thread with the attachment.

You might consider signing up so you can log into the commitfest
app. https://www.postgresql.org/account/signup/

--
Mark Dilger

#32Andres Freund
andres@anarazel.de
In reply to: Robert Haas (#28)
Re: [Proposal] Level4 Warnings show many shadow vars

Hi,

On 2019-12-09 11:59:23 -0500, Robert Haas wrote:

On Mon, Dec 9, 2019 at 11:48 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:

I think it depends a lot on the particular identifiers in use. You
mentioned examples like "i" and "lc", and I'd add other obviously
nonce variable names like "oldcxt". I'm not particularly concerned
about shadowing arising from somebody writing a five-line loop using
a local "i" inside a much larger loop also using "i" --- yeah, in
theory there could be an issue, but in practice there isn't. Being
picky about that just adds difficulty when writing/reviewing a patch
that adds such a five-line loop.

I think I would take the contrary view here. I think reusing the same
variable names in a single function is confusing, and if I noticed it
while reviewing, I would ask for it to be changed. It's not a
five-alarm fire, but it's not good, either.

+1. For me it leaves mildly bad taste seing code like that.

To me, the grey
area is in conflicts between stuff in our code and stuff in system
header files. I'm not sure I'd want to try to have precisely 0
conflicts with every crazy decision by every OS / libc maintainer out
there, and I suspect on that point at least we are in agreement.

I believe the relevant C standards (and practice) are that random
names exposed by system headers ought to start with some underscores.
If there's a conflict there, it's a bug in the header and cause
for a bug report to the OS vendor, not us.

Sure. I mean we'd have to look at individual cases, but in general I agree.

We do have a few files where we have names starting with underscores
ourselves, imo not a great idea for most of them.

Now, if a conflict of that sort exists and is causing a live bug in PG
on a popular OS, then I'd likely be on board with adjusting our code
to dodge the problem. But not with doing so just to silence a
compiler warning.

Sounds reasonable.

FWIW, I've had bugs in code submitted to PG (both by myself and me
merging other people's work IIRC) that were related to such naming
conflicts.

The only thing I think is really a substantial bug risk here is your
point about our own macros referencing our own global variables.
We might be better off fixing that in a localized way by establishing
a policy that any such macros should be converted to static inlines.

That would be a lot of work, but it would probably have some side
benefits, like making things more type-safe.

It's also not always possible in C99, as we have plenty macros with
essentially dynamic types. And there's no typeof() in standard C,
unfortunately (C11's _Generic can help, but isn't great either).

Greetings,

Andres Freund

#33Tom Lane
tgl@sss.pgh.pa.us
In reply to: Andres Freund (#32)
Re: [Proposal] Level4 Warnings show many shadow vars

Andres Freund <andres@anarazel.de> writes:

On 2019-12-09 11:59:23 -0500, Robert Haas wrote:

On Mon, Dec 9, 2019 at 11:48 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:

The only thing I think is really a substantial bug risk here is your
point about our own macros referencing our own global variables.
We might be better off fixing that in a localized way by establishing
a policy that any such macros should be converted to static inlines.

That would be a lot of work, but it would probably have some side
benefits, like making things more type-safe.

It's also not always possible in C99, as we have plenty macros with
essentially dynamic types. And there's no typeof() in standard C,
unfortunately (C11's _Generic can help, but isn't great either).

How much overlap is there between macros referencing global variables
and macros with indeterminate types? Not much I bet. I'd mostly
be worried about things like CHECK_FOR_INTERRUPTS().

regards, tom lane

#34Alvaro Herrera
alvherre@2ndquadrant.com
In reply to: Kyotaro Horiguchi (#18)
Re: [Proposal] Level4 Warnings show many shadow vars

On 2019-Dec-09, Kyotaro Horiguchi wrote:

BTW, if we do go forward with changing the RedoRecPtr uses, I'm not
in love with "XRedoRecPtr" as a replacement parameter name; it conveys
nothing much, and the "X" prefix is already overused in that area of
the code. Perhaps "pRedoRecPtr" would be a better choice? Or maybe
make the local variables be all-lower-case "redorecptr", which would
fit well in context in places like

pRedoRecPtr, It's perfect for me.

Anyway I strongly object to the name 'pRedoRecPtr', which suggests as
if it is a C-pointer to some variable. (And I believe we use Hungarian
notation only if we don't have a better way...) LatestRedoRecPtr
looks better to me.

We have a not-consistently-used convention that names in CamelCase are
used for global variables. Naming a function parameter in that style
seems pointlessly confusing. I would rather use redorecptr as Tom
suggested, which fits with the style used for the other arguments of
that function. BTW prepending an X or a p looks like minimum effort...
I'd stay away from that.

It's probably a lost cause to enforce such a style with ironclad
consistency, but I suggest we make at least a token effort at it, and
keep our source as least confusing as possible.

--
�lvaro Herrera https://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#35Alvaro Herrera
alvherre@2ndquadrant.com
In reply to: Ranier Vilela (#29)
Re: [Proposal] Level4 Warnings show many shadow vars

On 2019-Dec-09, Ranier Vilela wrote:

--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -70,7 +70,7 @@ report_invalid_record(XLogReaderState *state, const char *fmt,...)
* Returns NULL if the xlogreader couldn't be allocated.
*/
XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int wallog_segment_size, const char *waldir,
XLogPageReadCB pagereadfunc, void *private_data)
{
XLogReaderState *state;

I find this choice a bit ugly and even more confusing than the original.
I'd change this to be just "segsize".

I would tend to name the GUC variable as if it were a global in the
sense that I proposed in my previous response (ie. WalSegmentSize), but
that creates a bit of a problem when one greps the source looking for
reference to the GUCs. Some GUCs do have CamelCase names and others
don't; I've grown fond of the current style of using the same name for
the variable as for the GUC itself, for grepping reasons. So I'm not
going to propose to do that. But let's not make a function parameter
have a name that vaguely suggests that it itself is a GUC.

@@ -430,14 +430,14 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
{
XLogRecPtr lsn;
char *err;
- WalReceiverConn *wrconn;
+ WalReceiverConn *walrconn;
List *tables;
ListCell *lc;
char table_state;

/* Try to connect to the publisher. */
-		wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
-		if (!wrconn)
+		walrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
+		if (!walrconn)
ereport(ERROR,
(errmsg("could not connect to the publisher: %s", err)));

Here I propose to rename the global instead (to WalReceiverConn maybe).
There's nothing about the name "wrconn" that suggests it's a global
variable. In any other place where the object is used as a local
variable, I'd just use "conn". Trying to be clever and adding a letter
here or a letter there makes it *more* likely that you'll reference the
wrong one in some function.

index a9edbfd4a4..1f5921b6e7 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -225,7 +225,7 @@ main(int argc, char *argv[])
* without help.  Avoid adding more here, if you can.
*/
static void
-startup_hacks(const char *progname)
+startup_hacks(const char *prog_name)
{
/*
* Windows-specific execution environment hacking.

I don't agree with this change very much. I think "progname" in
particular is a bit of a debacle right now but I don't think this is the
best fix. I'd leave this alone.

diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index 8b2a2be1c0..e12f41cea4 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -3223,7 +3223,7 @@ pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
for (i = 0; i < max_wal_senders; i++)
{
WalSnd	   *walsnd = &WalSndCtl->walsnds[i];
-		XLogRecPtr	sentPtr;
+		XLogRecPtr	walsentPtr;
XLogRecPtr	write;
XLogRecPtr	flush;
XLogRecPtr	apply;

As before: let's rename the file-level static instead. "sentPtr" is not
a good name.

--
�lvaro Herrera https://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#36Tom Lane
tgl@sss.pgh.pa.us
In reply to: Alvaro Herrera (#34)
Re: [Proposal] Level4 Warnings show many shadow vars

Alvaro Herrera <alvherre@2ndquadrant.com> writes:

We have a not-consistently-used convention that names in CamelCase are
used for global variables. Naming a function parameter in that style
seems pointlessly confusing. I would rather use redorecptr as Tom
suggested, which fits with the style used for the other arguments of
that function. BTW prepending an X or a p looks like minimum effort...
I'd stay away from that.

Actually, for the particular case of RemoveXlogFile(s), I wonder if it
shouldn't be "startptr" to go with the other argument "endptr". This line
of thinking might not lead to nicer names in other functions, of course.
But we shouldn't assume that a one-size-fits-all solution is going to
improve legibility, and in the end, legibility is what this should be
about.

regards, tom lane

#37Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Alvaro Herrera (#35)
RE: [Proposal] Level4 Warnings show many shadow vars

De: Alvaro Herrera <alvherre@2ndquadrant.com>
Enviado: segunda-feira, 9 de dezembro de 2019 22:06

I find this choice a bit ugly and even more confusing than the original.
I'd change this to be just "segsize".

Ok.

I would tend to name the GUC variable as if it were a global in the
sense that I proposed in my previous response (ie. WalSegmentSize), but
that creates a bit of a problem when one greps the source looking for
reference to the GUCs. Some GUCs do have CamelCase names and others
don't; I've grown fond of the current style of using the same name for
the variable as for the GUC itself, for grepping reasons. So I'm not
going to propose to do that. But let's not make a function parameter
have a name that vaguely suggests that it itself is a GUC.

I understand the ease of grepping.
But ideally, having global names that by convention would make it very clear that they are global, something like:
pg_conn or gconn or guc_synch_commit
The prefix does not matter, as long as once all the new variables and the ones that might have to be changed were chosen, they adopted the agreed nomenclature.
That way, when looking for global names, it would be easy.

Here I propose to rename the global instead (to WalReceiverConn maybe).
There's nothing about the name "wrconn" that suggests it's a global
variable. In any other place where the object is used as a local
variable, I'd just use "conn". Trying to be clever and adding a letter
here or a letter there makes it *more* likely that you'll reference the
wrong one in some function.

Again, it could be that name, WalReceiverConn, but nothing in it suggests it is a global one.
For a project that makes extensive use of globals, it would help to have a nomenclature defined at least for the prefix:
pg_WalReceiverConn or gWalReceiverConn and if it is a guc, guc_WalReceiverConn?

I don't agree with this change very much. I think "progname" in
particular is a bit of a debacle right now but I don't think this is the
best fix. I'd leave this alone.

Ok. In such cases, it doesn't hurt today. But for future reasons, it would be better to fix everything, imo.

As before: let's rename the file-level static instead. "sentPtr" is not
a good name.

gsent_Ptr or pg_sentPtr?

regards,
Ranier Vilela

#38Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Alvaro Herrera (#35)
1 attachment(s)
RE: [Proposal] Level4 Warnings show many shadow vars

New version the global patch, with the considerations.
Unfortunately WalReceiverConn cannot be used because it is currently the typedef name for the structure.
I switched to WalReceiverConnection, it was long but it looks good.
RedoRecPtr proper name has no consensus yet, so it was still lastRedoRecPtr.

regards,
Ranier Vilela

Attachments:

shadow_global_v3.patchtext/x-patch; name=shadow_global_v3.patchDownload
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 6bc1a6b46d..83be23d77b 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -892,8 +892,8 @@ static int	emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
 static void XLogFileClose(void);
 static void PreallocXlogFiles(XLogRecPtr endptr);
 static void RemoveTempXlogFiles(void);
-static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
-static void RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
+static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr);
+static void RemoveXlogFile(const char *segname, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr);
 static void UpdateLastRemovedPtr(char *filename);
 static void ValidateXLOGDirectoryStructure(void);
 static void CleanupBackupHistory(void);
@@ -2299,7 +2299,7 @@ assign_checkpoint_completion_target(double newval, void *extra)
  * XLOG segments? Returns the highest segment that should be preallocated.
  */
 static XLogSegNo
-XLOGfileslop(XLogRecPtr RedoRecPtr)
+XLOGfileslop(XLogRecPtr lastRedoRecPtr)
 {
 	XLogSegNo	minSegNo;
 	XLogSegNo	maxSegNo;
@@ -2311,9 +2311,9 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	 * correspond to. Always recycle enough segments to meet the minimum, and
 	 * remove enough segments to stay below the maximum.
 	 */
-	minSegNo = RedoRecPtr / wal_segment_size +
+	minSegNo = lastRedoRecPtr / wal_segment_size +
 		ConvertToXSegs(min_wal_size_mb, wal_segment_size) - 1;
-	maxSegNo = RedoRecPtr / wal_segment_size +
+	maxSegNo = lastRedoRecPtr / wal_segment_size +
 		ConvertToXSegs(max_wal_size_mb, wal_segment_size) - 1;
 
 	/*
@@ -2328,7 +2328,7 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	/* add 10% for good measure. */
 	distance *= 1.10;
 
-	recycleSegNo = (XLogSegNo) ceil(((double) RedoRecPtr + distance) /
+	recycleSegNo = (XLogSegNo) ceil(((double) lastRedoRecPtr + distance) /
 									wal_segment_size);
 
 	if (recycleSegNo < minSegNo)
@@ -3949,12 +3949,12 @@ RemoveTempXlogFiles(void)
 /*
  * Recycle or remove all log files older or equal to passed segno.
  *
- * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * endptr is current (or recent) end of xlog, and lastRedoRecPtr is the
  * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
  */
 static void
-RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr)
 {
 	DIR		   *xldir;
 	struct dirent *xlde;
@@ -3997,7 +3997,7 @@ RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 				/* Update the last removed location in shared memory first */
 				UpdateLastRemovedPtr(xlde->d_name);
 
-				RemoveXlogFile(xlde->d_name, RedoRecPtr, endptr);
+				RemoveXlogFile(xlde->d_name, lastRedoRecPtr, endptr);
 			}
 		}
 	}
@@ -4071,14 +4071,14 @@ RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
 /*
  * Recycle or remove a log file that's no longer needed.
  *
- * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * endptr is current (or recent) end of xlog, and lastRedoRecPtr is the
  * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
- * If RedoRecPtr is not known, pass invalid, and the function will recycle,
+ * If lastRedoRecPtr is not known, pass invalid, and the function will recycle,
  * somewhat arbitrarily, 10 future segments.
  */
 static void
-RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveXlogFile(const char *segname, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr)
 {
 	char		path[MAXPGPATH];
 #ifdef WIN32
@@ -4094,10 +4094,10 @@ RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 		 * Initialize info about where to try to recycle to.
 		 */
 		XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
-		if (RedoRecPtr == InvalidXLogRecPtr)
+		if (lastRedoRecPtr == InvalidXLogRecPtr)
 			recycleSegNo = endlogSegNo + 10;
 		else
-			recycleSegNo = XLOGfileslop(RedoRecPtr);
+			recycleSegNo = XLOGfileslop(lastRedoRecPtr);
 	}
 	else
 		recycleSegNo = 0;		/* keep compiler quiet */
@@ -7158,11 +7158,11 @@ StartupXLOG(void)
 
 					if (info == XLOG_CHECKPOINT_SHUTDOWN)
 					{
-						CheckPoint	checkPoint;
+						CheckPoint	xcheckPoint;
 
-						memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
-						newTLI = checkPoint.ThisTimeLineID;
-						prevTLI = checkPoint.PrevTimeLineID;
+						memcpy(&xcheckPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+						newTLI = xcheckPoint.ThisTimeLineID;
+						prevTLI = xcheckPoint.PrevTimeLineID;
 					}
 					else if (info == XLOG_END_OF_RECOVERY)
 					{
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 67418b05f1..4915577e10 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -70,7 +70,7 @@ report_invalid_record(XLogReaderState *state, const char *fmt,...)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int segment_size, const char *waldir,
 				   XLogPageReadCB pagereadfunc, void *private_data)
 {
 	XLogReaderState *state;
@@ -99,7 +99,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, segment_size,
 					   waldir);
 
 	state->read_page = pagereadfunc;
diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c
index 5408edcfc2..9931016fd7 100644
--- a/src/backend/commands/subscriptioncmds.c
+++ b/src/backend/commands/subscriptioncmds.c
@@ -57,7 +57,7 @@ static void
 parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 						   bool *enabled, bool *create_slot,
 						   bool *slot_name_given, char **slot_name,
-						   bool *copy_data, char **synchronous_commit,
+						   bool *copy_data, char **synchr_commit,
 						   bool *refresh)
 {
 	ListCell   *lc;
@@ -85,8 +85,8 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 	}
 	if (copy_data)
 		*copy_data = true;
-	if (synchronous_commit)
-		*synchronous_commit = NULL;
+	if (synchr_commit)
+		*synchr_commit = NULL;
 	if (refresh)
 		*refresh = true;
 
@@ -150,17 +150,17 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 			*copy_data = defGetBoolean(defel);
 		}
 		else if (strcmp(defel->defname, "synchronous_commit") == 0 &&
-				 synchronous_commit)
+				 synchr_commit)
 		{
-			if (*synchronous_commit)
+			if (*synchr_commit)
 				ereport(ERROR,
 						(errcode(ERRCODE_SYNTAX_ERROR),
 						 errmsg("conflicting or redundant options")));
 
-			*synchronous_commit = defGetString(defel);
+			*synchr_commit = defGetString(defel);
 
 			/* Test if the given value is valid for synchronous_commit GUC. */
-			(void) set_config_option("synchronous_commit", *synchronous_commit,
+			(void) set_config_option("synchronous_commit", *synchr_commit,
 									 PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
 									 false, 0, false);
 		}
@@ -317,7 +317,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	bool		enabled_given;
 	bool		enabled;
 	bool		copy_data;
-	char	   *synchronous_commit;
+	char	   *synchr_commit;
 	char	   *conninfo;
 	char	   *slotname;
 	bool		slotname_given;
@@ -332,7 +332,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	 */
 	parse_subscription_options(stmt->options, &connect, &enabled_given,
 							   &enabled, &create_slot, &slotname_given,
-							   &slotname, &copy_data, &synchronous_commit,
+							   &slotname, &copy_data, &synchr_commit,
 							   NULL);
 
 	/*
@@ -375,8 +375,8 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 		slotname = stmt->subname;
 
 	/* The default for synchronous_commit of subscriptions is off. */
-	if (synchronous_commit == NULL)
-		synchronous_commit = "off";
+	if (synchr_commit == NULL)
+		synchr_commit = "off";
 
 	conninfo = stmt->conninfo;
 	publications = stmt->publication;
@@ -407,7 +407,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	else
 		nulls[Anum_pg_subscription_subslotname - 1] = true;
 	values[Anum_pg_subscription_subsynccommit - 1] =
-		CStringGetTextDatum(synchronous_commit);
+		CStringGetTextDatum(synchr_commit);
 	values[Anum_pg_subscription_subpublications - 1] =
 		publicationListToArray(publications);
 
@@ -453,7 +453,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 			 * Get the table list from publisher and build local table status
 			 * info.
 			 */
-			tables = fetch_table_list(wrconn, publications);
+			tables = fetch_table_list(WalReceiverConnection, publications);
 			foreach(lc, tables)
 			{
 				RangeVar   *rv = (RangeVar *) lfirst(lc);
@@ -478,7 +478,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 			{
 				Assert(slotname);
 
-				walrcv_create_slot(wrconn, slotname, false,
+				walrcv_create_slot(WalReceiverConnection, slotname, false,
 								   CRS_NOEXPORT_SNAPSHOT, &lsn);
 				ereport(NOTICE,
 						(errmsg("created replication slot \"%s\" on publisher",
@@ -487,7 +487,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 		}
 		PG_FINALLY();
 		{
-			walrcv_disconnect(wrconn);
+			walrcv_disconnect(WalReceiverConnection);
 		}
 		PG_END_TRY();
 	}
@@ -524,16 +524,16 @@ AlterSubscription_refresh(Subscription *sub, bool copy_data)
 	load_file("libpqwalreceiver", false);
 
 	/* Try to connect to the publisher. */
-	wrconn = walrcv_connect(sub->conninfo, true, sub->name, &err);
-	if (!wrconn)
+	WalReceiverConnection = walrcv_connect(sub->conninfo, true, sub->name, &err);
+	if (!WalReceiverConnection)
 		ereport(ERROR,
 				(errmsg("could not connect to the publisher: %s", err)));
 
 	/* Get the table list from publisher. */
-	pubrel_names = fetch_table_list(wrconn, sub->publications);
+	pubrel_names = fetch_table_list(WalReceiverConnection, sub->publications);
 
 	/* We are done with the remote side, close connection. */
-	walrcv_disconnect(wrconn);
+	walrcv_disconnect(WalReceiverConnection);
 
 	/* Get local table list. */
 	subrel_states = GetSubscriptionRelations(sub->oid);
@@ -668,11 +668,11 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
 			{
 				char	   *slotname;
 				bool		slotname_given;
-				char	   *synchronous_commit;
+				char	   *synchr_commit;
 
 				parse_subscription_options(stmt->options, NULL, NULL, NULL,
 										   NULL, &slotname_given, &slotname,
-										   NULL, &synchronous_commit, NULL);
+										   NULL, &synchr_commit, NULL);
 
 				if (slotname_given)
 				{
@@ -690,10 +690,10 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
 					replaces[Anum_pg_subscription_subslotname - 1] = true;
 				}
 
-				if (synchronous_commit)
+				if (synchr_commit)
 				{
 					values[Anum_pg_subscription_subsynccommit - 1] =
-						CStringGetTextDatum(synchronous_commit);
+						CStringGetTextDatum(synchr_commit);
 					replaces[Anum_pg_subscription_subsynccommit - 1] = true;
 				}
 
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 9ff2832c00..29a3a7517d 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -2538,7 +2538,7 @@ ConnFree(Port *conn)
  * the global variable yet when this is called.
  */
 void
-ClosePostmasterPorts(bool am_syslogger)
+ClosePostmasterPorts(bool syslogger)
 {
 	int			i;
 
@@ -2567,7 +2567,7 @@ ClosePostmasterPorts(bool am_syslogger)
 	}
 
 	/* If using syslogger, close the read side of the pipe */
-	if (!am_syslogger)
+	if (!syslogger)
 	{
 #ifndef WIN32
 		if (syslogPipe[0] >= 0)
diff --git a/src/backend/replication/logical/launcher.c b/src/backend/replication/logical/launcher.c
index 4643af95fe..7fb7b4ad73 100644
--- a/src/backend/replication/logical/launcher.c
+++ b/src/backend/replication/logical/launcher.c
@@ -706,8 +706,8 @@ static void
 logicalrep_worker_onexit(int code, Datum arg)
 {
 	/* Disconnect gracefully from the remote side. */
-	if (wrconn)
-		walrcv_disconnect(wrconn);
+	if (WalReceiverConnection)
+		walrcv_disconnect(WalReceiverConnection);
 
 	logicalrep_worker_detach();
 
diff --git a/src/backend/replication/logical/tablesync.c b/src/backend/replication/logical/tablesync.c
index e01d18c3a1..28b89f9af4 100644
--- a/src/backend/replication/logical/tablesync.c
+++ b/src/backend/replication/logical/tablesync.c
@@ -288,7 +288,7 @@ process_syncing_tables_for_sync(XLogRecPtr current_lsn)
 								   MyLogicalRepWorker->relstate,
 								   MyLogicalRepWorker->relstate_lsn);
 
-		walrcv_endstreaming(wrconn, &tli);
+		walrcv_endstreaming(WalReceiverConnection, &tli);
 		finish_sync_worker();
 	}
 	else
@@ -584,7 +584,7 @@ copy_read_data(void *outbuf, int minread, int maxread)
 		for (;;)
 		{
 			/* Try read the data. */
-			len = walrcv_receive(wrconn, &buf, &fd);
+			len = walrcv_receive(WalReceiverConnection, &buf, &fd);
 
 			CHECK_FOR_INTERRUPTS();
 
@@ -658,7 +658,7 @@ fetch_remote_table_info(char *nspname, char *relname,
 					 "   AND c.relkind = 'r'",
 					 quote_literal_cstr(nspname),
 					 quote_literal_cstr(relname));
-	res = walrcv_exec(wrconn, cmd.data, 2, tableRow);
+	res = walrcv_exec(WalReceiverConnection, cmd.data, 2, tableRow);
 
 	if (res->status != WALRCV_OK_TUPLES)
 		ereport(ERROR,
@@ -694,9 +694,9 @@ fetch_remote_table_info(char *nspname, char *relname,
 					 "   AND a.attrelid = %u"
 					 " ORDER BY a.attnum",
 					 lrel->remoteid,
-					 (walrcv_server_version(wrconn) >= 120000 ? "AND a.attgenerated = ''" : ""),
+					 (walrcv_server_version(WalReceiverConnection) >= 120000 ? "AND a.attgenerated = ''" : ""),
 					 lrel->remoteid);
-	res = walrcv_exec(wrconn, cmd.data, 4, attrRow);
+	res = walrcv_exec(WalReceiverConnection, cmd.data, 4, attrRow);
 
 	if (res->status != WALRCV_OK_TUPLES)
 		ereport(ERROR,
@@ -766,7 +766,7 @@ copy_table(Relation rel)
 	initStringInfo(&cmd);
 	appendStringInfo(&cmd, "COPY %s TO STDOUT",
 					 quote_qualified_identifier(lrel.nspname, lrel.relname));
-	res = walrcv_exec(wrconn, cmd.data, 0, NULL);
+	res = walrcv_exec(WalReceiverConnection, cmd.data, 0, NULL);
 	pfree(cmd.data);
 	if (res->status != WALRCV_OK_COPY_OUT)
 		ereport(ERROR,
@@ -833,8 +833,8 @@ LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
 	 * application_name, so that it is different from the main apply worker,
 	 * so that synchronous replication can distinguish them.
 	 */
-	wrconn = walrcv_connect(MySubscription->conninfo, true, slotname, &err);
-	if (wrconn == NULL)
+	WalReceiverConnection = walrcv_connect(MySubscription->conninfo, true, slotname, &err);
+	if (WalReceiverConnection == NULL)
 		ereport(ERROR,
 				(errmsg("could not connect to the publisher: %s", err)));
 
@@ -879,7 +879,7 @@ LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
 				 * inside the transaction so that we can use the snapshot made
 				 * by the slot to get existing data.
 				 */
-				res = walrcv_exec(wrconn,
+				res = walrcv_exec(WalReceiverConnection,
 								  "BEGIN READ ONLY ISOLATION LEVEL "
 								  "REPEATABLE READ", 0, NULL);
 				if (res->status != WALRCV_OK_COMMAND)
@@ -896,14 +896,14 @@ LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
 				 * that is consistent with the lsn used by the slot to start
 				 * decoding.
 				 */
-				walrcv_create_slot(wrconn, slotname, true,
+				walrcv_create_slot(WalReceiverConnection, slotname, true,
 								   CRS_USE_SNAPSHOT, origin_startpos);
 
 				PushActiveSnapshot(GetTransactionSnapshot());
 				copy_table(rel);
 				PopActiveSnapshot();
 
-				res = walrcv_exec(wrconn, "COMMIT", 0, NULL);
+				res = walrcv_exec(WalReceiverConnection, "COMMIT", 0, NULL);
 				if (res->status != WALRCV_OK_COMMAND)
 					ereport(ERROR,
 							(errmsg("table copy could not finish transaction on publisher"),
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index ced0d191c2..4f5400c369 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -97,7 +97,7 @@ typedef struct SlotErrCallbackArg
 static MemoryContext ApplyMessageContext = NULL;
 MemoryContext ApplyContext = NULL;
 
-WalReceiverConn *wrconn = NULL;
+WalReceiverConn *WalReceiverConnection = NULL;
 
 Subscription *MySubscription = NULL;
 bool		MySubscriptionValid = false;
@@ -1132,7 +1132,7 @@ LogicalRepApplyLoop(XLogRecPtr last_received)
 
 		MemoryContextSwitchTo(ApplyMessageContext);
 
-		len = walrcv_receive(wrconn, &buf, &fd);
+		len = walrcv_receive(WalReceiverConnection, &buf, &fd);
 
 		if (len != 0)
 		{
@@ -1212,7 +1212,7 @@ LogicalRepApplyLoop(XLogRecPtr last_received)
 					MemoryContextReset(ApplyMessageContext);
 				}
 
-				len = walrcv_receive(wrconn, &buf, &fd);
+				len = walrcv_receive(WalReceiverConnection, &buf, &fd);
 			}
 		}
 
@@ -1242,7 +1242,7 @@ LogicalRepApplyLoop(XLogRecPtr last_received)
 		{
 			TimeLineID	tli;
 
-			walrcv_endstreaming(wrconn, &tli);
+			walrcv_endstreaming(WalReceiverConnection, &tli);
 			break;
 		}
 
@@ -1408,7 +1408,7 @@ send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
 		 (uint32) (flushpos >> 32), (uint32) flushpos
 		);
 
-	walrcv_send(wrconn, reply_message->data, reply_message->len);
+	walrcv_send(WalReceiverConnection, reply_message->data, reply_message->len);
 
 	if (recvpos > last_recvpos)
 		last_recvpos = recvpos;
@@ -1714,9 +1714,9 @@ ApplyWorkerMain(Datum main_arg)
 		origin_startpos = replorigin_session_get_progress(false);
 		CommitTransactionCommand();
 
-		wrconn = walrcv_connect(MySubscription->conninfo, true, MySubscription->name,
+		WalReceiverConnection = walrcv_connect(MySubscription->conninfo, true, MySubscription->name,
 								&err);
-		if (wrconn == NULL)
+		if (WalReceiverConnection == NULL)
 			ereport(ERROR,
 					(errmsg("could not connect to the publisher: %s", err)));
 
@@ -1724,7 +1724,7 @@ ApplyWorkerMain(Datum main_arg)
 		 * We don't really use the output identify_system for anything but it
 		 * does some initializations on the upstream so let's still call it.
 		 */
-		(void) walrcv_identify_system(wrconn, &startpointTLI);
+		(void) walrcv_identify_system(WalReceiverConnection, &startpointTLI);
 
 	}
 
@@ -1744,7 +1744,7 @@ ApplyWorkerMain(Datum main_arg)
 	options.proto.logical.publication_names = MySubscription->publications;
 
 	/* Start normal logical streaming replication. */
-	walrcv_startstreaming(wrconn, &options);
+	walrcv_startstreaming(WalReceiverConnection, &options);
 
 	/* Run the main loop. */
 	LogicalRepApplyLoop(origin_startpos);
diff --git a/src/backend/replication/walreceiver.c b/src/backend/replication/walreceiver.c
index c1e439adb4..f9d3a9feb9 100644
--- a/src/backend/replication/walreceiver.c
+++ b/src/backend/replication/walreceiver.c
@@ -78,7 +78,7 @@ int			wal_receiver_timeout;
 bool		hot_standby_feedback;
 
 /* libpqwalreceiver connection */
-static WalReceiverConn *wrconn = NULL;
+static WalReceiverConn *WalReceiverConnection = NULL;
 WalReceiverFunctionsType *WalReceiverFunctions = NULL;
 
 #define NAPTIME_PER_CYCLE 100	/* max sleep time between cycles (100ms) */
@@ -270,8 +270,8 @@ WalReceiverMain(void)
 	PG_SETMASK(&UnBlockSig);
 
 	/* Establish the connection to the primary for XLOG streaming */
-	wrconn = walrcv_connect(conninfo, false, cluster_name[0] ? cluster_name : "walreceiver", &err);
-	if (!wrconn)
+	WalReceiverConnection = walrcv_connect(conninfo, false, cluster_name[0] ? cluster_name : "walreceiver", &err);
+	if (!WalReceiverConnection)
 		ereport(ERROR,
 				(errmsg("could not connect to the primary server: %s", err)));
 
@@ -280,8 +280,8 @@ WalReceiverMain(void)
 	 * conninfo, for security. Also save host and port of the sender server
 	 * this walreceiver is connected to.
 	 */
-	tmp_conninfo = walrcv_get_conninfo(wrconn);
-	walrcv_get_senderinfo(wrconn, &sender_host, &sender_port);
+	tmp_conninfo = walrcv_get_conninfo(WalReceiverConnection);
+	walrcv_get_senderinfo(WalReceiverConnection, &sender_host, &sender_port);
 	SpinLockAcquire(&walrcv->mutex);
 	memset(walrcv->conninfo, 0, MAXCONNINFO);
 	if (tmp_conninfo)
@@ -312,7 +312,7 @@ WalReceiverMain(void)
 		 * Check that we're connected to a valid server using the
 		 * IDENTIFY_SYSTEM replication command.
 		 */
-		primary_sysid = walrcv_identify_system(wrconn, &primaryTLI);
+		primary_sysid = walrcv_identify_system(WalReceiverConnection, &primaryTLI);
 
 		snprintf(standby_sysid, sizeof(standby_sysid), UINT64_FORMAT,
 				 GetSystemIdentifier());
@@ -362,7 +362,7 @@ WalReceiverMain(void)
 		options.slotname = slotname[0] != '\0' ? slotname : NULL;
 		options.proto.physical.startpointTLI = startpointTLI;
 		ThisTimeLineID = startpointTLI;
-		if (walrcv_startstreaming(wrconn, &options))
+		if (walrcv_startstreaming(WalReceiverConnection, &options))
 		{
 			if (first_stream)
 				ereport(LOG,
@@ -413,7 +413,7 @@ WalReceiverMain(void)
 				}
 
 				/* See if we can read data immediately */
-				len = walrcv_receive(wrconn, &buf, &wait_fd);
+				len = walrcv_receive(WalReceiverConnection, &buf, &wait_fd);
 				if (len != 0)
 				{
 					/*
@@ -444,7 +444,7 @@ WalReceiverMain(void)
 							endofwal = true;
 							break;
 						}
-						len = walrcv_receive(wrconn, &buf, &wait_fd);
+						len = walrcv_receive(WalReceiverConnection, &buf, &wait_fd);
 					}
 
 					/* Let the master know that we received some data. */
@@ -553,7 +553,7 @@ WalReceiverMain(void)
 			 * The backend finished streaming. Exit streaming COPY-mode from
 			 * our side, too.
 			 */
-			walrcv_endstreaming(wrconn, &primaryTLI);
+			walrcv_endstreaming(WalReceiverConnection, &primaryTLI);
 
 			/*
 			 * If the server had switched to a new timeline that we didn't
@@ -700,7 +700,7 @@ WalRcvFetchTimeLineHistoryFiles(TimeLineID first, TimeLineID last)
 					(errmsg("fetching timeline history file for timeline %u from primary server",
 							tli)));
 
-			walrcv_readtimelinehistoryfile(wrconn, tli, &fname, &content, &len);
+			walrcv_readtimelinehistoryfile(WalReceiverConnection, tli, &fname, &content, &len);
 
 			/*
 			 * Check that the filename on the master matches what we
@@ -751,8 +751,8 @@ WalRcvDie(int code, Datum arg)
 	SpinLockRelease(&walrcv->mutex);
 
 	/* Terminate the connection gracefully. */
-	if (wrconn != NULL)
-		walrcv_disconnect(wrconn);
+	if (WalReceiverConnection != NULL)
+		walrcv_disconnect(WalReceiverConnection);
 
 	/* Wake up the startup process to notice promptly that we're gone */
 	WakeupRecovery();
@@ -1114,7 +1114,7 @@ XLogWalRcvSendReply(bool force, bool requestReply)
 		 (uint32) (applyPtr >> 32), (uint32) applyPtr,
 		 requestReply ? " (reply requested)" : "");
 
-	walrcv_send(wrconn, reply_message.data, reply_message.len);
+	walrcv_send(WalReceiverConnection, reply_message.data, reply_message.len);
 }
 
 /*
@@ -1230,7 +1230,7 @@ XLogWalRcvSendHSFeedback(bool immed)
 	pq_sendint32(&reply_message, xmin_epoch);
 	pq_sendint32(&reply_message, catalog_xmin);
 	pq_sendint32(&reply_message, catalog_xmin_epoch);
-	walrcv_send(wrconn, reply_message.data, reply_message.len);
+	walrcv_send(WalReceiverConnection, reply_message.data, reply_message.len);
 	if (TransactionIdIsValid(xmin) || TransactionIdIsValid(catalog_xmin))
 		master_has_standby_xmin = true;
 	else
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index 8b2a2be1c0..e06e9a3015 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -146,7 +146,7 @@ static XLogRecPtr sendTimeLineValidUpto = InvalidXLogRecPtr;
  * How far have we sent WAL already? This is also advertised in
  * MyWalSnd->sentPtr.  (Actually, this is the next WAL location to send.)
  */
-static XLogRecPtr sentPtr = 0;
+static XLogRecPtr WalSentPtr = 0;
 
 /* Buffers for constructing outgoing messages and processing reply messages. */
 static StringInfoData output_message;
@@ -683,11 +683,11 @@ StartReplication(StartReplicationCmd *cmd)
 		}
 
 		/* Start streaming from the requested point */
-		sentPtr = cmd->startpoint;
+		WalSentPtr = cmd->startpoint;
 
 		/* Initialize shared memory status, too */
 		SpinLockAcquire(&MyWalSnd->mutex);
-		MyWalSnd->sentPtr = sentPtr;
+		MyWalSnd->sentPtr = WalSentPtr;
 		SpinLockRelease(&MyWalSnd->mutex);
 
 		SyncRepInitConfig();
@@ -1135,9 +1135,9 @@ StartLogicalReplication(StartReplicationCmd *cmd)
 
 	/*
 	 * Report the location after which we'll send out further commits as the
-	 * current sentPtr.
+	 * current WalSentPtr.
 	 */
-	sentPtr = MyReplicationSlot->data.confirmed_flush;
+	WalSentPtr = MyReplicationSlot->data.confirmed_flush;
 
 	/* Also update the sent position status in shared memory */
 	SpinLockAcquire(&MyWalSnd->mutex);
@@ -1390,8 +1390,8 @@ WalSndWaitForWal(XLogRecPtr loc)
 		 * possibly are waiting for a later location. So we send pings
 		 * containing the flush location every now and then.
 		 */
-		if (MyWalSnd->flush < sentPtr &&
-			MyWalSnd->write < sentPtr &&
+		if (MyWalSnd->flush < WalSentPtr &&
+			MyWalSnd->write < WalSentPtr &&
 			!waiting_for_ping_response)
 		{
 			WalSndKeepalive(false);
@@ -1848,7 +1848,7 @@ ProcessStandbyReplyMessage(void)
 	 * until more WAL traffic arrives.
 	 */
 	clearLagTimes = false;
-	if (applyPtr == sentPtr)
+	if (applyPtr == WalSentPtr)
 	{
 		if (fullyAppliedLastTime)
 			clearLagTimes = true;
@@ -2607,11 +2607,11 @@ XLogSendPhysical(void)
 	 * terminated at a WAL page boundary, the valid portion of the timeline
 	 * might end in the middle of a WAL record. We might've already sent the
 	 * first half of that partial WAL record to the cascading standby, so that
-	 * sentPtr > sendTimeLineValidUpto. That's OK; the cascading standby can't
+	 * WalSentPtr > sendTimeLineValidUpto. That's OK; the cascading standby can't
 	 * replay the partial WAL record either, so it can still follow our
 	 * timeline switch.
 	 */
-	if (sendTimeLineIsHistoric && sendTimeLineValidUpto <= sentPtr)
+	if (sendTimeLineIsHistoric && sendTimeLineValidUpto <= WalSentPtr)
 	{
 		/* close the current file. */
 		if (sendSeg->ws_file >= 0)
@@ -2626,13 +2626,13 @@ XLogSendPhysical(void)
 
 		elog(DEBUG1, "walsender reached end of timeline at %X/%X (sent up to %X/%X)",
 			 (uint32) (sendTimeLineValidUpto >> 32), (uint32) sendTimeLineValidUpto,
-			 (uint32) (sentPtr >> 32), (uint32) sentPtr);
+			 (uint32) (WalSentPtr >> 32), (uint32) WalSentPtr);
 		return;
 	}
 
 	/* Do we have any work to do? */
-	Assert(sentPtr <= SendRqstPtr);
-	if (SendRqstPtr <= sentPtr)
+	Assert(WalSentPtr <= SendRqstPtr);
+	if (SendRqstPtr <= WalSentPtr)
 	{
 		WalSndCaughtUp = true;
 		return;
@@ -2649,7 +2649,7 @@ XLogSendPhysical(void)
 	 * page boundary is always a safe cut-off point. We also assume that
 	 * SendRqstPtr never points to the middle of a WAL record.
 	 */
-	startptr = sentPtr;
+	startptr = WalSentPtr;
 	endptr = startptr;
 	endptr += MAX_SEND_SIZE;
 
@@ -2743,14 +2743,14 @@ retry:
 
 	pq_putmessage_noblock('d', output_message.data, output_message.len);
 
-	sentPtr = endptr;
+	WalSentPtr = endptr;
 
 	/* Update shared memory status */
 	{
 		WalSnd	   *walsnd = MyWalSnd;
 
 		SpinLockAcquire(&walsnd->mutex);
-		walsnd->sentPtr = sentPtr;
+		walsnd->sentPtr = WalSentPtr;
 		SpinLockRelease(&walsnd->mutex);
 	}
 
@@ -2760,7 +2760,7 @@ retry:
 		char		activitymsg[50];
 
 		snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
-				 (uint32) (sentPtr >> 32), (uint32) sentPtr);
+				 (uint32) (WalSentPtr >> 32), (uint32) WalSentPtr);
 		set_ps_display(activitymsg, false);
 	}
 }
@@ -2804,7 +2804,7 @@ XLogSendLogical(void)
 		 */
 		LogicalDecodingProcessRecord(logical_decoding_ctx, logical_decoding_ctx->reader);
 
-		sentPtr = logical_decoding_ctx->reader->EndRecPtr;
+		WalSentPtr = logical_decoding_ctx->reader->EndRecPtr;
 	}
 
 	/* Set flag if we're caught up. */
@@ -2824,7 +2824,7 @@ XLogSendLogical(void)
 		WalSnd	   *walsnd = MyWalSnd;
 
 		SpinLockAcquire(&walsnd->mutex);
-		walsnd->sentPtr = sentPtr;
+		walsnd->sentPtr = WalSentPtr;
 		SpinLockRelease(&walsnd->mutex);
 	}
 }
@@ -2854,7 +2854,7 @@ WalSndDone(WalSndSendDataCallback send_data)
 	replicatedPtr = XLogRecPtrIsInvalid(MyWalSnd->flush) ?
 		MyWalSnd->write : MyWalSnd->flush;
 
-	if (WalSndCaughtUp && sentPtr == replicatedPtr &&
+	if (WalSndCaughtUp && WalSentPtr == replicatedPtr &&
 		!pq_is_send_pending())
 	{
 		/* Inform the standby that XLOG streaming is done */
@@ -3370,7 +3370,7 @@ WalSndKeepalive(bool requestReply)
 	/* construct the message... */
 	resetStringInfo(&output_message);
 	pq_sendbyte(&output_message, 'k');
-	pq_sendint64(&output_message, sentPtr);
+	pq_sendint64(&output_message, WalSentPtr);
 	pq_sendint64(&output_message, GetCurrentTimestamp());
 	pq_sendbyte(&output_message, requestReply ? 1 : 0);
 
diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index 709bbaaf5a..63097739c4 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -508,16 +508,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		ndays = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + ndays;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((ndays >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -532,16 +532,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		ndays = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - ndays;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((ndays >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -1810,18 +1810,18 @@ interval_time(PG_FUNCTION_ARGS)
 {
 	Interval   *span = PG_GETARG_INTERVAL_P(0);
 	TimeADT		result;
-	int64		days;
+	int64		ndays;
 
 	result = span->time;
 	if (result >= USECS_PER_DAY)
 	{
-		days = result / USECS_PER_DAY;
-		result -= days * USECS_PER_DAY;
+		ndays = result / USECS_PER_DAY;
+		result -= ndays * USECS_PER_DAY;
 	}
 	else if (result < 0)
 	{
-		days = (-result + USECS_PER_DAY - 1) / USECS_PER_DAY;
-		result += days * USECS_PER_DAY;
+		ndays = (-result + USECS_PER_DAY - 1) / USECS_PER_DAY;
+		result += ndays * USECS_PER_DAY;
 	}
 
 	PG_RETURN_TIMEADT(result);
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 31bdb37c55..2f721ee67e 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -1500,9 +1500,9 @@ Datum
 make_interval(PG_FUNCTION_ARGS)
 {
 	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
+	int32		nmonths = PG_GETARG_INT32(1);
 	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
+	int32		ndays = PG_GETARG_INT32(3);
 	int32		hours = PG_GETARG_INT32(4);
 	int32		mins = PG_GETARG_INT32(5);
 	double		secs = PG_GETARG_FLOAT8(6);
@@ -1518,8 +1518,8 @@ make_interval(PG_FUNCTION_ARGS)
 				 errmsg("interval out of range")));
 
 	result = (Interval *) palloc(sizeof(Interval));
-	result->month = years * MONTHS_PER_YEAR + months;
-	result->day = weeks * 7 + days;
+	result->month = years * MONTHS_PER_YEAR + nmonths;
+	result->day = weeks * 7 + ndays;
 
 	secs = rint(secs * USECS_PER_SEC);
 	result->time = hours * ((int64) SECS_PER_HOUR * USECS_PER_SEC) +
@@ -2343,22 +2343,22 @@ interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
 	int64		dayfraction;
-	int64		days;
+	int64		ndays;
 
 	/*
 	 * Separate time field into days and dayfraction, then add the month and
 	 * day fields to the days part.  We cannot overflow int64 days here.
 	 */
 	dayfraction = interval->time % USECS_PER_DAY;
-	days = interval->time / USECS_PER_DAY;
-	days += interval->month * INT64CONST(30);
-	days += interval->day;
+	ndays = interval->time / USECS_PER_DAY;
+	ndays += interval->month * INT64CONST(30);
+	ndays += interval->day;
 
 	/* Widen dayfraction to 128 bits */
 	span = int64_to_int128(dayfraction);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, ndays, USECS_PER_DAY);
 
 	return span;
 }
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 1f6d8939be..2dcd4f4151 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -266,10 +266,10 @@ static void trapsig(int signum);
 static void check_ok(void);
 static char *escape_quotes(const char *src);
 static char *escape_quotes_bki(const char *src);
-static int	locale_date_order(const char *locale);
-static void check_locale_name(int category, const char *locale,
+static int	locale_date_order(const char *locale_name);
+static void check_locale_name(int category, const char *locale_name,
 							  char **canonname);
-static bool check_locale_encoding(const char *locale, int encoding);
+static bool check_locale_encoding(const char *locale_name, int encoding);
 static void setlocales(void);
 static void usage(const char *progname);
 void		setup_pgdata(void);
@@ -631,7 +631,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user_name;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -644,9 +644,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user_name = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user_name);
 }
 
 static char *
@@ -864,17 +864,17 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *file;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+        file = fopen(path, PG_BINARY_W);
+	if (file == NULL)
 	{
 		pg_log_error("could not open file \"%s\" for writing: %m", path);
 		exit(1);
 	}
-	if (fclose(conf_file))
+	if (fclose(file))
 	{
 		pg_log_error("could not write file \"%s\": %m", path);
 		exit(1);
@@ -2107,7 +2107,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *locale_name)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2125,7 +2125,7 @@ locale_date_order(const char *locale)
 		return result;
 	save = pg_strdup(save);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, locale_name);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2170,7 +2170,7 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *locale_name, char **canonname)
 {
 	char	   *save;
 	char	   *res;
@@ -2193,7 +2193,7 @@ check_locale_name(int category, const char *locale, char **canonname)
 		locale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, locale_name);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2210,8 +2210,8 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
-			pg_log_error("invalid locale name \"%s\"", locale);
+		if (*locale_name)
+			pg_log_error("invalid locale name \"%s\"", locale_name);
 		else
 		{
 			/*
@@ -2234,11 +2234,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *locale_name, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(locale_name, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2393,22 +2393,22 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
+check_need_password(const char *authmethod_local, const char *authmethod_host)
 {
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+	if ((strcmp(authmethod_local, "md5") == 0 ||
+		 strcmp(authmethod_local, "password") == 0 ||
+		 strcmp(authmethod_local, "scram-sha-256") == 0) &&
+		(strcmp(authmethod_host, "md5") == 0 ||
+		 strcmp(authmethod_host, "password") == 0 ||
+		 strcmp(authmethod_host, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 	{
 		pg_log_error("must specify a password for the superuser to enable %s authentication",
-					 (strcmp(authmethodlocal, "md5") == 0 ||
-					  strcmp(authmethodlocal, "password") == 0 ||
-					  strcmp(authmethodlocal, "scram-sha-256") == 0)
-					 ? authmethodlocal
-					 : authmethodhost);
+					 (strcmp(authmethod_local, "md5") == 0 ||
+					  strcmp(authmethod_local, "password") == 0 ||
+					  strcmp(authmethod_local, "scram-sha-256") == 0)
+					 ? authmethod_local
+					 : authmethod_host);
 		exit(1);
 	}
 }
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index 19e21ab491..acc8fbfcc8 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -69,9 +69,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel wallevel)
 {
-	switch (wal_level)
+	switch (wallevel)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 65f9fb4c0a..80715bae01 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -742,7 +742,7 @@ read_post_opts(void)
  * waiting for the server to start up, the server launch is aborted.
  */
 static void
-trap_sigint_during_startup(int sig)
+trap_sigint_during_startup(int signal)
 {
 	if (postmasterPID != -1)
 	{
@@ -760,18 +760,18 @@ trap_sigint_during_startup(int sig)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *argv_0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(argv_0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(argv_0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c
index 37432a6f4b..ef5cd5c60c 100644
--- a/src/bin/pg_dump/common.c
+++ b/src/bin/pg_dump/common.c
@@ -64,10 +64,10 @@ static int	numExtensions;
 static ExtensionMemberId *extmembers;
 static int	numextmembers;
 
-static void flagInhTables(Archive *fout, TableInfo *tbinfo, int numTables,
+static void flagInhTables(Archive *fout, TableInfo *tbinfo, int nTables,
 						  InhInfo *inhinfo, int numInherits);
-static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int numTables);
-static void flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables);
+static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int nTables);
+static void flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int nTables);
 static DumpableObject **buildIndexArray(void *objArray, int numObjs,
 										Size objSize);
 static int	DOCatalogIdCompare(const void *p1, const void *p2);
@@ -270,14 +270,14 @@ getSchemaData(Archive *fout, int *numTablesPtr)
  * modifies tblinfo
  */
 static void
-flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
+flagInhTables(Archive *fout, TableInfo *tblinfo, int nTables,
 			  InhInfo *inhinfo, int numInherits)
 {
 	DumpOptions *dopt = fout->dopt;
 	int			i,
 				j;
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < nTables; i++)
 	{
 		bool		find_parents = true;
 		bool		mark_parents = true;
@@ -329,7 +329,7 @@ flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
  *	 appropriate dependency links.
  */
 static void
-flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
+flagInhIndexes(Archive *fout, TableInfo tblinfo[], int nTables)
 {
 	int			i,
 				j,
@@ -339,7 +339,7 @@ flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
 	parentIndexArray = (DumpableObject ***)
 		pg_malloc0(getMaxDumpId() * sizeof(DumpableObject **));
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < nTables; i++)
 	{
 		TableInfo  *parenttbl;
 		IndexAttachInfo *attachinfo;
@@ -436,13 +436,13 @@ flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
  * modifies tblinfo
  */
 static void
-flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables)
+flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int nTables)
 {
 	int			i,
 				j,
 				k;
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < nTables; i++)
 	{
 		TableInfo  *tbinfo = &(tblinfo[i]);
 		int			numParents;
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 08658c8e86..ac33da02a9 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -155,11 +155,11 @@ static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
 static void expand_schema_name_patterns(Archive *fout,
 										SimpleStringList *patterns,
 										SimpleOidList *oids,
-										bool strict_names);
+										bool is_strict_names);
 static void expand_table_name_patterns(Archive *fout,
 									   SimpleStringList *patterns,
 									   SimpleOidList *oids,
-									   bool strict_names);
+									   bool is_strict_names);
 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
@@ -1293,7 +1293,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool is_strict_names)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1318,7 +1318,7 @@ expand_schema_name_patterns(Archive *fout,
 							  false, NULL, "n.nspname", NULL, NULL);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (is_strict_names && PQntuples(res) == 0)
 			fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1341,7 +1341,7 @@ expand_schema_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names)
+						   bool is_strict_names)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1383,7 +1383,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (is_strict_names && PQntuples(res) == 0)
 			fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 2e286f6339..7fb590ffb8 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -738,9 +738,9 @@ GuessControlValues(void)
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool guessed_control)
 {
-	if (guessed)
+	if (guessed_control)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 2ca1608bd2..0023c67938 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -91,7 +91,7 @@ static void signal_cleanup(int sig);
 #ifdef HAVE_FSYNC_WRITETHROUGH
 static int	pg_fsync_writethrough(int fd);
 #endif
-static void print_elapse(struct timeval start_t, struct timeval stop_t, int ops);
+static void print_elapse(struct timeval startt, struct timeval stopt, int ops);
 
 #define die(msg) do { pg_log_error("%s: %m", _(msg)); exit(1); } while(0)
 
@@ -576,10 +576,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval startt, struct timeval stopt, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-	(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stopt.tv_sec - startt.tv_sec) +
+	(stopt.tv_usec - startt.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
diff --git a/src/include/access/xlogreader.h b/src/include/access/xlogreader.h
index 0193611b7f..d8991d1a79 100644
--- a/src/include/access/xlogreader.h
+++ b/src/include/access/xlogreader.h
@@ -209,7 +209,7 @@ struct XLogReaderState
 };
 
 /* Get a new XLogReader */
-extern XLogReaderState *XLogReaderAllocate(int wal_segment_size,
+extern XLogReaderState *XLogReaderAllocate(int wallog_segment_size,
 										   const char *waldir,
 										   XLogPageReadCB pagereadfunc,
 										   void *private_data);
diff --git a/src/include/replication/worker_internal.h b/src/include/replication/worker_internal.h
index 05f4936419..132b4199e8 100644
--- a/src/include/replication/worker_internal.h
+++ b/src/include/replication/worker_internal.h
@@ -60,7 +60,7 @@ typedef struct LogicalRepWorker
 extern MemoryContext ApplyContext;
 
 /* libpqreceiver connection */
-extern struct WalReceiverConn *wrconn;
+extern struct WalReceiverConn *WalReceiverConnection;
 
 /* Worker and subscription objects. */
 extern Subscription *MySubscription;
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index a29f530327..7568d1c1a9 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -73,7 +73,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(char *name, char *connection)
+add_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *new;
 
@@ -87,16 +87,16 @@ add_descriptor(char *name, char *connection)
 	strcpy(new->name, name);
 	if (connection)
 	{
-		new->connection = mm_alloc(strlen(connection) + 1);
-		strcpy(new->connection, connection);
+		new->connection = mm_alloc(strlen(conn_str) + 1);
+		strcpy(new->connection, conn_str);
 	}
 	else
-		new->connection = connection;
+		new->connection = conn_str;
 	descriptors = new;
 }
 
 void
-drop_descriptor(char *name, char *connection)
+drop_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -108,9 +108,9 @@ drop_descriptor(char *name, char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				if (i->connection)
@@ -126,7 +126,7 @@ drop_descriptor(char *name, char *connection)
 
 struct descriptor
 		   *
-lookup_descriptor(char *name, char *connection)
+lookup_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *i;
 
@@ -137,9 +137,9 @@ lookup_descriptor(char *name, char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
 		}
 	}
#39John W Higgins
wishdev@gmail.com
In reply to: Ranier Vilela (#38)
Re: [Proposal] Level4 Warnings show many shadow vars

On Tue, Dec 10, 2019 at 5:21 AM Ranier Vilela <ranier_gyn@hotmail.com>
wrote:

New version the global patch, with the considerations.
Unfortunately WalReceiverConn cannot be used because it is currently the
typedef name for the structure.
I switched to WalReceiverConnection, it was long but it looks good.
RedoRecPtr proper name has no consensus yet, so it was still
lastRedoRecPtr.

For someone that expounds consistency - this patch is the furthest thing
from it.

In some places names are randomly changed to have an underscore
(authmethodlocal to authmethod_local with the obvious inconsistency as
well) - in some places names are changed to remove underscores (stop_t to
stopt). Some places random letters are added (checkPoint to xcheckPoint)
some places perfectly good names are truncated (conf_file to file).

Random places remove perfectly good prefixes and replace with single
letters (numTables to nTables)

Random places switch from lower case names to upper case names (sentPtr to
WalSentPtr) most places leave lower case names (days to ndays).

Please at least be consistent within the patch itself.....

John W Higgins

#40Ranier Vilela
ranier_gyn@hotmail.com
In reply to: John W Higgins (#39)
RE: [Proposal] Level4 Warnings show many shadow vars

De: John W Higgins <wishdev@gmail.com>
Enviado: terça-feira, 10 de dezembro de 2019 15:58

For someone that expounds consistency - this patch is the furthest thing from it.
In some places names are randomly changed to have an underscore >(authmethodlocal to authmethod_local with the obvious inconsistency as well) - >in some places names are changed to remove underscores (stop_t to stopt). >Some places random letters are added (checkPoint to xcheckPoint) some places >perfectly good names are truncated (conf_file to file).

The first purpose of the patch was to remove collisions from shadow global variable names.
The second was not to change the semantics of variable names, hence the use of x or putting or remove underscore.
But I agree with you that the choice of names can improve.
xcheckpoint sounds ugly.
stopt sounds ugly too.

Random places remove perfectly good prefixes and replace with single letters >(numTables to nTables)

numTables already a global variable name.
nTables It seems very reasonable to me to contain the number of tables.

Random places switch from lower case names to upper case names (sentPtr to >WalSentPtr) most places leave lower case names (days to ndays).

again senPtr already a global variable name.
Well, I tried to follow the local source style a little, since the project does not have a default for global names.
There we have some WalSntCtl por example.

ndays sounds very good to me for number of days.

Please at least be consistent within the patch itself.....

I'm trying.

regards,
Ranier Vilela

#41Stephen Frost
sfrost@snowman.net
In reply to: Ranier Vilela (#40)
Re: [Proposal] Level4 Warnings show many shadow vars

Greetings,

* Ranier Vilela (ranier_gyn@hotmail.com) wrote:

For someone that expounds consistency - this patch is the furthest thing from it.
In some places names are randomly changed to have an underscore >(authmethodlocal to authmethod_local with the obvious inconsistency as well) - >in some places names are changed to remove underscores (stop_t to stopt). >Some places random letters are added (checkPoint to xcheckPoint) some places >perfectly good names are truncated (conf_file to file).

The first purpose of the patch was to remove collisions from shadow global variable names.

There's multiple ways to get there though and I think what you're seeing
is that the "just change it to something else" answer isn't necessairly
going to be viewed as an improvement (or, at least, not enough of an
improvement to accept the cost of the change).

The second was not to change the semantics of variable names, hence the use of x or putting or remove underscore.

Why not change the variables? Changes that also improve the code itself
along with eliminating the shadowing of the global variable are going to
be a lot easier to be accepted.

Random places remove perfectly good prefixes and replace with single letters >(numTables to nTables)

numTables already a global variable name.

Sure, but have you looked at how it's used? Instead of just renaming
the numTables variables in the functions that accept it- could those
variables just be removed instead of changing their name to make it look
like they're something different when they aren't actually different?

I've only spent a bit of time looking at it, but it sure looks like the
variables could just be removed, and doing so doesn't break the
regression tests, which supports the idea that maybe there's a better
way to deal with those particular variables rather than renaming them.

Another approach to consider might be to move some global variables into
structures that are then global with better names to indicate that's
what they are.

In short, a hack-and-slash patch that doesn't really spend much time
considering the changes beyond "let's just change these to be different
to avoid shadowing globals" isn't really a good way to go about
addressing these cases and has a good chance of making things more
confusing, not less.

Thanks,

Stephen

#42Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Stephen Frost (#41)
RE: [Proposal] Level4 Warnings show many shadow vars

De: Stephen Frost
Enviadas: Terça-feira, 10 de Dezembro de 2019 17:52

There's multiple ways to get there though and I think what you're seeing
is that the "just change it to something else" answer isn't necessairly
going to be viewed as an improvement (or, at least, not enough of an
improvement to accept the cost of the change).

Well, I was trying to apply another non-implied rule, "break nothing".

Why not change the variables? Changes that also improve the code itself
along with eliminating the shadowing of the global variable are going to
be a lot easier to be accepted.

Contrary to what I was initially thinking, it seems to me that changing the names of global variables is more acceptable to the people of the project.

Sure, but have you looked at how it's used? Instead of just renaming
the numTables variables in the functions that accept it- could those
variables just be removed instead of changing their name to make it look
like they're something different when they aren't actually different?

No. I didn't look.

I've only spent a bit of time looking at it, but it sure looks like the
variables could just be removed, and doing so doesn't break the
regression tests, which supports the idea that maybe there's a better
way to deal with those particular variables rather than renaming them.
Another approach to consider might be to move some global variables into
structures that are then global with better names to indicate that's
what they are.

It does not seem reasonable to me what you are asking.
Because as I was told here and I agree in part. I do not have the necessary knowledge of structures and logic to propose big changes.
For the work I set out to, find bugs and make minor performance improvements, I believe, can contribute safely and without ruining anything.
By just changing the names of variables to something consistent and readable, the goal will be done without break anything.
Who is best to make these changes, are the authors and reviewers. Once we no longer have the problem of shadow variables, we can turn on the alert without breaking automatic compilation, as Tom Lane is concerned.
That's why I'd like to fix all collisions of variables, even the dumbest.

In short, a hack-and-slash patch that doesn't really spend much time
considering the changes beyond "let's just change these to be different
to avoid shadowing globals" isn't really a good way to go about
addressing these cases and has a good chance of making things more
confusing, not less.

This is totally contrary to what I think about it.

regards,
Ranier Vilela

#43Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Ranier Vilela (#38)
1 attachment(s)
RE: [Proposal] Level4 Warnings show many shadow vars

New version the global patch unshadow.
* names more consistent and readable.
* without big changes.
* goal,, unshadow all global variables, only, even the simplest.

regards,
Ranier Vilela

Attachments:

shadow_global_v4.patchtext/x-patch; name=shadow_global_v4.patchDownload
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 6bc1a6b46d..a496727e34 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -892,8 +892,8 @@ static int	emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
 static void XLogFileClose(void);
 static void PreallocXlogFiles(XLogRecPtr endptr);
 static void RemoveTempXlogFiles(void);
-static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
-static void RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
+static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr);
+static void RemoveXlogFile(const char *segname, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr);
 static void UpdateLastRemovedPtr(char *filename);
 static void ValidateXLOGDirectoryStructure(void);
 static void CleanupBackupHistory(void);
@@ -2299,7 +2299,7 @@ assign_checkpoint_completion_target(double newval, void *extra)
  * XLOG segments? Returns the highest segment that should be preallocated.
  */
 static XLogSegNo
-XLOGfileslop(XLogRecPtr RedoRecPtr)
+XLOGfileslop(XLogRecPtr lastRedoRecPtr)
 {
 	XLogSegNo	minSegNo;
 	XLogSegNo	maxSegNo;
@@ -2311,9 +2311,9 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	 * correspond to. Always recycle enough segments to meet the minimum, and
 	 * remove enough segments to stay below the maximum.
 	 */
-	minSegNo = RedoRecPtr / wal_segment_size +
+	minSegNo = lastRedoRecPtr / wal_segment_size +
 		ConvertToXSegs(min_wal_size_mb, wal_segment_size) - 1;
-	maxSegNo = RedoRecPtr / wal_segment_size +
+	maxSegNo = lastRedoRecPtr / wal_segment_size +
 		ConvertToXSegs(max_wal_size_mb, wal_segment_size) - 1;
 
 	/*
@@ -2328,7 +2328,7 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	/* add 10% for good measure. */
 	distance *= 1.10;
 
-	recycleSegNo = (XLogSegNo) ceil(((double) RedoRecPtr + distance) /
+	recycleSegNo = (XLogSegNo) ceil(((double) lastRedoRecPtr + distance) /
 									wal_segment_size);
 
 	if (recycleSegNo < minSegNo)
@@ -3949,12 +3949,12 @@ RemoveTempXlogFiles(void)
 /*
  * Recycle or remove all log files older or equal to passed segno.
  *
- * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * endptr is current (or recent) end of xlog, and lastRedoRecPtr is the
  * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
  */
 static void
-RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr)
 {
 	DIR		   *xldir;
 	struct dirent *xlde;
@@ -3997,7 +3997,7 @@ RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 				/* Update the last removed location in shared memory first */
 				UpdateLastRemovedPtr(xlde->d_name);
 
-				RemoveXlogFile(xlde->d_name, RedoRecPtr, endptr);
+				RemoveXlogFile(xlde->d_name, lastRedoRecPtr, endptr);
 			}
 		}
 	}
@@ -4071,14 +4071,14 @@ RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
 /*
  * Recycle or remove a log file that's no longer needed.
  *
- * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * endptr is current (or recent) end of xlog, and lastRedoRecPtr is the
  * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
- * If RedoRecPtr is not known, pass invalid, and the function will recycle,
+ * If lastRedoRecPtr is not known, pass invalid, and the function will recycle,
  * somewhat arbitrarily, 10 future segments.
  */
 static void
-RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveXlogFile(const char *segname, XLogRecPtr lastRedoRecPtr, XLogRecPtr endptr)
 {
 	char		path[MAXPGPATH];
 #ifdef WIN32
@@ -4094,10 +4094,10 @@ RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 		 * Initialize info about where to try to recycle to.
 		 */
 		XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
-		if (RedoRecPtr == InvalidXLogRecPtr)
+		if (lastRedoRecPtr == InvalidXLogRecPtr)
 			recycleSegNo = endlogSegNo + 10;
 		else
-			recycleSegNo = XLOGfileslop(RedoRecPtr);
+			recycleSegNo = XLOGfileslop(lastRedoRecPtr);
 	}
 	else
 		recycleSegNo = 0;		/* keep compiler quiet */
@@ -7158,11 +7158,11 @@ StartupXLOG(void)
 
 					if (info == XLOG_CHECKPOINT_SHUTDOWN)
 					{
-						CheckPoint	checkPoint;
+						CheckPoint	chkptrec;
 
-						memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
-						newTLI = checkPoint.ThisTimeLineID;
-						prevTLI = checkPoint.PrevTimeLineID;
+						memcpy(&chkptrec, XLogRecGetData(xlogreader), sizeof(CheckPoint));
+						newTLI = chkptrec.ThisTimeLineID;
+						prevTLI = chkptrec.PrevTimeLineID;
 					}
 					else if (info == XLOG_END_OF_RECOVERY)
 					{
diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c
index 67418b05f1..4915577e10 100644
--- a/src/backend/access/transam/xlogreader.c
+++ b/src/backend/access/transam/xlogreader.c
@@ -70,7 +70,7 @@ report_invalid_record(XLogReaderState *state, const char *fmt,...)
  * Returns NULL if the xlogreader couldn't be allocated.
  */
 XLogReaderState *
-XLogReaderAllocate(int wal_segment_size, const char *waldir,
+XLogReaderAllocate(int segment_size, const char *waldir,
 				   XLogPageReadCB pagereadfunc, void *private_data)
 {
 	XLogReaderState *state;
@@ -99,7 +99,7 @@ XLogReaderAllocate(int wal_segment_size, const char *waldir,
 	}
 
 	/* Initialize segment info. */
-	WALOpenSegmentInit(&state->seg, &state->segcxt, wal_segment_size,
+	WALOpenSegmentInit(&state->seg, &state->segcxt, segment_size,
 					   waldir);
 
 	state->read_page = pagereadfunc;
diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c
index 5408edcfc2..9931016fd7 100644
--- a/src/backend/commands/subscriptioncmds.c
+++ b/src/backend/commands/subscriptioncmds.c
@@ -57,7 +57,7 @@ static void
 parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 						   bool *enabled, bool *create_slot,
 						   bool *slot_name_given, char **slot_name,
-						   bool *copy_data, char **synchronous_commit,
+						   bool *copy_data, char **synchr_commit,
 						   bool *refresh)
 {
 	ListCell   *lc;
@@ -85,8 +85,8 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 	}
 	if (copy_data)
 		*copy_data = true;
-	if (synchronous_commit)
-		*synchronous_commit = NULL;
+	if (synchr_commit)
+		*synchr_commit = NULL;
 	if (refresh)
 		*refresh = true;
 
@@ -150,17 +150,17 @@ parse_subscription_options(List *options, bool *connect, bool *enabled_given,
 			*copy_data = defGetBoolean(defel);
 		}
 		else if (strcmp(defel->defname, "synchronous_commit") == 0 &&
-				 synchronous_commit)
+				 synchr_commit)
 		{
-			if (*synchronous_commit)
+			if (*synchr_commit)
 				ereport(ERROR,
 						(errcode(ERRCODE_SYNTAX_ERROR),
 						 errmsg("conflicting or redundant options")));
 
-			*synchronous_commit = defGetString(defel);
+			*synchr_commit = defGetString(defel);
 
 			/* Test if the given value is valid for synchronous_commit GUC. */
-			(void) set_config_option("synchronous_commit", *synchronous_commit,
+			(void) set_config_option("synchronous_commit", *synchr_commit,
 									 PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
 									 false, 0, false);
 		}
@@ -317,7 +317,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	bool		enabled_given;
 	bool		enabled;
 	bool		copy_data;
-	char	   *synchronous_commit;
+	char	   *synchr_commit;
 	char	   *conninfo;
 	char	   *slotname;
 	bool		slotname_given;
@@ -332,7 +332,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	 */
 	parse_subscription_options(stmt->options, &connect, &enabled_given,
 							   &enabled, &create_slot, &slotname_given,
-							   &slotname, &copy_data, &synchronous_commit,
+							   &slotname, &copy_data, &synchr_commit,
 							   NULL);
 
 	/*
@@ -375,8 +375,8 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 		slotname = stmt->subname;
 
 	/* The default for synchronous_commit of subscriptions is off. */
-	if (synchronous_commit == NULL)
-		synchronous_commit = "off";
+	if (synchr_commit == NULL)
+		synchr_commit = "off";
 
 	conninfo = stmt->conninfo;
 	publications = stmt->publication;
@@ -407,7 +407,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 	else
 		nulls[Anum_pg_subscription_subslotname - 1] = true;
 	values[Anum_pg_subscription_subsynccommit - 1] =
-		CStringGetTextDatum(synchronous_commit);
+		CStringGetTextDatum(synchr_commit);
 	values[Anum_pg_subscription_subpublications - 1] =
 		publicationListToArray(publications);
 
@@ -453,7 +453,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 			 * Get the table list from publisher and build local table status
 			 * info.
 			 */
-			tables = fetch_table_list(wrconn, publications);
+			tables = fetch_table_list(WalReceiverConnection, publications);
 			foreach(lc, tables)
 			{
 				RangeVar   *rv = (RangeVar *) lfirst(lc);
@@ -478,7 +478,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 			{
 				Assert(slotname);
 
-				walrcv_create_slot(wrconn, slotname, false,
+				walrcv_create_slot(WalReceiverConnection, slotname, false,
 								   CRS_NOEXPORT_SNAPSHOT, &lsn);
 				ereport(NOTICE,
 						(errmsg("created replication slot \"%s\" on publisher",
@@ -487,7 +487,7 @@ CreateSubscription(CreateSubscriptionStmt *stmt, bool isTopLevel)
 		}
 		PG_FINALLY();
 		{
-			walrcv_disconnect(wrconn);
+			walrcv_disconnect(WalReceiverConnection);
 		}
 		PG_END_TRY();
 	}
@@ -524,16 +524,16 @@ AlterSubscription_refresh(Subscription *sub, bool copy_data)
 	load_file("libpqwalreceiver", false);
 
 	/* Try to connect to the publisher. */
-	wrconn = walrcv_connect(sub->conninfo, true, sub->name, &err);
-	if (!wrconn)
+	WalReceiverConnection = walrcv_connect(sub->conninfo, true, sub->name, &err);
+	if (!WalReceiverConnection)
 		ereport(ERROR,
 				(errmsg("could not connect to the publisher: %s", err)));
 
 	/* Get the table list from publisher. */
-	pubrel_names = fetch_table_list(wrconn, sub->publications);
+	pubrel_names = fetch_table_list(WalReceiverConnection, sub->publications);
 
 	/* We are done with the remote side, close connection. */
-	walrcv_disconnect(wrconn);
+	walrcv_disconnect(WalReceiverConnection);
 
 	/* Get local table list. */
 	subrel_states = GetSubscriptionRelations(sub->oid);
@@ -668,11 +668,11 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
 			{
 				char	   *slotname;
 				bool		slotname_given;
-				char	   *synchronous_commit;
+				char	   *synchr_commit;
 
 				parse_subscription_options(stmt->options, NULL, NULL, NULL,
 										   NULL, &slotname_given, &slotname,
-										   NULL, &synchronous_commit, NULL);
+										   NULL, &synchr_commit, NULL);
 
 				if (slotname_given)
 				{
@@ -690,10 +690,10 @@ AlterSubscription(AlterSubscriptionStmt *stmt)
 					replaces[Anum_pg_subscription_subslotname - 1] = true;
 				}
 
-				if (synchronous_commit)
+				if (synchr_commit)
 				{
 					values[Anum_pg_subscription_subsynccommit - 1] =
-						CStringGetTextDatum(synchronous_commit);
+						CStringGetTextDatum(synchr_commit);
 					replaces[Anum_pg_subscription_subsynccommit - 1] = true;
 				}
 
diff --git a/src/backend/main/main.c b/src/backend/main/main.c
index a9edbfd4a4..9885a519ba 100644
--- a/src/backend/main/main.c
+++ b/src/backend/main/main.c
@@ -47,10 +47,10 @@
 const char *progname;
 
 
-static void startup_hacks(const char *progname);
+static void startup_hacks(const char *appname);
 static void init_locale(const char *categoryname, int category, const char *locale);
-static void help(const char *progname);
-static void check_root(const char *progname);
+static void help(const char *appname);
+static void check_root(const char *appname);
 
 
 /*
@@ -225,7 +225,7 @@ main(int argc, char *argv[])
  * without help.  Avoid adding more here, if you can.
  */
 static void
-startup_hacks(const char *progname)
+startup_hacks(const char *appname)
 {
 	/*
 	 * Windows-specific execution environment hacking.
@@ -305,10 +305,10 @@ init_locale(const char *categoryname, int category, const char *locale)
  * Messages emitted in write_console() do not exhibit this problem.
  */
 static void
-help(const char *progname)
+help(const char *appname)
 {
-	printf(_("%s is the PostgreSQL server.\n\n"), progname);
-	printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
+	printf(_("%s is the PostgreSQL server.\n\n"), appname);
+	printf(_("Usage:\n  %s [OPTION]...\n\n"), appname);
 	printf(_("Options:\n"));
 	printf(_("  -B NBUFFERS        number of shared buffers\n"));
 	printf(_("  -c NAME=VALUE      set run-time parameter\n"));
@@ -365,7 +365,7 @@ help(const char *progname)
 
 
 static void
-check_root(const char *progname)
+check_root(const char *appname)
 {
 #ifndef WIN32
 	if (geteuid() == 0)
@@ -388,7 +388,7 @@ check_root(const char *progname)
 	if (getuid() != geteuid())
 	{
 		write_stderr("%s: real and effective user IDs must match\n",
-					 progname);
+					 appname);
 		exit(1);
 	}
 #else							/* WIN32 */
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 9ff2832c00..29a3a7517d 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -2538,7 +2538,7 @@ ConnFree(Port *conn)
  * the global variable yet when this is called.
  */
 void
-ClosePostmasterPorts(bool am_syslogger)
+ClosePostmasterPorts(bool syslogger)
 {
 	int			i;
 
@@ -2567,7 +2567,7 @@ ClosePostmasterPorts(bool am_syslogger)
 	}
 
 	/* If using syslogger, close the read side of the pipe */
-	if (!am_syslogger)
+	if (!syslogger)
 	{
 #ifndef WIN32
 		if (syslogPipe[0] >= 0)
diff --git a/src/backend/replication/logical/launcher.c b/src/backend/replication/logical/launcher.c
index 4643af95fe..7fb7b4ad73 100644
--- a/src/backend/replication/logical/launcher.c
+++ b/src/backend/replication/logical/launcher.c
@@ -706,8 +706,8 @@ static void
 logicalrep_worker_onexit(int code, Datum arg)
 {
 	/* Disconnect gracefully from the remote side. */
-	if (wrconn)
-		walrcv_disconnect(wrconn);
+	if (WalReceiverConnection)
+		walrcv_disconnect(WalReceiverConnection);
 
 	logicalrep_worker_detach();
 
diff --git a/src/backend/replication/logical/tablesync.c b/src/backend/replication/logical/tablesync.c
index e01d18c3a1..28b89f9af4 100644
--- a/src/backend/replication/logical/tablesync.c
+++ b/src/backend/replication/logical/tablesync.c
@@ -288,7 +288,7 @@ process_syncing_tables_for_sync(XLogRecPtr current_lsn)
 								   MyLogicalRepWorker->relstate,
 								   MyLogicalRepWorker->relstate_lsn);
 
-		walrcv_endstreaming(wrconn, &tli);
+		walrcv_endstreaming(WalReceiverConnection, &tli);
 		finish_sync_worker();
 	}
 	else
@@ -584,7 +584,7 @@ copy_read_data(void *outbuf, int minread, int maxread)
 		for (;;)
 		{
 			/* Try read the data. */
-			len = walrcv_receive(wrconn, &buf, &fd);
+			len = walrcv_receive(WalReceiverConnection, &buf, &fd);
 
 			CHECK_FOR_INTERRUPTS();
 
@@ -658,7 +658,7 @@ fetch_remote_table_info(char *nspname, char *relname,
 					 "   AND c.relkind = 'r'",
 					 quote_literal_cstr(nspname),
 					 quote_literal_cstr(relname));
-	res = walrcv_exec(wrconn, cmd.data, 2, tableRow);
+	res = walrcv_exec(WalReceiverConnection, cmd.data, 2, tableRow);
 
 	if (res->status != WALRCV_OK_TUPLES)
 		ereport(ERROR,
@@ -694,9 +694,9 @@ fetch_remote_table_info(char *nspname, char *relname,
 					 "   AND a.attrelid = %u"
 					 " ORDER BY a.attnum",
 					 lrel->remoteid,
-					 (walrcv_server_version(wrconn) >= 120000 ? "AND a.attgenerated = ''" : ""),
+					 (walrcv_server_version(WalReceiverConnection) >= 120000 ? "AND a.attgenerated = ''" : ""),
 					 lrel->remoteid);
-	res = walrcv_exec(wrconn, cmd.data, 4, attrRow);
+	res = walrcv_exec(WalReceiverConnection, cmd.data, 4, attrRow);
 
 	if (res->status != WALRCV_OK_TUPLES)
 		ereport(ERROR,
@@ -766,7 +766,7 @@ copy_table(Relation rel)
 	initStringInfo(&cmd);
 	appendStringInfo(&cmd, "COPY %s TO STDOUT",
 					 quote_qualified_identifier(lrel.nspname, lrel.relname));
-	res = walrcv_exec(wrconn, cmd.data, 0, NULL);
+	res = walrcv_exec(WalReceiverConnection, cmd.data, 0, NULL);
 	pfree(cmd.data);
 	if (res->status != WALRCV_OK_COPY_OUT)
 		ereport(ERROR,
@@ -833,8 +833,8 @@ LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
 	 * application_name, so that it is different from the main apply worker,
 	 * so that synchronous replication can distinguish them.
 	 */
-	wrconn = walrcv_connect(MySubscription->conninfo, true, slotname, &err);
-	if (wrconn == NULL)
+	WalReceiverConnection = walrcv_connect(MySubscription->conninfo, true, slotname, &err);
+	if (WalReceiverConnection == NULL)
 		ereport(ERROR,
 				(errmsg("could not connect to the publisher: %s", err)));
 
@@ -879,7 +879,7 @@ LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
 				 * inside the transaction so that we can use the snapshot made
 				 * by the slot to get existing data.
 				 */
-				res = walrcv_exec(wrconn,
+				res = walrcv_exec(WalReceiverConnection,
 								  "BEGIN READ ONLY ISOLATION LEVEL "
 								  "REPEATABLE READ", 0, NULL);
 				if (res->status != WALRCV_OK_COMMAND)
@@ -896,14 +896,14 @@ LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
 				 * that is consistent with the lsn used by the slot to start
 				 * decoding.
 				 */
-				walrcv_create_slot(wrconn, slotname, true,
+				walrcv_create_slot(WalReceiverConnection, slotname, true,
 								   CRS_USE_SNAPSHOT, origin_startpos);
 
 				PushActiveSnapshot(GetTransactionSnapshot());
 				copy_table(rel);
 				PopActiveSnapshot();
 
-				res = walrcv_exec(wrconn, "COMMIT", 0, NULL);
+				res = walrcv_exec(WalReceiverConnection, "COMMIT", 0, NULL);
 				if (res->status != WALRCV_OK_COMMAND)
 					ereport(ERROR,
 							(errmsg("table copy could not finish transaction on publisher"),
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index ced0d191c2..4f5400c369 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -97,7 +97,7 @@ typedef struct SlotErrCallbackArg
 static MemoryContext ApplyMessageContext = NULL;
 MemoryContext ApplyContext = NULL;
 
-WalReceiverConn *wrconn = NULL;
+WalReceiverConn *WalReceiverConnection = NULL;
 
 Subscription *MySubscription = NULL;
 bool		MySubscriptionValid = false;
@@ -1132,7 +1132,7 @@ LogicalRepApplyLoop(XLogRecPtr last_received)
 
 		MemoryContextSwitchTo(ApplyMessageContext);
 
-		len = walrcv_receive(wrconn, &buf, &fd);
+		len = walrcv_receive(WalReceiverConnection, &buf, &fd);
 
 		if (len != 0)
 		{
@@ -1212,7 +1212,7 @@ LogicalRepApplyLoop(XLogRecPtr last_received)
 					MemoryContextReset(ApplyMessageContext);
 				}
 
-				len = walrcv_receive(wrconn, &buf, &fd);
+				len = walrcv_receive(WalReceiverConnection, &buf, &fd);
 			}
 		}
 
@@ -1242,7 +1242,7 @@ LogicalRepApplyLoop(XLogRecPtr last_received)
 		{
 			TimeLineID	tli;
 
-			walrcv_endstreaming(wrconn, &tli);
+			walrcv_endstreaming(WalReceiverConnection, &tli);
 			break;
 		}
 
@@ -1408,7 +1408,7 @@ send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
 		 (uint32) (flushpos >> 32), (uint32) flushpos
 		);
 
-	walrcv_send(wrconn, reply_message->data, reply_message->len);
+	walrcv_send(WalReceiverConnection, reply_message->data, reply_message->len);
 
 	if (recvpos > last_recvpos)
 		last_recvpos = recvpos;
@@ -1714,9 +1714,9 @@ ApplyWorkerMain(Datum main_arg)
 		origin_startpos = replorigin_session_get_progress(false);
 		CommitTransactionCommand();
 
-		wrconn = walrcv_connect(MySubscription->conninfo, true, MySubscription->name,
+		WalReceiverConnection = walrcv_connect(MySubscription->conninfo, true, MySubscription->name,
 								&err);
-		if (wrconn == NULL)
+		if (WalReceiverConnection == NULL)
 			ereport(ERROR,
 					(errmsg("could not connect to the publisher: %s", err)));
 
@@ -1724,7 +1724,7 @@ ApplyWorkerMain(Datum main_arg)
 		 * We don't really use the output identify_system for anything but it
 		 * does some initializations on the upstream so let's still call it.
 		 */
-		(void) walrcv_identify_system(wrconn, &startpointTLI);
+		(void) walrcv_identify_system(WalReceiverConnection, &startpointTLI);
 
 	}
 
@@ -1744,7 +1744,7 @@ ApplyWorkerMain(Datum main_arg)
 	options.proto.logical.publication_names = MySubscription->publications;
 
 	/* Start normal logical streaming replication. */
-	walrcv_startstreaming(wrconn, &options);
+	walrcv_startstreaming(WalReceiverConnection, &options);
 
 	/* Run the main loop. */
 	LogicalRepApplyLoop(origin_startpos);
diff --git a/src/backend/replication/walreceiver.c b/src/backend/replication/walreceiver.c
index c1e439adb4..f9d3a9feb9 100644
--- a/src/backend/replication/walreceiver.c
+++ b/src/backend/replication/walreceiver.c
@@ -78,7 +78,7 @@ int			wal_receiver_timeout;
 bool		hot_standby_feedback;
 
 /* libpqwalreceiver connection */
-static WalReceiverConn *wrconn = NULL;
+static WalReceiverConn *WalReceiverConnection = NULL;
 WalReceiverFunctionsType *WalReceiverFunctions = NULL;
 
 #define NAPTIME_PER_CYCLE 100	/* max sleep time between cycles (100ms) */
@@ -270,8 +270,8 @@ WalReceiverMain(void)
 	PG_SETMASK(&UnBlockSig);
 
 	/* Establish the connection to the primary for XLOG streaming */
-	wrconn = walrcv_connect(conninfo, false, cluster_name[0] ? cluster_name : "walreceiver", &err);
-	if (!wrconn)
+	WalReceiverConnection = walrcv_connect(conninfo, false, cluster_name[0] ? cluster_name : "walreceiver", &err);
+	if (!WalReceiverConnection)
 		ereport(ERROR,
 				(errmsg("could not connect to the primary server: %s", err)));
 
@@ -280,8 +280,8 @@ WalReceiverMain(void)
 	 * conninfo, for security. Also save host and port of the sender server
 	 * this walreceiver is connected to.
 	 */
-	tmp_conninfo = walrcv_get_conninfo(wrconn);
-	walrcv_get_senderinfo(wrconn, &sender_host, &sender_port);
+	tmp_conninfo = walrcv_get_conninfo(WalReceiverConnection);
+	walrcv_get_senderinfo(WalReceiverConnection, &sender_host, &sender_port);
 	SpinLockAcquire(&walrcv->mutex);
 	memset(walrcv->conninfo, 0, MAXCONNINFO);
 	if (tmp_conninfo)
@@ -312,7 +312,7 @@ WalReceiverMain(void)
 		 * Check that we're connected to a valid server using the
 		 * IDENTIFY_SYSTEM replication command.
 		 */
-		primary_sysid = walrcv_identify_system(wrconn, &primaryTLI);
+		primary_sysid = walrcv_identify_system(WalReceiverConnection, &primaryTLI);
 
 		snprintf(standby_sysid, sizeof(standby_sysid), UINT64_FORMAT,
 				 GetSystemIdentifier());
@@ -362,7 +362,7 @@ WalReceiverMain(void)
 		options.slotname = slotname[0] != '\0' ? slotname : NULL;
 		options.proto.physical.startpointTLI = startpointTLI;
 		ThisTimeLineID = startpointTLI;
-		if (walrcv_startstreaming(wrconn, &options))
+		if (walrcv_startstreaming(WalReceiverConnection, &options))
 		{
 			if (first_stream)
 				ereport(LOG,
@@ -413,7 +413,7 @@ WalReceiverMain(void)
 				}
 
 				/* See if we can read data immediately */
-				len = walrcv_receive(wrconn, &buf, &wait_fd);
+				len = walrcv_receive(WalReceiverConnection, &buf, &wait_fd);
 				if (len != 0)
 				{
 					/*
@@ -444,7 +444,7 @@ WalReceiverMain(void)
 							endofwal = true;
 							break;
 						}
-						len = walrcv_receive(wrconn, &buf, &wait_fd);
+						len = walrcv_receive(WalReceiverConnection, &buf, &wait_fd);
 					}
 
 					/* Let the master know that we received some data. */
@@ -553,7 +553,7 @@ WalReceiverMain(void)
 			 * The backend finished streaming. Exit streaming COPY-mode from
 			 * our side, too.
 			 */
-			walrcv_endstreaming(wrconn, &primaryTLI);
+			walrcv_endstreaming(WalReceiverConnection, &primaryTLI);
 
 			/*
 			 * If the server had switched to a new timeline that we didn't
@@ -700,7 +700,7 @@ WalRcvFetchTimeLineHistoryFiles(TimeLineID first, TimeLineID last)
 					(errmsg("fetching timeline history file for timeline %u from primary server",
 							tli)));
 
-			walrcv_readtimelinehistoryfile(wrconn, tli, &fname, &content, &len);
+			walrcv_readtimelinehistoryfile(WalReceiverConnection, tli, &fname, &content, &len);
 
 			/*
 			 * Check that the filename on the master matches what we
@@ -751,8 +751,8 @@ WalRcvDie(int code, Datum arg)
 	SpinLockRelease(&walrcv->mutex);
 
 	/* Terminate the connection gracefully. */
-	if (wrconn != NULL)
-		walrcv_disconnect(wrconn);
+	if (WalReceiverConnection != NULL)
+		walrcv_disconnect(WalReceiverConnection);
 
 	/* Wake up the startup process to notice promptly that we're gone */
 	WakeupRecovery();
@@ -1114,7 +1114,7 @@ XLogWalRcvSendReply(bool force, bool requestReply)
 		 (uint32) (applyPtr >> 32), (uint32) applyPtr,
 		 requestReply ? " (reply requested)" : "");
 
-	walrcv_send(wrconn, reply_message.data, reply_message.len);
+	walrcv_send(WalReceiverConnection, reply_message.data, reply_message.len);
 }
 
 /*
@@ -1230,7 +1230,7 @@ XLogWalRcvSendHSFeedback(bool immed)
 	pq_sendint32(&reply_message, xmin_epoch);
 	pq_sendint32(&reply_message, catalog_xmin);
 	pq_sendint32(&reply_message, catalog_xmin_epoch);
-	walrcv_send(wrconn, reply_message.data, reply_message.len);
+	walrcv_send(WalReceiverConnection, reply_message.data, reply_message.len);
 	if (TransactionIdIsValid(xmin) || TransactionIdIsValid(catalog_xmin))
 		master_has_standby_xmin = true;
 	else
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index 8b2a2be1c0..e06e9a3015 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -146,7 +146,7 @@ static XLogRecPtr sendTimeLineValidUpto = InvalidXLogRecPtr;
  * How far have we sent WAL already? This is also advertised in
  * MyWalSnd->sentPtr.  (Actually, this is the next WAL location to send.)
  */
-static XLogRecPtr sentPtr = 0;
+static XLogRecPtr WalSentPtr = 0;
 
 /* Buffers for constructing outgoing messages and processing reply messages. */
 static StringInfoData output_message;
@@ -683,11 +683,11 @@ StartReplication(StartReplicationCmd *cmd)
 		}
 
 		/* Start streaming from the requested point */
-		sentPtr = cmd->startpoint;
+		WalSentPtr = cmd->startpoint;
 
 		/* Initialize shared memory status, too */
 		SpinLockAcquire(&MyWalSnd->mutex);
-		MyWalSnd->sentPtr = sentPtr;
+		MyWalSnd->sentPtr = WalSentPtr;
 		SpinLockRelease(&MyWalSnd->mutex);
 
 		SyncRepInitConfig();
@@ -1135,9 +1135,9 @@ StartLogicalReplication(StartReplicationCmd *cmd)
 
 	/*
 	 * Report the location after which we'll send out further commits as the
-	 * current sentPtr.
+	 * current WalSentPtr.
 	 */
-	sentPtr = MyReplicationSlot->data.confirmed_flush;
+	WalSentPtr = MyReplicationSlot->data.confirmed_flush;
 
 	/* Also update the sent position status in shared memory */
 	SpinLockAcquire(&MyWalSnd->mutex);
@@ -1390,8 +1390,8 @@ WalSndWaitForWal(XLogRecPtr loc)
 		 * possibly are waiting for a later location. So we send pings
 		 * containing the flush location every now and then.
 		 */
-		if (MyWalSnd->flush < sentPtr &&
-			MyWalSnd->write < sentPtr &&
+		if (MyWalSnd->flush < WalSentPtr &&
+			MyWalSnd->write < WalSentPtr &&
 			!waiting_for_ping_response)
 		{
 			WalSndKeepalive(false);
@@ -1848,7 +1848,7 @@ ProcessStandbyReplyMessage(void)
 	 * until more WAL traffic arrives.
 	 */
 	clearLagTimes = false;
-	if (applyPtr == sentPtr)
+	if (applyPtr == WalSentPtr)
 	{
 		if (fullyAppliedLastTime)
 			clearLagTimes = true;
@@ -2607,11 +2607,11 @@ XLogSendPhysical(void)
 	 * terminated at a WAL page boundary, the valid portion of the timeline
 	 * might end in the middle of a WAL record. We might've already sent the
 	 * first half of that partial WAL record to the cascading standby, so that
-	 * sentPtr > sendTimeLineValidUpto. That's OK; the cascading standby can't
+	 * WalSentPtr > sendTimeLineValidUpto. That's OK; the cascading standby can't
 	 * replay the partial WAL record either, so it can still follow our
 	 * timeline switch.
 	 */
-	if (sendTimeLineIsHistoric && sendTimeLineValidUpto <= sentPtr)
+	if (sendTimeLineIsHistoric && sendTimeLineValidUpto <= WalSentPtr)
 	{
 		/* close the current file. */
 		if (sendSeg->ws_file >= 0)
@@ -2626,13 +2626,13 @@ XLogSendPhysical(void)
 
 		elog(DEBUG1, "walsender reached end of timeline at %X/%X (sent up to %X/%X)",
 			 (uint32) (sendTimeLineValidUpto >> 32), (uint32) sendTimeLineValidUpto,
-			 (uint32) (sentPtr >> 32), (uint32) sentPtr);
+			 (uint32) (WalSentPtr >> 32), (uint32) WalSentPtr);
 		return;
 	}
 
 	/* Do we have any work to do? */
-	Assert(sentPtr <= SendRqstPtr);
-	if (SendRqstPtr <= sentPtr)
+	Assert(WalSentPtr <= SendRqstPtr);
+	if (SendRqstPtr <= WalSentPtr)
 	{
 		WalSndCaughtUp = true;
 		return;
@@ -2649,7 +2649,7 @@ XLogSendPhysical(void)
 	 * page boundary is always a safe cut-off point. We also assume that
 	 * SendRqstPtr never points to the middle of a WAL record.
 	 */
-	startptr = sentPtr;
+	startptr = WalSentPtr;
 	endptr = startptr;
 	endptr += MAX_SEND_SIZE;
 
@@ -2743,14 +2743,14 @@ retry:
 
 	pq_putmessage_noblock('d', output_message.data, output_message.len);
 
-	sentPtr = endptr;
+	WalSentPtr = endptr;
 
 	/* Update shared memory status */
 	{
 		WalSnd	   *walsnd = MyWalSnd;
 
 		SpinLockAcquire(&walsnd->mutex);
-		walsnd->sentPtr = sentPtr;
+		walsnd->sentPtr = WalSentPtr;
 		SpinLockRelease(&walsnd->mutex);
 	}
 
@@ -2760,7 +2760,7 @@ retry:
 		char		activitymsg[50];
 
 		snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
-				 (uint32) (sentPtr >> 32), (uint32) sentPtr);
+				 (uint32) (WalSentPtr >> 32), (uint32) WalSentPtr);
 		set_ps_display(activitymsg, false);
 	}
 }
@@ -2804,7 +2804,7 @@ XLogSendLogical(void)
 		 */
 		LogicalDecodingProcessRecord(logical_decoding_ctx, logical_decoding_ctx->reader);
 
-		sentPtr = logical_decoding_ctx->reader->EndRecPtr;
+		WalSentPtr = logical_decoding_ctx->reader->EndRecPtr;
 	}
 
 	/* Set flag if we're caught up. */
@@ -2824,7 +2824,7 @@ XLogSendLogical(void)
 		WalSnd	   *walsnd = MyWalSnd;
 
 		SpinLockAcquire(&walsnd->mutex);
-		walsnd->sentPtr = sentPtr;
+		walsnd->sentPtr = WalSentPtr;
 		SpinLockRelease(&walsnd->mutex);
 	}
 }
@@ -2854,7 +2854,7 @@ WalSndDone(WalSndSendDataCallback send_data)
 	replicatedPtr = XLogRecPtrIsInvalid(MyWalSnd->flush) ?
 		MyWalSnd->write : MyWalSnd->flush;
 
-	if (WalSndCaughtUp && sentPtr == replicatedPtr &&
+	if (WalSndCaughtUp && WalSentPtr == replicatedPtr &&
 		!pq_is_send_pending())
 	{
 		/* Inform the standby that XLOG streaming is done */
@@ -3370,7 +3370,7 @@ WalSndKeepalive(bool requestReply)
 	/* construct the message... */
 	resetStringInfo(&output_message);
 	pq_sendbyte(&output_message, 'k');
-	pq_sendint64(&output_message, sentPtr);
+	pq_sendint64(&output_message, WalSentPtr);
 	pq_sendint64(&output_message, GetCurrentTimestamp());
 	pq_sendbyte(&output_message, requestReply ? 1 : 0);
 
diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index 709bbaaf5a..63097739c4 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -508,16 +508,16 @@ Datum
 date_pli(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		ndays = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal + days;
+	result = dateVal + ndays;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result < dateVal) : (result > dateVal)) ||
+	if ((ndays >= 0 ? (result < dateVal) : (result > dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -532,16 +532,16 @@ Datum
 date_mii(PG_FUNCTION_ARGS)
 {
 	DateADT		dateVal = PG_GETARG_DATEADT(0);
-	int32		days = PG_GETARG_INT32(1);
+	int32		ndays = PG_GETARG_INT32(1);
 	DateADT		result;
 
 	if (DATE_NOT_FINITE(dateVal))
 		PG_RETURN_DATEADT(dateVal); /* can't change infinity */
 
-	result = dateVal - days;
+	result = dateVal - ndays;
 
 	/* Check for integer overflow and out-of-allowed-range */
-	if ((days >= 0 ? (result > dateVal) : (result < dateVal)) ||
+	if ((ndays >= 0 ? (result > dateVal) : (result < dateVal)) ||
 		!IS_VALID_DATE(result))
 		ereport(ERROR,
 				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
@@ -1810,18 +1810,18 @@ interval_time(PG_FUNCTION_ARGS)
 {
 	Interval   *span = PG_GETARG_INTERVAL_P(0);
 	TimeADT		result;
-	int64		days;
+	int64		ndays;
 
 	result = span->time;
 	if (result >= USECS_PER_DAY)
 	{
-		days = result / USECS_PER_DAY;
-		result -= days * USECS_PER_DAY;
+		ndays = result / USECS_PER_DAY;
+		result -= ndays * USECS_PER_DAY;
 	}
 	else if (result < 0)
 	{
-		days = (-result + USECS_PER_DAY - 1) / USECS_PER_DAY;
-		result += days * USECS_PER_DAY;
+		ndays = (-result + USECS_PER_DAY - 1) / USECS_PER_DAY;
+		result += ndays * USECS_PER_DAY;
 	}
 
 	PG_RETURN_TIMEADT(result);
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 31bdb37c55..2f721ee67e 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -1500,9 +1500,9 @@ Datum
 make_interval(PG_FUNCTION_ARGS)
 {
 	int32		years = PG_GETARG_INT32(0);
-	int32		months = PG_GETARG_INT32(1);
+	int32		nmonths = PG_GETARG_INT32(1);
 	int32		weeks = PG_GETARG_INT32(2);
-	int32		days = PG_GETARG_INT32(3);
+	int32		ndays = PG_GETARG_INT32(3);
 	int32		hours = PG_GETARG_INT32(4);
 	int32		mins = PG_GETARG_INT32(5);
 	double		secs = PG_GETARG_FLOAT8(6);
@@ -1518,8 +1518,8 @@ make_interval(PG_FUNCTION_ARGS)
 				 errmsg("interval out of range")));
 
 	result = (Interval *) palloc(sizeof(Interval));
-	result->month = years * MONTHS_PER_YEAR + months;
-	result->day = weeks * 7 + days;
+	result->month = years * MONTHS_PER_YEAR + nmonths;
+	result->day = weeks * 7 + ndays;
 
 	secs = rint(secs * USECS_PER_SEC);
 	result->time = hours * ((int64) SECS_PER_HOUR * USECS_PER_SEC) +
@@ -2343,22 +2343,22 @@ interval_cmp_value(const Interval *interval)
 {
 	INT128		span;
 	int64		dayfraction;
-	int64		days;
+	int64		ndays;
 
 	/*
 	 * Separate time field into days and dayfraction, then add the month and
 	 * day fields to the days part.  We cannot overflow int64 days here.
 	 */
 	dayfraction = interval->time % USECS_PER_DAY;
-	days = interval->time / USECS_PER_DAY;
-	days += interval->month * INT64CONST(30);
-	days += interval->day;
+	ndays = interval->time / USECS_PER_DAY;
+	ndays += interval->month * INT64CONST(30);
+	ndays += interval->day;
 
 	/* Widen dayfraction to 128 bits */
 	span = int64_to_int128(dayfraction);
 
 	/* Scale up days to microseconds, forming a 128-bit product */
-	int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
+	int128_add_int64_mul_int64(&span, ndays, USECS_PER_DAY);
 
 	return span;
 }
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index ba74bf9f7d..6da19113cd 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -5383,13 +5383,13 @@ InitializeOneGUCOption(struct config_generic *gconf)
  *
  * This is called after processing command-line switches.
  *		userDoption is the -D switch value if any (NULL if unspecified).
- *		progname is just for use in error messages.
+ *		appname is just for use in error messages.
  *
  * Returns true on success; on failure, prints a suitable error message
  * to stderr and returns false.
  */
 bool
-SelectConfigFiles(const char *userDoption, const char *progname)
+SelectConfigFiles(const char *userDoption, const char *appname)
 {
 	char	   *configdir;
 	char	   *fname;
@@ -5404,7 +5404,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 	if (configdir && stat(configdir, &stat_buf) != 0)
 	{
 		write_stderr("%s: could not access directory \"%s\": %s\n",
-					 progname,
+					 appname,
 					 configdir,
 					 strerror(errno));
 		if (errno == ENOENT)
@@ -5431,7 +5431,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 		write_stderr("%s does not know where to find the server configuration file.\n"
 					 "You must specify the --config-file or -D invocation "
 					 "option or set the PGDATA environment variable.\n",
-					 progname);
+					 appname);
 		return false;
 	}
 
@@ -5448,7 +5448,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 	if (stat(ConfigFileName, &stat_buf) != 0)
 	{
 		write_stderr("%s: could not access the server configuration file \"%s\": %s\n",
-					 progname, ConfigFileName, strerror(errno));
+					 appname, ConfigFileName, strerror(errno));
 		free(configdir);
 		return false;
 	}
@@ -5477,7 +5477,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 					 "This can be specified as \"data_directory\" in \"%s\", "
 					 "or by the -D invocation option, or by the "
 					 "PGDATA environment variable.\n",
-					 progname, ConfigFileName);
+					 appname, ConfigFileName);
 		return false;
 	}
 
@@ -5525,7 +5525,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 					 "This can be specified as \"hba_file\" in \"%s\", "
 					 "or by the -D invocation option, or by the "
 					 "PGDATA environment variable.\n",
-					 progname, ConfigFileName);
+					 appname, ConfigFileName);
 		return false;
 	}
 	SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
@@ -5548,7 +5548,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 					 "This can be specified as \"ident_file\" in \"%s\", "
 					 "or by the -D invocation option, or by the "
 					 "PGDATA environment variable.\n",
-					 progname, ConfigFileName);
+					appname, ConfigFileName);
 		return false;
 	}
 	SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 1f6d8939be..3dc3a3fc6c 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -266,12 +266,12 @@ static void trapsig(int signum);
 static void check_ok(void);
 static char *escape_quotes(const char *src);
 static char *escape_quotes_bki(const char *src);
-static int	locale_date_order(const char *locale);
-static void check_locale_name(int category, const char *locale,
+static int	locale_date_order(const char *locale_name);
+static void check_locale_name(int category, const char *locale_name,
 							  char **canonname);
-static bool check_locale_encoding(const char *locale, int encoding);
+static bool check_locale_encoding(const char *locale_name, int encoding);
 static void setlocales(void);
-static void usage(const char *progname);
+static void usage(const char *appname);
 void		setup_pgdata(void);
 void		setup_bin_paths(const char *argv0);
 void		setup_data_file_paths(void);
@@ -631,7 +631,7 @@ cleanup_directories_atexit(void)
 static char *
 get_id(void)
 {
-	const char *username;
+	const char *user_name;
 
 #ifndef WIN32
 	if (geteuid() == 0)			/* 0 is root's uid */
@@ -644,9 +644,9 @@ get_id(void)
 	}
 #endif
 
-	username = get_user_name_or_exit(progname);
+	user_name = get_user_name_or_exit(progname);
 
-	return pg_strdup(username);
+	return pg_strdup(user_name);
 }
 
 static char *
@@ -864,17 +864,17 @@ write_version_file(const char *extrapath)
 static void
 set_null_conf(void)
 {
-	FILE	   *conf_file;
+	FILE	   *file;
 	char	   *path;
 
 	path = psprintf("%s/postgresql.conf", pg_data);
-	conf_file = fopen(path, PG_BINARY_W);
-	if (conf_file == NULL)
+        file = fopen(path, PG_BINARY_W);
+	if (file == NULL)
 	{
 		pg_log_error("could not open file \"%s\" for writing: %m", path);
 		exit(1);
 	}
-	if (fclose(conf_file))
+	if (fclose(file))
 	{
 		pg_log_error("could not write file \"%s\": %m", path);
 		exit(1);
@@ -2107,7 +2107,7 @@ my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
  * Determine likely date order from locale
  */
 static int
-locale_date_order(const char *locale)
+locale_date_order(const char *locale_name)
 {
 	struct tm	testtime;
 	char		buf[128];
@@ -2125,7 +2125,7 @@ locale_date_order(const char *locale)
 		return result;
 	save = pg_strdup(save);
 
-	setlocale(LC_TIME, locale);
+	setlocale(LC_TIME, locale_name);
 
 	memset(&testtime, 0, sizeof(testtime));
 	testtime.tm_mday = 22;
@@ -2170,7 +2170,7 @@ locale_date_order(const char *locale)
  * this should match the backend's check_locale() function
  */
 static void
-check_locale_name(int category, const char *locale, char **canonname)
+check_locale_name(int category, const char *locale_name, char **canonname)
 {
 	char	   *save;
 	char	   *res;
@@ -2193,7 +2193,7 @@ check_locale_name(int category, const char *locale, char **canonname)
 		locale = "";
 
 	/* set the locale with setlocale, to see if it accepts it. */
-	res = setlocale(category, locale);
+	res = setlocale(category, locale_name);
 
 	/* save canonical name if requested. */
 	if (res && canonname)
@@ -2210,8 +2210,8 @@ check_locale_name(int category, const char *locale, char **canonname)
 	/* complain if locale wasn't valid */
 	if (res == NULL)
 	{
-		if (*locale)
-			pg_log_error("invalid locale name \"%s\"", locale);
+		if (*locale_name)
+			pg_log_error("invalid locale name \"%s\"", locale_name);
 		else
 		{
 			/*
@@ -2234,11 +2234,11 @@ check_locale_name(int category, const char *locale, char **canonname)
  * this should match the similar check in the backend createdb() function
  */
 static bool
-check_locale_encoding(const char *locale, int user_enc)
+check_locale_encoding(const char *locale_name, int user_enc)
 {
 	int			locale_enc;
 
-	locale_enc = pg_get_encoding_from_locale(locale, true);
+	locale_enc = pg_get_encoding_from_locale(locale_name, true);
 
 	/* See notes in createdb() to understand these tests */
 	if (!(locale_enc == user_enc ||
@@ -2321,11 +2321,11 @@ setlocales(void)
  * print help text
  */
 static void
-usage(const char *progname)
+usage(const char *appname)
 {
-	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), appname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION]... [DATADIR]\n"), appname);
 	printf(_("\nOptions:\n"));
 	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
 	printf(_("      --auth-host=METHOD    default authentication method for local TCP/IP connections\n"));
@@ -2393,22 +2393,22 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
 }
 
 static void
-check_need_password(const char *authmethodlocal, const char *authmethodhost)
+check_need_password(const char *authmethod, const char *host)
 {
-	if ((strcmp(authmethodlocal, "md5") == 0 ||
-		 strcmp(authmethodlocal, "password") == 0 ||
-		 strcmp(authmethodlocal, "scram-sha-256") == 0) &&
-		(strcmp(authmethodhost, "md5") == 0 ||
-		 strcmp(authmethodhost, "password") == 0 ||
-		 strcmp(authmethodhost, "scram-sha-256") == 0) &&
+	if ((strcmp(authmethod, "md5") == 0 ||
+		 strcmp(authmethod, "password") == 0 ||
+		 strcmp(authmethod, "scram-sha-256") == 0) &&
+		(strcmp(authmethod, "md5") == 0 ||
+		 strcmp(authmethod, "password") == 0 ||
+		 strcmp(authmethod, "scram-sha-256") == 0) &&
 		!(pwprompt || pwfilename))
 	{
 		pg_log_error("must specify a password for the superuser to enable %s authentication",
-					 (strcmp(authmethodlocal, "md5") == 0 ||
-					  strcmp(authmethodlocal, "password") == 0 ||
-					  strcmp(authmethodlocal, "scram-sha-256") == 0)
-					 ? authmethodlocal
-					 : authmethodhost);
+					 (strcmp(authmethod, "md5") == 0 ||
+					  strcmp(authmethod, "password") == 0 ||
+					  strcmp(authmethod, "scram-sha-256") == 0)
+					 ? authmethod
+					 : host);
 		exit(1);
 	}
 }
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index 19e21ab491..3eb335fb0b 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -30,11 +30,11 @@
 #include "pg_getopt.h"
 
 static void
-usage(const char *progname)
+usage(const char *appname)
 {
-	printf(_("%s displays control information of a PostgreSQL database cluster.\n\n"), progname);
+	printf(_("%s displays control information of a PostgreSQL database cluster.\n\n"), appname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION] [DATADIR]\n"), progname);
+	printf(_("  %s [OPTION] [DATADIR]\n"), appname);
 	printf(_("\nOptions:\n"));
 	printf(_(" [-D, --pgdata=]DATADIR  data directory\n"));
 	printf(_("  -V, --version          output version information, then exit\n"));
@@ -69,9 +69,9 @@ dbState(DBState state)
 }
 
 static const char *
-wal_level_str(WalLevel wal_level)
+wal_level_str(WalLevel level)
 {
-	switch (wal_level)
+	switch (level)
 	{
 		case WAL_LEVEL_MINIMAL:
 			return "minimal";
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 65f9fb4c0a..80715bae01 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -742,7 +742,7 @@ read_post_opts(void)
  * waiting for the server to start up, the server launch is aborted.
  */
 static void
-trap_sigint_during_startup(int sig)
+trap_sigint_during_startup(int signal)
 {
 	if (postmasterPID != -1)
 	{
@@ -760,18 +760,18 @@ trap_sigint_during_startup(int sig)
 }
 
 static char *
-find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
+find_other_exec_or_die(const char *argv_0, const char *target, const char *versionstr)
 {
 	int			ret;
 	char	   *found_path;
 
 	found_path = pg_malloc(MAXPGPATH);
 
-	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
+	if ((ret = find_other_exec(argv_0, target, versionstr, found_path)) < 0)
 	{
 		char		full_path[MAXPGPATH];
 
-		if (find_my_exec(argv0, full_path) < 0)
+		if (find_my_exec(argv_0, full_path) < 0)
 			strlcpy(full_path, progname, sizeof(full_path));
 
 		if (ret == -1)
diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c
index 37432a6f4b..ef5cd5c60c 100644
--- a/src/bin/pg_dump/common.c
+++ b/src/bin/pg_dump/common.c
@@ -64,10 +64,10 @@ static int	numExtensions;
 static ExtensionMemberId *extmembers;
 static int	numextmembers;
 
-static void flagInhTables(Archive *fout, TableInfo *tbinfo, int numTables,
+static void flagInhTables(Archive *fout, TableInfo *tbinfo, int nTables,
 						  InhInfo *inhinfo, int numInherits);
-static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int numTables);
-static void flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables);
+static void flagInhIndexes(Archive *fout, TableInfo *tblinfo, int nTables);
+static void flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int nTables);
 static DumpableObject **buildIndexArray(void *objArray, int numObjs,
 										Size objSize);
 static int	DOCatalogIdCompare(const void *p1, const void *p2);
@@ -270,14 +270,14 @@ getSchemaData(Archive *fout, int *numTablesPtr)
  * modifies tblinfo
  */
 static void
-flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
+flagInhTables(Archive *fout, TableInfo *tblinfo, int nTables,
 			  InhInfo *inhinfo, int numInherits)
 {
 	DumpOptions *dopt = fout->dopt;
 	int			i,
 				j;
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < nTables; i++)
 	{
 		bool		find_parents = true;
 		bool		mark_parents = true;
@@ -329,7 +329,7 @@ flagInhTables(Archive *fout, TableInfo *tblinfo, int numTables,
  *	 appropriate dependency links.
  */
 static void
-flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
+flagInhIndexes(Archive *fout, TableInfo tblinfo[], int nTables)
 {
 	int			i,
 				j,
@@ -339,7 +339,7 @@ flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
 	parentIndexArray = (DumpableObject ***)
 		pg_malloc0(getMaxDumpId() * sizeof(DumpableObject **));
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < nTables; i++)
 	{
 		TableInfo  *parenttbl;
 		IndexAttachInfo *attachinfo;
@@ -436,13 +436,13 @@ flagInhIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
  * modifies tblinfo
  */
 static void
-flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables)
+flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int nTables)
 {
 	int			i,
 				j,
 				k;
 
-	for (i = 0; i < numTables; i++)
+	for (i = 0; i < nTables; i++)
 	{
 		TableInfo  *tbinfo = &(tblinfo[i]);
 		int			numParents;
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 08658c8e86..d5498272b8 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -147,7 +147,7 @@ static int	extra_float_digits;
 	fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
 				   (obj)->dobj.name)
 
-static void help(const char *progname);
+static void help(const char *appname);
 static void setup_connection(Archive *AH,
 							 const char *dumpencoding, const char *dumpsnapshot,
 							 char *use_role);
@@ -155,11 +155,11 @@ static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
 static void expand_schema_name_patterns(Archive *fout,
 										SimpleStringList *patterns,
 										SimpleOidList *oids,
-										bool strict_names);
+										bool is_strict_names);
 static void expand_table_name_patterns(Archive *fout,
 									   SimpleStringList *patterns,
 									   SimpleOidList *oids,
-									   bool strict_names);
+									   bool is_strict_names);
 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
@@ -972,11 +972,11 @@ main(int argc, char **argv)
 
 
 static void
-help(const char *progname)
+help(const char *appname)
 {
-	printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
+	printf(_("%s dumps a database as a text file or to other formats.\n\n"), appname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
+	printf(_("  %s [OPTION]... [DBNAME]\n"), appname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -f, --file=FILENAME          output file or directory name\n"));
@@ -1293,7 +1293,7 @@ static void
 expand_schema_name_patterns(Archive *fout,
 							SimpleStringList *patterns,
 							SimpleOidList *oids,
-							bool strict_names)
+							bool is_strict_names)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1318,7 +1318,7 @@ expand_schema_name_patterns(Archive *fout,
 							  false, NULL, "n.nspname", NULL, NULL);
 
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
-		if (strict_names && PQntuples(res) == 0)
+		if (is_strict_names && PQntuples(res) == 0)
 			fatal("no matching schemas were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
@@ -1341,7 +1341,7 @@ expand_schema_name_patterns(Archive *fout,
 static void
 expand_table_name_patterns(Archive *fout,
 						   SimpleStringList *patterns, SimpleOidList *oids,
-						   bool strict_names)
+						   bool is_strict_names)
 {
 	PQExpBuffer query;
 	PGresult   *res;
@@ -1383,7 +1383,7 @@ expand_table_name_patterns(Archive *fout,
 		res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
 		PQclear(ExecuteSqlQueryForSingleRow(fout,
 											ALWAYS_SECURE_SEARCH_PATH_SQL));
-		if (strict_names && PQntuples(res) == 0)
+		if (is_strict_names && PQntuples(res) == 0)
 			fatal("no matching tables were found for pattern \"%s\"", cell->val);
 
 		for (i = 0; i < PQntuples(res); i++)
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index d1a36b1495..716368e24c 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -50,7 +50,7 @@
 #include "parallel.h"
 #include "pg_backup_utils.h"
 
-static void usage(const char *progname);
+static void usage(const char *appname);
 
 int
 main(int argc, char **argv)
@@ -456,11 +456,11 @@ main(int argc, char **argv)
 }
 
 static void
-usage(const char *progname)
+usage(const char *appname)
 {
-	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), progname);
+	printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), appname);
 	printf(_("Usage:\n"));
-	printf(_("  %s [OPTION]... [FILE]\n"), progname);
+	printf(_("  %s [OPTION]... [FILE]\n"), appname);
 
 	printf(_("\nGeneral options:\n"));
 	printf(_("  -d, --dbname=NAME        connect to database name\n"));
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 2e286f6339..7fb590ffb8 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -738,9 +738,9 @@ GuessControlValues(void)
  * reset by RewriteControlFile().
  */
 static void
-PrintControlValues(bool guessed)
+PrintControlValues(bool guessed_control)
 {
-	if (guessed)
+	if (guessed_control)
 		printf(_("Guessed pg_control values:\n\n"));
 	else
 		printf(_("Current pg_control values:\n\n"));
diff --git a/src/bin/pg_test_fsync/pg_test_fsync.c b/src/bin/pg_test_fsync/pg_test_fsync.c
index 2ca1608bd2..9ef52bff32 100644
--- a/src/bin/pg_test_fsync/pg_test_fsync.c
+++ b/src/bin/pg_test_fsync/pg_test_fsync.c
@@ -91,7 +91,7 @@ static void signal_cleanup(int sig);
 #ifdef HAVE_FSYNC_WRITETHROUGH
 static int	pg_fsync_writethrough(int fd);
 #endif
-static void print_elapse(struct timeval start_t, struct timeval stop_t, int ops);
+static void print_elapse(struct timeval start, struct timeval stop, int ops);
 
 #define die(msg) do { pg_log_error("%s: %m", _(msg)); exit(1); } while(0)
 
@@ -576,10 +576,10 @@ pg_fsync_writethrough(int fd)
  * print out the writes per second for tests
  */
 static void
-print_elapse(struct timeval start_t, struct timeval stop_t, int ops)
+print_elapse(struct timeval start, struct timeval stop, int ops)
 {
-	double		total_time = (stop_t.tv_sec - start_t.tv_sec) +
-	(stop_t.tv_usec - start_t.tv_usec) * 0.000001;
+	double		total_time = (stop.tv_sec - start.tv_sec) +
+	(stop.tv_usec - start.tv_usec) * 0.000001;
 	double		per_second = ops / total_time;
 	double		avg_op_time_us = (total_time / ops) * USECS_SEC;
 
diff --git a/src/include/access/xlogreader.h b/src/include/access/xlogreader.h
index 0193611b7f..f4f5117b8b 100644
--- a/src/include/access/xlogreader.h
+++ b/src/include/access/xlogreader.h
@@ -209,7 +209,7 @@ struct XLogReaderState
 };
 
 /* Get a new XLogReader */
-extern XLogReaderState *XLogReaderAllocate(int wal_segment_size,
+extern XLogReaderState *XLogReaderAllocate(int segment_size,
 										   const char *waldir,
 										   XLogPageReadCB pagereadfunc,
 										   void *private_data);
diff --git a/src/include/replication/worker_internal.h b/src/include/replication/worker_internal.h
index 05f4936419..132b4199e8 100644
--- a/src/include/replication/worker_internal.h
+++ b/src/include/replication/worker_internal.h
@@ -60,7 +60,7 @@ typedef struct LogicalRepWorker
 extern MemoryContext ApplyContext;
 
 /* libpqreceiver connection */
-extern struct WalReceiverConn *wrconn;
+extern struct WalReceiverConn *WalReceiverConnection;
 
 /* Worker and subscription objects. */
 extern Subscription *MySubscription;
diff --git a/src/include/utils/guc.h b/src/include/utils/guc.h
index 50098e63fe..5ab7ed1a80 100644
--- a/src/include/utils/guc.h
+++ b/src/include/utils/guc.h
@@ -354,7 +354,7 @@ extern const char *GetConfigOptionResetString(const char *name);
 extern int	GetConfigOptionFlags(const char *name, bool missing_ok);
 extern void ProcessConfigFile(GucContext context);
 extern void InitializeGUCOptions(void);
-extern bool SelectConfigFiles(const char *userDoption, const char *progname);
+extern bool SelectConfigFiles(const char *userDoption, const char *appname);
 extern void ResetAllOptions(void);
 extern void AtStart_GUC(void);
 extern int	NewGUCNestLevel(void);
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index a29f530327..7568d1c1a9 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -73,7 +73,7 @@ ECPGnumeric_lvalue(char *name)
 static struct descriptor *descriptors;
 
 void
-add_descriptor(char *name, char *connection)
+add_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *new;
 
@@ -87,16 +87,16 @@ add_descriptor(char *name, char *connection)
 	strcpy(new->name, name);
 	if (connection)
 	{
-		new->connection = mm_alloc(strlen(connection) + 1);
-		strcpy(new->connection, connection);
+		new->connection = mm_alloc(strlen(conn_str) + 1);
+		strcpy(new->connection, conn_str);
 	}
 	else
-		new->connection = connection;
+		new->connection = conn_str;
 	descriptors = new;
 }
 
 void
-drop_descriptor(char *name, char *connection)
+drop_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *i;
 	struct descriptor **lastptr = &descriptors;
@@ -108,9 +108,9 @@ drop_descriptor(char *name, char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 			{
 				*lastptr = i->next;
 				if (i->connection)
@@ -126,7 +126,7 @@ drop_descriptor(char *name, char *connection)
 
 struct descriptor
 		   *
-lookup_descriptor(char *name, char *connection)
+lookup_descriptor(char *name, char *conn_str)
 {
 	struct descriptor *i;
 
@@ -137,9 +137,9 @@ lookup_descriptor(char *name, char *connection)
 	{
 		if (strcmp(name, i->name) == 0)
 		{
-			if ((!connection && !i->connection)
-				|| (connection && i->connection
-					&& strcmp(connection, i->connection) == 0))
+			if ((!conn_str && !i->connection)
+				|| (conn_str && i->connection
+					&& strcmp(conn_str, i->connection) == 0))
 				return i;
 		}
 	}
#44Stephen Frost
sfrost@snowman.net
In reply to: Ranier Vilela (#43)
Re: [Proposal] Level4 Warnings show many shadow vars

Greetings,

* Ranier Vilela (ranier_gyn@hotmail.com) wrote:

New version the global patch unshadow.
* names more consistent and readable.
* without big changes.
* goal,, unshadow all global variables, only, even the simplest.

This didn't address any of the comments that I raised elsewhere on this
thread... I certainly don't like the changes being proposed here for
pg_dump.

Thanks,

Stephen

#45Stephen Frost
sfrost@snowman.net
In reply to: Ranier Vilela (#42)
Re: [Proposal] Level4 Warnings show many shadow vars

Greetings,

Didn't see this previously (it's our typical approach to 'reply-all' to
people), though I don't think it changes my feelings about the latest
proposed patch.

* Ranier Vilela (ranier_gyn@hotmail.com) wrote:

De: Stephen Frost
Enviadas: Terça-feira, 10 de Dezembro de 2019 17:52

There's multiple ways to get there though and I think what you're seeing
is that the "just change it to something else" answer isn't necessairly
going to be viewed as an improvement (or, at least, not enough of an
improvement to accept the cost of the change).

Well, I was trying to apply another non-implied rule, "break nothing".

I agree with not breaking things but that doesn't mean the only
reasonable approach is to do the absolute minimum- you might not be
breaking something today, but it's going to confuse people later on down
the road and may lead to bugs being introduced due to that confusion, or
at the very least will add to people's time to figure out what's really
going on.

Why not change the variables? Changes that also improve the code itself
along with eliminating the shadowing of the global variable are going to
be a lot easier to be accepted.

Contrary to what I was initially thinking, it seems to me that changing the names of global variables is more acceptable to the people of the project.

I wasn't suggesting to change the names of the global variables in this
specific case, though I could see that being a better approach in some
instances- but it really depends. Each case needs to be reviewed and
considered and the best approach taken.

Sure, but have you looked at how it's used? Instead of just renaming
the numTables variables in the functions that accept it- could those
variables just be removed instead of changing their name to make it look
like they're something different when they aren't actually different?

No. I didn't look.

I think we need to be looking at the changes and considering them, and
the person proposing the changes should be doing that and not just
expecting everyone else to do so.

I've only spent a bit of time looking at it, but it sure looks like the
variables could just be removed, and doing so doesn't break the
regression tests, which supports the idea that maybe there's a better
way to deal with those particular variables rather than renaming them.
Another approach to consider might be to move some global variables into
structures that are then global with better names to indicate that's
what they are.

It does not seem reasonable to me what you are asking.
Because as I was told here and I agree in part. I do not have the necessary knowledge of structures and logic to propose big changes.

I'd suggest that we work through that then and get you up to speed on
the structures and logic- the pg_dump code is pretty ugly but the
specific usage of numTables isn't too bad. Each of these should be
looked at independently and thought about "what's the right way to fix
this?" The right way isn't necessairly to just rename the variables, as
I was saying, and doing so may lead to more confusion, not less.

For the work I set out to, find bugs and make minor performance improvements, I believe, can contribute safely and without ruining anything.

Having shadowed globals, while kinda ugly, doesn't necessairly mean it's
a bug. I'm not sure what "minor performance improvements" are being
claimed here but there's a whole lot of work involved in demonstrating
that a change is a performance improvement.

By just changing the names of variables to something consistent and readable, the goal will be done without break anything.

but.. the changes you're proposing are making them inconsistent and
confusing when there isn't actually a difference between the global and
the local, it's just the somewhere along the way someone thought they
needed to pass in numTables when they really didn't, and we should go
fix *that*, not rename the variable to something else to make someone
later on go "wait, why did we need to pass in this variable? how is
this different from the global?"

Who is best to make these changes, are the authors and reviewers. Once we no longer have the problem of shadow variables, we can turn on the alert without breaking automatic compilation, as Tom Lane is concerned.

Perhaps I'm a bit confused, but it seems that you're the author of these
specific changes, and I'm trying to provide feedback as to how you can
improve what you're proposing in a way that will improve the code base
overall and reduce the confusion while also eliminating the shadow
variables. If the author of a patch isn't open to this kind of review
and willing to adjust the patch to improve it because they aren't sure
that their changes will be correct then they could at least post them
back here and ask, or better, go look at the code and get a better
understanding of what's going on to build confidence in the change.

The goal here also shouldn't be "we just want to turn on this alert, so
we're going to make changes to the source without thinking just to
appease the compiler".

That's why I'd like to fix all collisions of variables, even the dumbest.

I agree with fixing collisions, but not in a rote way like this.

In short, a hack-and-slash patch that doesn't really spend much time
considering the changes beyond "let's just change these to be different
to avoid shadowing globals" isn't really a good way to go about
addressing these cases and has a good chance of making things more
confusing, not less.

This is totally contrary to what I think about it.

-1 from me then on this whole thread of changes.

Thanks,

Stephen

#46Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Stephen Frost (#45)
RE: [Proposal] Level4 Warnings show many shadow vars

De: Stephen Frost
Enviadas: Quarta-feira, 11 de Dezembro de 2019 15:34

I agree with not breaking things but that doesn't mean the only
reasonable approach is to do the absolute minimum- you might not be
breaking something today, but it's going to confuse people later on down
the road and may lead to bugs being introduced due to that confusion, or
at the very least will add to people's time to figure out what's really
going on.

I don't know how such fixes could lead to more bugs.
Currently there is a risk of having bugs by mixing access to shadow variables with macros.
I believe, that others has the same opinion.
/messages/by-id/CA+TgmoZsM04VCKn4n8dsXxg_s8drPUHUafshG=P0edVjUS3Gew@mail.gmail.com
and
/messages/by-id/20191209090329.GC72921@paquier.xyz

I wasn't suggesting to change the names of the global variables in this
specific case, though I could see that being a better approach in some
instances- but it really depends. Each case needs to be reviewed and
considered and the best approach taken.

Again, depending on the case, whether the best approach is to promote structure creation, variable removal, and logic changes, for now, is really beyond my reach.

I think we need to be looking at the changes and considering them, and
the person proposing the changes should be doing that and not just
expecting everyone else to do so.

Again, I am considering only the range of my changes, which are minimal, so less likely to do something wrong, or hinder future development.

I'd suggest that we work through that then and get you up to speed on
the structures and logic- the pg_dump code is pretty ugly but the
specific usage of numTables isn't too bad. Each of these should be
looked at independently and thought about "what's the right way to fix
this?" The right way isn't necessairly to just rename the variables, as
I was saying, and doing so may lead to more confusion, not less.

This way it will take a long time to eliminate all name collisions.
And worse, in my opinion, will continue to be adding new cases, since there is no rule, so check if this happens in the current development.
Not only are they global, there are dozens, perhaps hundreds of shadow local variables.
I was working on this second class of variables, which, in my opinion, would lead to less code, less bugs, and more security for the code, but I realize that my effort may not be worth it.

Having shadowed globals, while kinda ugly, doesn't necessairly mean it's
a bug. I'm not sure what "minor performance improvements" are being
claimed here but there's a whole lot of work involved in demonstrating
that a change is a performance improvement.

I was referring to contributions like this:
https://github.com/postgres/postgres/commit/91da65f4ac2837e0792071e42b2e2101059f1b1b
and not specifically, performance improvements in this global unshadow patch.

but.. the changes you're proposing are making them inconsistent and
confusing when there isn't actually a difference between the global and
the local, it's just the somewhere along the way someone thought they
needed to pass in numTables when they really didn't, and we should go
fix *that*, not rename the variable to something else to make someone
later on go "wait, why did we need to pass in this variable? how is
this different from the global?"

I'm confused here, but if you suggest removing the numTables variable is out of my reach.
Keeping the same name as the variable, the collision will continue, and the purpose of enabling -Wshadow will never be done someday.

Perhaps I'm a bit confused, but it seems that you're the author of these
specific changes, and I'm trying to provide feedback as to how you can
improve what you're proposing in a way that will improve the code base
overall and reduce the confusion while also eliminating the shadow
variables. If the author of a patch isn't open to this kind of review
and willing to adjust the patch to improve it because they aren't sure
that their changes will be correct then they could at least post them
back here and ask, or better, go look at the code and get a better
understanding of what's going on to build confidence in the change.

I am the author of the patch.
I'm repeating myself, but come on, I don't have confidence in proposing logic-altering changes for now.

The goal here also shouldn't be "we just want to turn on this alert, so
we're going to make changes to the source without thinking just to
appease the compiler".

Of course there is a difference in thinking here.
The changes I propose, in my opinion, are consistent, readable and break nothing.

I agree with fixing collisions, but not in a rote way like this.

Glad you think alike about fixing collisions.

regards,
Ranier Vilela

#47John W Higgins
wishdev@gmail.com
In reply to: Ranier Vilela (#46)
Re: [Proposal] Level4 Warnings show many shadow vars

On Wed, Dec 11, 2019 at 9:46 AM Ranier Vilela <ranier_gyn@hotmail.com>
wrote:

I am the author of the patch.
I'm repeating myself, but come on, I don't have confidence in proposing
logic-altering changes for now.

Then you need to stop and patch the holes and not just throw paint on the
wall to cover things up.

Specific example

src/bin/pgdump/common.c

That file discusses the purpose of numTables

* These variables are static to avoid the notational cruft of having to
pass
* them into findTableByOid() and friends.

Then the file goes and doesn't follow that logic by passing numTables
around to a bunch of functions within itself.

The fix here, very much appears to be to remove the spurious numTables in
the functions.

However, if you cannot, or will not, take the opportunity to correct it
properly - as has been asked earlier for this specific file - then please
just leave it alone.

There have been plenty of emails on these threads where folks have looked
at your work and discussed whether or not specific things should be changed
based on your analysis - that's an amazing thing to see occur - but that's
getting overwhelmed by your inability to take a step back and stop just
throwing stuff on the wall.

I've mentioned inconsistencies in your patches - that is a product of just
trying to throw something on the wall to cover over the issue - hiding a
hole in the wall with something doesn't remove the hole in the wall.

You would be so much better off taking on one specific instance at a time
and working with folks to learn how the code functions. If you don't think
you can handle the bigger issues - then stick with things like numTables
and the clear issues within your grasp first.

I truly do wish you all the best - but you do not seem to be approaching
these issues with the correct mindset at the moment. Volume is not the
winner over quality here.

John W Higgins

Show quoted text
#48Stephen Frost
sfrost@snowman.net
In reply to: Ranier Vilela (#46)
Re: [Proposal] Level4 Warnings show many shadow vars

Greetings,

* Ranier Vilela (ranier_gyn@hotmail.com) wrote:

De: Stephen Frost
Enviadas: Quarta-feira, 11 de Dezembro de 2019 15:34

I agree with not breaking things but that doesn't mean the only
reasonable approach is to do the absolute minimum- you might not be
breaking something today, but it's going to confuse people later on down
the road and may lead to bugs being introduced due to that confusion, or
at the very least will add to people's time to figure out what's really
going on.

I don't know how such fixes could lead to more bugs.
Currently there is a risk of having bugs by mixing access to shadow variables with macros.

I really don't have any doubts that it's going to lead to confusion,
particularly in a case like the numTables vs. nTables thing you're
proposing in the one case that I spent some time looking at, and that
confusion certainly could lead to bugs. Sure, having shadow variables
also could- but you haven't identified an actual bug there today, so why
not just fix it in a way that eliminates the confusion here?

Here's an example of my concern- we change the name of the numTables
variable in these pg_dump functions to nTables as you propose... And
then later on someone starts hacking on these functions and they know
about the global and they start using it, so now we've got two
variables, both able to be used in the same scope, but one of them is a
global and the other is a local. As long as both are always the same,
sure everything works- but what happens if, for whatever reason, someone
uses the function in a new way and passes in a different value as an
argument, one that doesn't match what the global has? Well, some of the
code will use the argument, and some of the code won't. At least today,
there's no chance that the global variable will be used inside that
function- it's *always* going to use the argument passed in.

I don't think that's even that far-fetched of a possibility considering
most of the code is using the global variable directly and these
functions are really the odd ones where numTables is being passed in as
an argument, so ending up with a mix in the function looks rather likely
to happen, and a bug resulting from that inconsistency entirely
possible.

It's also possbile that the changes you're proposing might themselves
induce bugs- by keeping the variable and just renaming it, you had
better be ABSOLUTELY sure you rename every case because, if you don't,
everything will still work just *fine*, except where you missed a case,
the code will reference the global and the compiler won't complain and
it might very well look like everything is working.

Either way, in my view, you had better review the code, have an
understanding of how it works, and make sure that the change you're
making is correct and makes sense, and that you've tested it well.

I wasn't suggesting to change the names of the global variables in this
specific case, though I could see that being a better approach in some
instances- but it really depends. Each case needs to be reviewed and
considered and the best approach taken.

Again, depending on the case, whether the best approach is to promote structure creation, variable removal, and logic changes, for now, is really beyond my reach.

Then I'd suggest that you spend some time looking at each case and
working through what the best approach is and proposing patches that use
the best approach in each case. If you don't wish to spend time on
that, that's fine, but I don't agree with this approach of just pushing
through and making things changes just to satisfy a particular compiler
warning. I don't anticipate further discussion on this changing my mind
on this point.

I think we need to be looking at the changes and considering them, and
the person proposing the changes should be doing that and not just
expecting everyone else to do so.

Again, I am considering only the range of my changes, which are minimal, so less likely to do something wrong, or hinder future development.

I've already pointed out why I don't think this is the right approach to
be addressing these issues, and it seems that you don't disagree with me
about the recommended changes I've suggested, you've just said that you
only want to think about or care about renaming of variables and I am
specifically saying that's not an acceptable approach to addressing
these issues.

I'd suggest that we work through that then and get you up to speed on
the structures and logic- the pg_dump code is pretty ugly but the
specific usage of numTables isn't too bad. Each of these should be
looked at independently and thought about "what's the right way to fix
this?" The right way isn't necessairly to just rename the variables, as
I was saying, and doing so may lead to more confusion, not less.

This way it will take a long time to eliminate all name collisions.

Why is that an issue?

And worse, in my opinion, will continue to be adding new cases, since there is no rule, so check if this happens in the current development.

Feel free to monitor the situation and complain about new patches which
are proposed that add to them. I don't have any particular problem with
that. Nor do I object to generally pushing forward with the goal of
eliminating the existing ones.

Let me lay this out in a different way- we could do the exact same thing
you're doing here by just mindlessly changing, right before we commit,
any variables that shadow global variables, we'd eliminate the compiler
error, but it doesn't directly make anything *better* by itself, and
ultimately isn't really all that different from the current situation
where the compiler is essentially doing this for us by manging the
variables as shadowing the globals thanks to C scoping rules, except
that we add in the possibility of mixing usage of the local and the
global throughout the functions therefore adding to the confusion.

Not only are they global, there are dozens, perhaps hundreds of shadow local variables.

That doesn't actually make any of them bugs though.

I was working on this second class of variables, which, in my opinion, would lead to less code, less bugs, and more security for the code, but I realize that my effort may not be worth it.

I'm all for working to eliminate these shadow variables, but, again, not
through rote renaming of the locals without putting in any real thought
about what the code is doing and working out what the right approach to
such a change to eliminate the shadow variables should be.

Having shadowed globals, while kinda ugly, doesn't necessairly mean it's
a bug. I'm not sure what "minor performance improvements" are being
claimed here but there's a whole lot of work involved in demonstrating
that a change is a performance improvement.

I was referring to contributions like this:
https://github.com/postgres/postgres/commit/91da65f4ac2837e0792071e42b2e2101059f1b1b
and not specifically, performance improvements in this global unshadow patch.

Ok, so this specific "global unshadow patch" is all about bugs, but
without actually showing that there's actual bugs here, just that there
are shadowed variables... In which case, the real question is "is this
change an improvement to the code" and I'm arguing that just the act of
changing the variable names to avoid shadowing isn't necessairly a code
improvement- that has to be evaluated on a case-by-case basis. If
you're not going to do that evaluation then you're just throwing changes
at the community with the expectation that someone else will do the
analysis and decide if the changes are worthwhile or not and that
strikes me as not really being very helpful. I'd really rather work
towards patches that are clear improvements which have been well
considered by the proposer of the patch.

Thanks,

Stephen

#49Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Stephen Frost (#48)
RE: [Proposal] Level4 Warnings show many shadow vars

De: Stephen Frost
Enviadas: Quarta-feira, 11 de Dezembro de 2019 18:57

I really don't have any doubts that it's going to lead to confusion,
particularly in a case like the numTables vs. nTables thing you're
proposing in the one case that I spent some time looking at, and that
confusion certainly could lead to bugs. Sure, having shadow variables
also could- but you haven't identified an actual bug there today, so why
not just fix it in a way that eliminates the confusion here?

I'm starting to think you're absolutely right.

Here's an example of my concern- we change the name of the numTables
variable in these pg_dump functions to nTables as you propose... And
then later on someone starts hacking on these functions and they know
about the global and they start using it, so now we've got two
variables, both able to be used in the same scope, but one of them is a
global and the other is a local. As long as both are always the same,
sure everything works- but what happens if, for whatever reason, someone
uses the function in a new way and passes in a different value as an
argument, one that doesn't match what the global has? Well, some of the
code will use the argument, and some of the code won't. At least today,
there's no chance that the global variable will be used inside that
function- it's *always* going to use the argument passed in.

Understood.

I don't think that's even that far-fetched of a possibility considering
most of the code is using the global variable directly and these
functions are really the odd ones where numTables is being passed in as
an argument, so ending up with a mix in the function looks rather likely
to happen, and a bug resulting from that inconsistency entirely
possible.

Yes.

It's also possbile that the changes you're proposing might themselves
induce bugs- by keeping the variable and just renaming it, you had
better be ABSOLUTELY sure you rename every case because, if you don't,
everything will still work just *fine*, except where you missed a case,
the code will reference the global and the compiler won't complain and
it might very well look like everything is working.

I can tell you that I tried to take every precaution in that direction.
But it is really not exempt from this risk.

Either way, in my view, you had better review the code, have an
understanding of how it works, and make sure that the change you're
making is correct and makes sense, and that you've tested it well.

This view is very correct.

Then I'd suggest that you spend some time looking at each case and
working through what the best approach is and proposing patches that use
the best approach in each case. If you don't wish to spend time on
that, that's fine, but I don't agree with this approach of just pushing
through and making things changes just to satisfy a particular compiler
warning. I don't anticipate further discussion on this changing my mind
on this point.

I've already pointed out why I don't think this is the right approach to
be addressing these issues, and it seems that you don't disagree with me
about the recommended changes I've suggested, you've just said that you
only want to think about or care about renaming of variables and I am
specifically saying that's not an acceptable approach to addressing
these issues.

Why is that an issue?

It's not anymore.

Feel free to monitor the situation and complain about new patches which
are proposed that add to them. I don't have any particular problem with
that. Nor do I object to generally pushing forward with the goal of
eliminating the existing ones.

I would better it safer to do this automatically in the course of development.
Alone, the risk of failure is high.

Let me lay this out in a different way- we could do the exact same thing
you're doing here by just mindlessly changing, right before we commit,
any variables that shadow global variables, we'd eliminate the compiler
error, but it doesn't directly make anything *better* by itself, and
ultimately isn't really all that different from the current situation
where the compiler is essentially doing this for us by manging the
variables as shadowing the globals thanks to C scoping rules, except
that we add in the possibility of mixing usage of the local and the
global throughout the functions therefore adding to the confusion.

This is the light.

That doesn't actually make any of them bugs though.

Truth.

I'm all for working to eliminate these shadow variables, but, again, not
through rote renaming of the locals without putting in any real thought
about what the code is doing and working out what the right approach to
such a change to eliminate the shadow variables should be.
Ok, so this specific "global unshadow patch" is all about bugs, but
without actually showing that there's actual bugs here, just that there
are shadowed variables... In which case, the real question is "is this
change an improvement to the code" and I'm arguing that just the act of
changing the variable names to avoid shadowing isn't necessairly a code
improvement- that has to be evaluated on a case-by-case basis. If
you're not going to do that evaluation then you're just throwing changes
at the community with the expectation that someone else will do the
analysis and decide if the changes are worthwhile or not and that
strikes me as not really being very helpful. I'd really rather work
towards patches that are clear improvements which have been well
considered by the proposer of the patch.

Sorry for not being able to answer point by point, your considerations.
but I think I finally got to understand them correctly.
By renaming, we would be hiding the dirt under the carpet.
And that is absolutely what I want.
From your point of view and from John, the fact that the compiler warns us of the dangers of collisions is much better than simply turning them off by renaming them.
Seeing that, I have to accept.

1.So I would like to ask you if at least what has consensus could be used.
Or is it better to leave everything as it is?

2.About local shadow variables, would you find it safe to do redundant declaration removals of the type: int i? Is it worth it to work on that?

Best regards,
Ranier Vilela

#50Stephen Frost
sfrost@snowman.net
In reply to: Ranier Vilela (#49)
Re: [Proposal] Level4 Warnings show many shadow vars

Greetings,

* Ranier Vilela (ranier_gyn@hotmail.com) wrote:

1.So I would like to ask you if at least what has consensus could be used.
Or is it better to leave everything as it is?

As I tried to say before- I'm all for working to eliminate the shadow
variables, but it should be on a case-by-case basis where the change
proposed is a well considered change by someone who has taken the time
to understand what the code is doing, looked at the call sites, made a
well reasoned argument for why the change is an improvement and reduces
confusion (which can't just be "because the compiler said we should make
this change"- compilers aren't nearly intelligent enough to give us the
right answer about what the code should look like- they can only point
out potential issues, and they're often bad at even doing that), and
then proposed a patch for each particular case where the patch is
addressing a specific set of shadow variable cases that somehow go
together.

A patch to address the numTables issues in pg_dump would be great, for
example. A single patch that renames numTables in pg_dump and then
makes a bunch of completely unrelated changes to things in the backend
isn't what I'd consider a reasonable grouping of changes.

2.About local shadow variables, would you find it safe to do redundant declaration removals of the type: int i? Is it worth it to work on that?

I really don't think you're going to find much in the PG code where
there would be general consensus of a broad renaming or modifying of
variables without having to put serious thought into the specific
change.

At least, I hope people would push back on that kind of rote change.

In other words, without looking at the specific cases you're talking
about, I don't know if I'd agree with them or not, but please don't just
submit patches that just rename things without having looked at the
code, gained some understanding of what the code does, and considered if
the change you want to make is a well reasoned improvement and makes the
code easier to read and understand.

Thanks,

Stephen

#51Michael Paquier
michael@paquier.xyz
In reply to: Tom Lane (#36)
1 attachment(s)
Re: [Proposal] Level4 Warnings show many shadow vars

On Mon, Dec 09, 2019 at 05:11:10PM -0500, Tom Lane wrote:

Alvaro Herrera <alvherre@2ndquadrant.com> writes:

We have a not-consistently-used convention that names in CamelCase are
used for global variables. Naming a function parameter in that style
seems pointlessly confusing. I would rather use redorecptr as Tom
suggested, which fits with the style used for the other arguments of
that function. BTW prepending an X or a p looks like minimum effort...
I'd stay away from that.

Actually, for the particular case of RemoveXlogFile(s), I wonder if it
shouldn't be "startptr" to go with the other argument "endptr". This line
of thinking might not lead to nicer names in other functions, of course.
But we shouldn't assume that a one-size-fits-all solution is going to
improve legibility, and in the end, legibility is what this should be
about.

Hmm. In the case of this logic, we are referring to the current end
of WAL with endptr, and what you are calling the startptr is really
the redo LSN of the last checkpoint in all the routines which are now
confused with RedoRecPtr: RemoveOldXlogFile, RemoveXlogFile and
XLOGfileslop. Using lower-case for all the characters of the variable
name sounds like a good improvement as well, so taking a combination
of all that I would just use "lastredoptr" in those three code paths
(note that we used to have PriorRedoPtr before). As that's a
confusion I introduced with d9fadbf, I would like to fix that and
backpatch this change down to 11. (Ranier gets the authorship
per se as that's extracted from a larger patch).
--
Michael

Attachments:

xlog-fix-varnames-v2.patchtext/x-diff; charset=us-asciiDownload
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 3baf1b009a..71b8389ba1 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -891,8 +891,8 @@ static int	emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
 static void XLogFileClose(void);
 static void PreallocXlogFiles(XLogRecPtr endptr);
 static void RemoveTempXlogFiles(void);
-static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
-static void RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr);
+static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr, XLogRecPtr endptr);
+static void RemoveXlogFile(const char *segname, XLogRecPtr lastredoptr, XLogRecPtr endptr);
 static void UpdateLastRemovedPtr(char *filename);
 static void ValidateXLOGDirectoryStructure(void);
 static void CleanupBackupHistory(void);
@@ -2298,7 +2298,7 @@ assign_checkpoint_completion_target(double newval, void *extra)
  * XLOG segments? Returns the highest segment that should be preallocated.
  */
 static XLogSegNo
-XLOGfileslop(XLogRecPtr RedoRecPtr)
+XLOGfileslop(XLogRecPtr lastredoptr)
 {
 	XLogSegNo	minSegNo;
 	XLogSegNo	maxSegNo;
@@ -2310,9 +2310,9 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	 * correspond to. Always recycle enough segments to meet the minimum, and
 	 * remove enough segments to stay below the maximum.
 	 */
-	minSegNo = RedoRecPtr / wal_segment_size +
+	minSegNo = lastredoptr / wal_segment_size +
 		ConvertToXSegs(min_wal_size_mb, wal_segment_size) - 1;
-	maxSegNo = RedoRecPtr / wal_segment_size +
+	maxSegNo = lastredoptr / wal_segment_size +
 		ConvertToXSegs(max_wal_size_mb, wal_segment_size) - 1;
 
 	/*
@@ -2327,7 +2327,7 @@ XLOGfileslop(XLogRecPtr RedoRecPtr)
 	/* add 10% for good measure. */
 	distance *= 1.10;
 
-	recycleSegNo = (XLogSegNo) ceil(((double) RedoRecPtr + distance) /
+	recycleSegNo = (XLogSegNo) ceil(((double) lastredoptr + distance) /
 									wal_segment_size);
 
 	if (recycleSegNo < minSegNo)
@@ -3948,12 +3948,12 @@ RemoveTempXlogFiles(void)
 /*
  * Recycle or remove all log files older or equal to passed segno.
  *
- * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * endptr is current (or recent) end of xlog, and lastredoptr is the
  * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
  */
 static void
-RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr, XLogRecPtr endptr)
 {
 	DIR		   *xldir;
 	struct dirent *xlde;
@@ -3996,7 +3996,7 @@ RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 				/* Update the last removed location in shared memory first */
 				UpdateLastRemovedPtr(xlde->d_name);
 
-				RemoveXlogFile(xlde->d_name, RedoRecPtr, endptr);
+				RemoveXlogFile(xlde->d_name, lastredoptr, endptr);
 			}
 		}
 	}
@@ -4070,14 +4070,14 @@ RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
 /*
  * Recycle or remove a log file that's no longer needed.
  *
- * endptr is current (or recent) end of xlog, and RedoRecPtr is the
+ * endptr is current (or recent) end of xlog, and lastredoptr is the
  * redo pointer of the last checkpoint. These are used to determine
  * whether we want to recycle rather than delete no-longer-wanted log files.
- * If RedoRecPtr is not known, pass invalid, and the function will recycle,
+ * If lastredoptr is not known, pass invalid, and the function will recycle,
  * somewhat arbitrarily, 10 future segments.
  */
 static void
-RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
+RemoveXlogFile(const char *segname, XLogRecPtr lastredoptr, XLogRecPtr endptr)
 {
 	char		path[MAXPGPATH];
 #ifdef WIN32
@@ -4093,10 +4093,10 @@ RemoveXlogFile(const char *segname, XLogRecPtr RedoRecPtr, XLogRecPtr endptr)
 		 * Initialize info about where to try to recycle to.
 		 */
 		XLByteToSeg(endptr, endlogSegNo, wal_segment_size);
-		if (RedoRecPtr == InvalidXLogRecPtr)
+		if (lastredoptr == InvalidXLogRecPtr)
 			recycleSegNo = endlogSegNo + 10;
 		else
-			recycleSegNo = XLOGfileslop(RedoRecPtr);
+			recycleSegNo = XLOGfileslop(lastredoptr);
 	}
 	else
 		recycleSegNo = 0;		/* keep compiler quiet */
#52Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Michael Paquier (#51)
RE: [Proposal] Level4 Warnings show many shadow vars

De: Michael Paquier
Enviadas: Terça-feira, 17 de Dezembro de 2019 00:36

Hmm. In the case of this logic, we are referring to the current end
of WAL with endptr, and what you are calling the startptr is really
the redo LSN of the last checkpoint in all the routines which are now
confused with RedoRecPtr: RemoveOldXlogFile, RemoveXlogFile and
XLOGfileslop. Using lower-case for all the characters of the variable
name sounds like a good improvement as well, so taking a combination
of all that I would just use "lastredoptr" in those three code paths
(note that we used to have PriorRedoPtr before). As that's a
confusion I introduced with d9fadbf, I would like to fix that and
backpatch this change down to 11. (Ranier gets the authorship
per se as that's extracted from a larger patch).

Hey Michael, thank you so much for considering correct at least part of an extensive work.

Best regards,
Ranier Vilela

#53Michael Paquier
michael@paquier.xyz
In reply to: Michael Paquier (#51)
Re: [Proposal] Level4 Warnings show many shadow vars

On Tue, Dec 17, 2019 at 09:36:13AM +0900, Michael Paquier wrote:

As that's a confusion I introduced with d9fadbf, I would like to fix
that and backpatch this change down to 11. (Ranier gets the
authorship per se as that's extracted from a larger patch).

Committed that part.

I got to look at the rest of the stuff discussed, and I am not sure
that any of the changes are actually things which improve
readability.

Let's take one example. The changes in pg_dump/ like
/progname/prog_name/ have just been done in haste, without actual
thoughts about how the problem ought to be fixed. And in this case,
something which could be more adapted is to remove the argument from
usage() because progname is a global variable, initialized from the
beginning in pg_restore.
--
Michael

#54Alvaro Herrera
alvherre@2ndquadrant.com
In reply to: Michael Paquier (#53)
Re: [Proposal] Level4 Warnings show many shadow vars

On 2019-Dec-18, Michael Paquier wrote:

Let's take one example. The changes in pg_dump/ like
/progname/prog_name/ have just been done in haste, without actual
thoughts about how the problem ought to be fixed. And in this case,
something which could be more adapted is to remove the argument from
usage() because progname is a global variable, initialized from the
beginning in pg_restore.

We discussed progname as a global/local before -- IIRC in the thread
that introduced the frontend logging API -- and while I think the whole
issue could stand some improvement, we shouldn't let it be driven by
minor changes; that'll only make it more confusing. IMO if we want it
improved, a larger change (involving the bunch of frontend programs) is
what to look for. Maybe what you suggest is an improvement, though
(certainly the "prog_name" patch wasn't).

--
�lvaro Herrera https://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#55Ranier Vilela
ranier_gyn@hotmail.com
In reply to: Alvaro Herrera (#54)
RE: [Proposal] Level4 Warnings show many shadow vars

De: Michael Paquier
Enviadas: Quarta-feira, 18 de Dezembro de 2019 01:18

Committed that part.

Thanks.

Let's take one example. The changes in pg_dump/ like
/progname/prog_name/ have just been done in haste, without actual
thoughts about how the problem ought to be fixed. And in this case,
something which could be more adapted is to remove the argument from
usage() because progname is a global variable, initialized from the
beginning in pg_restore.

Yeah, this is good hint about how improve the patch.

Best regards,
Ranier Vilela

#56Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Alvaro Herrera (#54)
Re: [Proposal] Level4 Warnings show many shadow vars

On 2019-12-18 10:55, Alvaro Herrera wrote:

On 2019-Dec-18, Michael Paquier wrote:

Let's take one example. The changes in pg_dump/ like
/progname/prog_name/ have just been done in haste, without actual
thoughts about how the problem ought to be fixed. And in this case,
something which could be more adapted is to remove the argument from
usage() because progname is a global variable, initialized from the
beginning in pg_restore.

We discussed progname as a global/local before -- IIRC in the thread
that introduced the frontend logging API -- and while I think the whole
issue could stand some improvement, we shouldn't let it be driven by
minor changes; that'll only make it more confusing. IMO if we want it
improved, a larger change (involving the bunch of frontend programs) is
what to look for. Maybe what you suggest is an improvement, though
(certainly the "prog_name" patch wasn't).

This thread is still in the commit fest, but it's apparently gone as far
as it will, so I've set it to "Committed" for lack of a "partial" status.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#57Michael Paquier
michael@paquier.xyz
In reply to: Peter Eisentraut (#56)
Re: [Proposal] Level4 Warnings show many shadow vars

On Thu, Feb 27, 2020 at 10:43:50AM +0100, Peter Eisentraut wrote:

This thread is still in the commit fest, but it's apparently gone as far as
it will, so I've set it to "Committed" for lack of a "partial" status.

Thanks, that sounds right to me. I was just looking at the latest
patch presented after seeing your reply, and I did not spot
immediately any issues standing out compared to the others.
--
Michael