Skip to content

Commit 96fdaa6

Browse files
committed
Style: Integrate #pragma once in builders/checks
1 parent 7459a03 commit 96fdaa6

17 files changed

+44
-197
lines changed

.pre-commit-config.yaml

-1
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,6 @@ repos:
154154
language: python
155155
entry: python misc/scripts/header_guards.py
156156
files: \.(h|hpp|hh|hxx)$
157-
exclude: ^.*/(dummy|thread|platform_config|platform_gl)\.h$
158157

159158
- id: file-format
160159
name: file-format

core/extension/make_interface_dumper.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@ def run(target, source, env):
1414

1515
g.write(
1616
"""/* THIS FILE IS GENERATED DO NOT EDIT */
17-
#ifndef GDEXTENSION_INTERFACE_DUMP_H
18-
#define GDEXTENSION_INTERFACE_DUMP_H
17+
#pragma once
1918
2019
#ifdef TOOLS_ENABLED
2120
@@ -49,7 +48,5 @@ class GDExtensionInterfaceDump {
4948
};
5049
5150
#endif // TOOLS_ENABLED
52-
53-
#endif // GDEXTENSION_INTERFACE_DUMP_H
5451
"""
5552
)

core/extension/make_wrappers.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -119,10 +119,7 @@ def generate_ex_version(argcount, const=False, returns=False):
119119
def run(target, source, env):
120120
max_versions = 12
121121

122-
txt = """
123-
#ifndef GDEXTENSION_WRAPPERS_GEN_H
124-
#define GDEXTENSION_WRAPPERS_GEN_H
125-
"""
122+
txt = "#pragma once"
126123

127124
for i in range(max_versions + 1):
128125
txt += "\n/* Extension Wrapper " + str(i) + " Arguments */\n"
@@ -138,7 +135,5 @@ def run(target, source, env):
138135
txt += generate_mod_version(i, True, False)
139136
txt += generate_mod_version(i, True, True)
140137

141-
txt += "\n#endif\n"
142-
143138
with open(str(target[0]), "w", encoding="utf-8", newline="\n") as f:
144139
f.write(txt)

core/object/make_virtuals.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,7 @@ def run(target, source, env):
207207
max_versions = 12
208208

209209
txt = """/* THIS FILE IS GENERATED DO NOT EDIT */
210-
#ifndef GDVIRTUAL_GEN_H
211-
#define GDVIRTUAL_GEN_H
210+
#pragma once
212211
213212
#include "core/object/script_instance.h"
214213
@@ -257,7 +256,5 @@ def run(target, source, env):
257256
txt += generate_version(i, True, False, False, True)
258257
txt += generate_version(i, True, True, False, True)
259258

260-
txt += "#endif // GDVIRTUAL_GEN_H\n"
261-
262259
with open(str(target[0]), "w", encoding="utf-8", newline="\n") as f:
263260
f.write(txt)

gles3_builders.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -209,13 +209,11 @@ def build_gles3_header(
209209
defvariant = ""
210210

211211
fd.write("/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\n")
212+
fd.write("#pragma once\n")
212213

213214
out_file_base = out_file
214215
out_file_base = out_file_base[out_file_base.rfind("/") + 1 :]
215216
out_file_base = out_file_base[out_file_base.rfind("\\") + 1 :]
216-
out_file_ifdef = out_file_base.replace(".", "_").upper()
217-
fd.write("#ifndef " + out_file_ifdef + class_suffix + "_GLES3\n")
218-
fd.write("#define " + out_file_ifdef + class_suffix + "_GLES3\n")
219217

220218
out_file_class = (
221219
out_file_base.replace(".glsl.gen.h", "").title().replace("_", "").replace(".", "") + "Shader" + class_suffix
@@ -580,8 +578,7 @@ def build_gles3_header(
580578

581579
fd.write("\t}\n\n")
582580

583-
fd.write("};\n\n")
584-
fd.write("#endif\n")
581+
fd.write("};\n")
585582

586583

587584
def build_gles3_headers(target, source, env):

glsl_builders.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ def build_rd_header(
106106
out_file_base = out_file
107107
out_file_base = out_file_base[out_file_base.rfind("/") + 1 :]
108108
out_file_base = out_file_base[out_file_base.rfind("\\") + 1 :]
109-
out_file_ifdef = out_file_base.replace(".", "_").upper()
110109
out_file_class = out_file_base.replace(".glsl.gen.h", "").title().replace("_", "").replace(".", "") + "ShaderRD"
111110

112111
if header_data.compute_lines:
@@ -125,8 +124,7 @@ def build_rd_header(
125124

126125
# Intended curly brackets are doubled so f-string doesn't eat them up.
127126
shader_template = f"""/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */
128-
#ifndef {out_file_ifdef}_RD
129-
#define {out_file_ifdef}_RD
127+
#pragma once
130128
131129
#include "servers/rendering/renderer_rd/shader_rd.h"
132130
@@ -139,8 +137,6 @@ class {out_file_class} : public ShaderRD {{
139137
{body_content}
140138
}}
141139
}};
142-
143-
#endif
144140
"""
145141

146142
with open(out_file, "w", encoding="utf-8", newline="\n") as fd:
@@ -189,16 +185,13 @@ def build_raw_header(
189185
out_file_base = out_file.replace(".glsl.gen.h", "_shader_glsl")
190186
out_file_base = out_file_base[out_file_base.rfind("/") + 1 :]
191187
out_file_base = out_file_base[out_file_base.rfind("\\") + 1 :]
192-
out_file_ifdef = out_file_base.replace(".", "_").upper()
193188

194189
shader_template = f"""/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */
195-
#ifndef {out_file_ifdef}_RAW_H
196-
#define {out_file_ifdef}_RAW_H
190+
#pragma once
197191
198192
static const char {out_file_base}[] = {{
199193
{to_raw_cstring(header_data.code)}
200194
}};
201-
#endif
202195
"""
203196

204197
with open(out_file, "w", encoding="utf-8", newline="\n") as f:

methods.py

+4-26
Original file line numberDiff line numberDiff line change
@@ -1447,8 +1447,6 @@ def generate_copyright_header(filename: str) -> str:
14471447
def generated_wrapper(
14481448
path, # FIXME: type with `Union[str, Node, List[Node]]` when pytest conflicts are resolved
14491449
guard: Optional[bool] = None,
1450-
prefix: str = "",
1451-
suffix: str = "",
14521450
) -> Generator[TextIOBase, None, None]:
14531451
"""
14541452
Wrapper class to automatically handle copyright headers and header guards
@@ -1458,12 +1456,8 @@ def generated_wrapper(
14581456
- `path`: The path of the file to be created. Can be passed a raw string, an
14591457
isolated SCons target, or a full SCons target list. If a target list contains
14601458
multiple entries, produces a warning & only creates the first entry.
1461-
- `guard`: Optional bool to determine if a header guard should be added. If
1462-
unassigned, header guards are determined by the file extension.
1463-
- `prefix`: Custom prefix to prepend to a header guard. Produces a warning if
1464-
provided a value when `guard` evaluates to `False`.
1465-
- `suffix`: Custom suffix to append to a header guard. Produces a warning if
1466-
provided a value when `guard` evaluates to `False`.
1459+
- `guard`: Optional bool to determine if `#pragma once` should be added. If
1460+
unassigned, the value is determined by file extension.
14671461
"""
14681462

14691463
# Handle unfiltered SCons target[s] passed as path.
@@ -1480,35 +1474,19 @@ def generated_wrapper(
14801474

14811475
path = str(path).replace("\\", "/")
14821476
if guard is None:
1483-
guard = path.endswith((".h", ".hh", ".hpp", ".inc"))
1484-
if not guard and (prefix or suffix):
1485-
print_warning(f'Trying to assign header guard prefix/suffix while `guard` is disabled: "{path}".')
1486-
1487-
header_guard = ""
1488-
if guard:
1489-
if prefix:
1490-
prefix += "_"
1491-
if suffix:
1492-
suffix = f"_{suffix}"
1493-
split = path.split("/")[-1].split(".")
1494-
header_guard = (f"{prefix}{split[0]}{suffix}.{'.'.join(split[1:])}".upper()
1495-
.replace(".", "_").replace("-", "_").replace(" ", "_").replace("__", "_")) # fmt: skip
1477+
guard = path.endswith((".h", ".hh", ".hpp", ".hxx", ".inc"))
14961478

14971479
with open(path, "wt", encoding="utf-8", newline="\n") as file:
14981480
file.write(generate_copyright_header(path))
14991481
file.write("\n/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n")
15001482

15011483
if guard:
1502-
file.write(f"#ifndef {header_guard}\n")
1503-
file.write(f"#define {header_guard}\n\n")
1484+
file.write("#pragma once\n\n")
15041485

15051486
with StringIO(newline="\n") as str_io:
15061487
yield str_io
15071488
file.write(str_io.getvalue().strip() or "/* NO CONTENT */")
15081489

1509-
if guard:
1510-
file.write(f"\n\n#endif // {header_guard}")
1511-
15121490
file.write("\n")
15131491

15141492

misc/scripts/char_range_fetch.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,7 @@ def generate_char_range_inc() -> None:
106106
source += f"""
107107
// This file was generated using the `misc/scripts/char_range_fetch.py` script.
108108
109-
#ifndef CHAR_RANGE_INC
110-
#define CHAR_RANGE_INC
109+
#pragma once
111110
112111
#include "core/typedefs.h"
113112
@@ -125,8 +124,6 @@ def generate_char_range_inc() -> None:
125124
source += make_array("lowercase_letter", lowercase_letter)
126125
source += make_array("unicode_letter", unicode_letter)
127126

128-
source += "#endif // CHAR_RANGE_INC\n"
129-
130127
char_range_path: str = os.path.join(os.path.dirname(__file__), "../../core/string/char_range.inc")
131128
with open(char_range_path, "w", newline="\n") as f:
132129
f.write(source)

misc/scripts/header_guards.py

+24-110
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
# -*- coding: utf-8 -*-
33

44
import sys
5-
from pathlib import Path
65

76
if len(sys.argv) < 2:
87
print("Invalid usage of header_guards.py, it should be called with a path to one or multiple files.")
@@ -13,7 +12,7 @@
1312

1413
for file in sys.argv[1:]:
1514
header_start = -1
16-
HEADER_CHECK_OFFSET = -1
15+
header_end = -1
1716

1817
with open(file.strip(), "rt", encoding="utf-8", newline="\n") as f:
1918
lines = f.readlines()
@@ -28,142 +27,57 @@
2827
if sline.startswith("/**********"): # Godot header starts this way.
2928
header_start = idx
3029
else:
31-
HEADER_CHECK_OFFSET = 0 # There is no Godot header.
30+
header_end = 0 # There is no Godot header.
3231
break
3332
else:
34-
if not sline.startswith("*") and not sline.startswith("/*"): # Not in the Godot header anymore.
35-
HEADER_CHECK_OFFSET = idx + 1 # The include should be two lines below the Godot header.
33+
if not sline.startswith(("*", "/*")): # Not in the Godot header anymore.
34+
header_end = idx + 1 # The guard should be two lines below the Godot header.
3635
break
3736

38-
if HEADER_CHECK_OFFSET < 0:
37+
if (HEADER_CHECK_OFFSET := header_end) < 0 or HEADER_CHECK_OFFSET >= len(lines):
3938
invalid.append(file)
4039
continue
4140

41+
if lines[HEADER_CHECK_OFFSET].startswith("#pragma once"):
42+
continue
43+
44+
# Might be using legacy header guards.
4245
HEADER_BEGIN_OFFSET = HEADER_CHECK_OFFSET + 1
4346
HEADER_END_OFFSET = len(lines) - 1
4447

4548
if HEADER_BEGIN_OFFSET >= HEADER_END_OFFSET:
4649
invalid.append(file)
4750
continue
4851

49-
split = file.split("/") # Already in posix-format.
50-
51-
prefix = ""
52-
if split[0] == "modules" and split[-1] == "register_types.h":
53-
prefix = f"{split[1]}_" # Name of module.
54-
elif split[0] == "platform" and (file.endswith("api/api.h") or "/export/" in file):
55-
prefix = f"{split[1]}_" # Name of platform.
56-
elif file.startswith("modules/mono/utils") and "mono" not in split[-1]:
57-
prefix = "MONO_"
58-
elif file == "servers/rendering/storage/utilities.h":
59-
prefix = "RENDERER_"
60-
61-
suffix = ""
62-
if "dummy" in file and "dummy" not in split[-1]:
63-
suffix = "_DUMMY"
64-
elif "gles3" in file and "gles3" not in split[-1]:
65-
suffix = "_GLES3"
66-
elif "renderer_rd" in file and "rd" not in split[-1]:
67-
suffix = "_RD"
68-
elif split[-1] == "ustring.h":
69-
suffix = "_GODOT"
70-
71-
name = (f"{prefix}{Path(file).stem}{suffix}{Path(file).suffix}".upper()
72-
.replace(".", "_").replace("-", "_").replace(" ", "_")) # fmt: skip
73-
74-
HEADER_CHECK = f"#ifndef {name}\n"
75-
HEADER_BEGIN = f"#define {name}\n"
76-
HEADER_END = f"#endif // {name}\n"
77-
78-
if (
79-
lines[HEADER_CHECK_OFFSET] == HEADER_CHECK
80-
and lines[HEADER_BEGIN_OFFSET] == HEADER_BEGIN
81-
and lines[HEADER_END_OFFSET] == HEADER_END
82-
):
83-
continue
84-
85-
# Guards might exist but with the wrong names.
8652
if (
8753
lines[HEADER_CHECK_OFFSET].startswith("#ifndef")
8854
and lines[HEADER_BEGIN_OFFSET].startswith("#define")
8955
and lines[HEADER_END_OFFSET].startswith("#endif")
9056
):
91-
lines[HEADER_CHECK_OFFSET] = HEADER_CHECK
92-
lines[HEADER_BEGIN_OFFSET] = HEADER_BEGIN
93-
lines[HEADER_END_OFFSET] = HEADER_END
57+
lines[HEADER_CHECK_OFFSET] = "#pragma once"
58+
lines[HEADER_BEGIN_OFFSET] = "\n"
59+
lines.pop()
9460
with open(file, "wt", encoding="utf-8", newline="\n") as f:
9561
f.writelines(lines)
9662
changed.append(file)
9763
continue
9864

99-
header_check = -1
100-
header_begin = -1
101-
header_end = -1
102-
pragma_once = -1
103-
objc = False
104-
105-
for idx, line in enumerate(lines):
106-
if line.startswith("// #import"): # Some dummy obj-c files only have commented out import lines.
107-
objc = True
108-
break
109-
if not line.startswith("#"):
110-
continue
111-
elif line.startswith("#ifndef") and header_check == -1:
112-
header_check = idx
113-
elif line.startswith("#define") and header_begin == -1:
114-
header_begin = idx
115-
elif line.startswith("#endif") and header_end == -1:
116-
header_end = idx
117-
elif line.startswith("#pragma once"):
118-
pragma_once = idx
65+
# Verify `#pragma once` doesn't exist at invalid location.
66+
misplaced = False
67+
for line in lines:
68+
if line.startswith("#pragma once"):
69+
misplaced = True
11970
break
120-
elif line.startswith("#import"):
121-
objc = True
122-
break
123-
124-
if objc:
125-
continue
126-
127-
if pragma_once != -1:
128-
lines.pop(pragma_once)
129-
lines.insert(HEADER_CHECK_OFFSET, HEADER_CHECK)
130-
lines.insert(HEADER_BEGIN_OFFSET, HEADER_BEGIN)
131-
lines.append("\n")
132-
lines.append(HEADER_END)
133-
with open(file, "wt", encoding="utf-8", newline="\n") as f:
134-
f.writelines(lines)
135-
changed.append(file)
136-
continue
13771

138-
if header_check == -1 and header_begin == -1 and header_end == -1:
139-
# Guards simply didn't exist
140-
lines.insert(HEADER_CHECK_OFFSET, HEADER_CHECK)
141-
lines.insert(HEADER_BEGIN_OFFSET, HEADER_BEGIN)
142-
lines.append("\n")
143-
lines.append(HEADER_END)
144-
with open(file, "wt", encoding="utf-8", newline="\n") as f:
145-
f.writelines(lines)
146-
changed.append(file)
72+
if misplaced:
73+
invalid.append(file)
14774
continue
14875

149-
if header_check != -1 and header_begin != -1 and header_end != -1:
150-
# All prepends "found", see if we can salvage this.
151-
if header_check == header_begin - 1 and header_begin < header_end:
152-
lines.pop(header_check)
153-
lines.pop(header_begin - 1)
154-
lines.pop(header_end - 2)
155-
if lines[header_end - 3] == "\n":
156-
lines.pop(header_end - 3)
157-
lines.insert(HEADER_CHECK_OFFSET, HEADER_CHECK)
158-
lines.insert(HEADER_BEGIN_OFFSET, HEADER_BEGIN)
159-
lines.append("\n")
160-
lines.append(HEADER_END)
161-
with open(file, "wt", encoding="utf-8", newline="\n") as f:
162-
f.writelines(lines)
163-
changed.append(file)
164-
continue
165-
166-
invalid.append(file)
76+
# Assume that we're simply missing a guard entirely.
77+
lines.insert(HEADER_CHECK_OFFSET, "#pragma once\n\n")
78+
with open(file, "wt", encoding="utf-8", newline="\n") as f:
79+
f.writelines(lines)
80+
changed.append(file)
16781

16882
if changed:
16983
for file in changed:

0 commit comments

Comments
 (0)