Debian Codegraph @

gcc/d/dmd/globals.d

raw
1 /**
2 * Stores command line options and contains other miscellaneous declarations.
3 *
4 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
5 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
6 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/globals.d, _globals.d)
8 * Documentation: https://dlang.org/phobos/dmd_globals.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/globals.d
10 */
11
12 module dmd.globals;
13
14 import core.stdc.stdio;
15 import core.stdc.stdint;
16 import core.stdc.string;
17
18 import dmd.astenums;
19 import dmd.root.array;
20 import dmd.root.file;
21 import dmd.root.filename;
22 import dmd.common.outbuffer;
23 import dmd.errorsink;
24 import dmd.errors;
25 import dmd.file_manager;
26 import dmd.identifier;
27 import dmd.location;
28 import dmd.lexer : CompileEnv;
29 import dmd.utils;
30
31 version (IN_GCC) {}
32 else version (IN_LLVM) {}
33 else version = MARS;
34
35 /// Defines a setting for how compiler warnings and deprecations are handled
36 enum DiagnosticReporting : ubyte
37 {
38 error, /// generate an error
39 inform, /// generate a warning
40 off, /// disable diagnostic
41 }
42
43 /**
44 Each flag represents a field that can be included in the JSON output.
45
46 NOTE: set type to uint so its size matches C++ unsigned type
47 */
48 enum JsonFieldFlags : uint
49 {
50 none = 0,
51 compilerInfo = (1 << 0),
52 buildInfo = (1 << 1),
53 modules = (1 << 2),
54 semantics = (1 << 3),
55 }
56
57 /// Version of C++ standard to support
58 enum CppStdRevision : uint
59 {
60 cpp98 = 1997_11,
61 cpp11 = 2011_03,
62 cpp14 = 2014_02,
63 cpp17 = 2017_03,
64 cpp20 = 2020_02,
65 cpp23 = 2023_02,
66 }
67
68 /// Trivalent boolean to represent the state of a `revert`able change
69 enum FeatureState : ubyte
70 {
71 default_ = 0, /// Not specified by the user
72 disabled = 1, /// Specified as `-revert=`
73 enabled = 2, /// Specified as `-preview=`
74 }
75
76 /// Different identifier tables specifiable by CLI
77 enum CLIIdentifierTable : ubyte
78 {
79 default_ = 0, /// Not specified by user
80 C99 = 1, /// Tables from C99 standard
81 C11 = 2, /// Tables from C11 standard
82 UAX31 = 3, /// Tables from the Unicode Standard Annex 31: UNICODE IDENTIFIERS AND SYNTAX
83 All = 4, /// The least restrictive set of all other tables
84 }
85
86 /// Specifies the mode for error printing
87 enum ErrorPrintMode : ubyte
88 {
89 simpleError, // Print errors without squiggles and carets
90 printErrorContext, // Print errors with context (source line and caret)
91 }
92
93 extern(C++) struct Output
94 {
95 bool doOutput; // Output is enabled
96 bool fullOutput; // Generate comments for hidden declarations (for -HC),
97 // and don't strip the bodies of plain (non-template) functions (for -H)
98
99 const(char)[] dir; // write to directory 'dir'
100 const(char)[] name; // write to file 'name'
101 Array!(const(char)*) files; // Other files associated with this output,
102 // e.g. macro include files for Ddoc, dependencies for makedeps
103 OutBuffer* buffer; // if this output is buffered, this is the buffer
104 int bufferLines; // number of lines written to the buffer
105 }
106
107 /// Command line state related to printing usage about other switches
108 extern(C++) struct Help
109 {
110 bool manual; // open browser on compiler manual
111 bool usage; // print usage and exit
112 // print help of switch:
113 bool mcpu; // -mcpu
114 bool transition; // -transition
115 bool check; // -check
116 bool checkAction; // -checkaction
117 bool revert; // -revert
118 bool preview; // -preview
119 bool externStd; // -extern-std
120 bool hc; // -HC
121 }
122
123 extern(C++) struct Verbose
124 {
125 bool verbose; // verbose compile
126 bool showColumns; // print character (column) numbers in diagnostics
127 bool tls; // identify thread local variables
128 bool templates; // collect and list statistics on template instantiations
129 // collect and list statistics on template instantiations origins.
130 // TODO: make this an enum when we want to list other kinds of instances
131 bool templatesListInstances;
132 bool gc; // identify gc usage
133 bool field; // identify non-mutable field variables
134 bool complex = true; // identify complex/imaginary type usage
135 bool vin; // identify 'in' parameters
136 bool showGaggedErrors; // print gagged errors anyway
137 bool logo; // print compiler logo
138 bool color; // use ANSI colors in console output
139 bool cov; // generate code coverage data
140 ErrorPrintMode errorPrintMode; // enum for error printing mode
141 MessageStyle messageStyle = MessageStyle.digitalmars; // style of file/line annotations on messages
142 uint errorLimit = 20;
143 uint errorSupplementLimit = 6; // Limit the number of supplemental messages for each error (0 means unlimited)
144
145 uint errorSupplementCount() @safe
146 {
147 if (verbose)
148 return uint.max;
149 if (errorSupplementLimit == 0)
150 return uint.max;
151 return errorSupplementLimit;
152 }
153 }
154
155 extern (C++) struct ImportPathInfo {
156 const(char)* path; // char*'s of where to look for import modules
157 }
158
159 /// Put command line switches in here
160 extern (C++) struct Param
161 {
162 bool obj = true; // write object file
163 bool readStdin; // saw "-" on command line, read source file from stdin
164 bool multiobj; // break one object file into multiple ones
165 bool trace; // insert profiling hooks
166 bool tracegc; // instrument calls to 'new'
167 bool vcg_ast; // write-out codegen-ast
168 DiagnosticReporting useDeprecated = DiagnosticReporting.inform; // how use of deprecated features are handled
169 bool useUnitTests; // generate unittest code
170 bool useInline = false; // inline expand functions
171 bool release; // build release version
172 bool preservePaths; // true means don't strip path from source file
173 DiagnosticReporting useWarnings = DiagnosticReporting.off; // how compiler warnings are handled
174 bool cov; // generate code coverage data
175 ubyte covPercent; // 0..100 code coverage percentage required
176 bool ctfe_cov = false; // generate coverage data for ctfe
177 bool ignoreUnsupportedPragmas = true; // rather than error on them
178 bool useModuleInfo = true; // generate runtime module information
179 bool useTypeInfo = true; // generate runtime type information
180 bool useExceptions = true; // support exception handling
181 bool useGC = true; // support features that require the D runtime GC
182 bool betterC; // be a "better C" compiler; no dependency on D runtime
183 bool addMain; // add a default main() function
184 bool allInst; // generate code for all template instantiations
185 bool bitfields; // support C style bit fields
186
187 CppStdRevision cplusplus = CppStdRevision.cpp11; // version of C++ standard to support
188
189 Help help;
190 Verbose v;
191
192 // Options for `-preview=/-revert=`
193 FeatureState useDIP25 = FeatureState.enabled; // implement https://wiki.dlang.org/DIP25
194 FeatureState useDIP1000; // implement https://dlang.org/spec/memory-safe-d.html#scope-return-params
195 bool ehnogc; // use @nogc exception handling
196 bool useDIP1021; // implement https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1021.md
197 FeatureState fieldwise; // do struct equality testing field-wise rather than by memcmp()
198 bool fixAliasThis; // if the current scope has an alias this, check it before searching upper scopes
199 FeatureState rvalueRefParam; // allow rvalues to be arguments to ref parameters
200 // https://dconf.org/2019/talks/alexandrescu.html
201 // https://gist.github.com/andralex/e5405a5d773f07f73196c05f8339435a
202 // https://digitalmars.com/d/archives/digitalmars/D/Binding_rvalues_to_ref_parameters_redux_325087.html
203 // Implementation: https://github.com/dlang/dmd/pull/9817
204 FeatureState safer; // safer by default (more @safe checks in unattributed code)
205 // https://github.com/WalterBright/documents/blob/38f0a846726b571f8108f6e63e5e217b91421c86/safer.md
206 FeatureState noSharedAccess; // read/write access to shared memory objects
207 bool previewIn; // `in` means `[ref] scope const`, accepts rvalues
208 bool inclusiveInContracts; // 'in' contracts of overridden methods must be a superset of parent contract
209 bool shortenedMethods = true; // allow => in normal function declarations
210 bool fixImmutableConv; // error on unsound immutable conversion - https://github.com/dlang/dmd/pull/14070
211 bool fix16997 = true; // fix integral promotions for unary + - ~ operators
212 // https://issues.dlang.org/show_bug.cgi?id=16997
213 FeatureState dtorFields; // destruct fields of partially constructed objects
214 // https://issues.dlang.org/show_bug.cgi?id=14246
215 FeatureState systemVariables; // limit access to variables marked @system from @safe code
216
217 CHECKENABLE useInvariants = CHECKENABLE._default; // generate class invariant checks
218 CHECKENABLE useIn = CHECKENABLE._default; // generate precondition checks
219 CHECKENABLE useOut = CHECKENABLE._default; // generate postcondition checks
220 CHECKENABLE useArrayBounds = CHECKENABLE._default; // when to generate code for array bounds checks
221 CHECKENABLE useAssert = CHECKENABLE._default; // when to generate code for assert()'s
222 CHECKENABLE useSwitchError = CHECKENABLE._default; // check for switches without a default
223 CHECKENABLE boundscheck = CHECKENABLE._default; // state of -boundscheck switch
224
225 CHECKACTION checkAction = CHECKACTION.D; // action to take when bounds, asserts or switch defaults are violated
226
227 CLIIdentifierTable dIdentifierTable = CLIIdentifierTable.default_;
228 CLIIdentifierTable cIdentifierTable = CLIIdentifierTable.default_;
229
230 const(char)[] argv0; // program name
231 Array!(const(char)*) modFileAliasStrings; // array of char*'s of -I module filename alias strings
232 Array!(ImportPathInfo) imppath; // array of import path information of where to look for import modules
233 Array!(const(char)*) fileImppath; // array of char*'s of where to look for file import modules
234 const(char)[] objdir; // .obj/.lib file output directory
235 const(char)[] objname; // .obj file output name
236 const(char)[] libname; // .lib file output name
237
238 Output ddoc; // Generate embedded documentation comments
239 Output dihdr; // Generate `.di` 'header' files
240 Output cxxhdr; // Generate 'Cxx header' file
241 Output json; // Generate JSON file
242 JsonFieldFlags jsonFieldFlags; // JSON field flags to include
243 Output makeDeps; // Generate make file dependencies
244 Output mixinOut; // write expanded mixins for debugging
245 Output moduleDeps; // Generate `.deps` module dependencies
246
247 bool debugEnabled; // Global -debug flag (no -debug=XXX) is active
248
249 bool run; // run resulting executable
250 Strings runargs; // arguments for executable
251 Array!(const(char)*) cppswitches; // C preprocessor switches
252 const(char)* cpp; // if not null, then this specifies the C preprocessor
253
254 // Linker stuff
255 Array!(const(char)*) objfiles;
256 Array!(const(char)*) linkswitches;
257 Array!bool linkswitchIsForCC;
258 Array!(const(char)*) libfiles;
259 Array!(const(char)*) dllfiles;
260 const(char)[] deffile;
261 const(char)[] resfile;
262 const(char)[] exefile;
263 const(char)[] mapfile;
264
265 bool fullyQualifiedObjectFiles; // prepend module names to object files to prevent name conflicts with -od
266
267 // Time tracing
268 bool timeTrace = false; /// Whether profiling of compile time is enabled
269 uint timeTraceGranularityUs = 500; /// In microseconds, minimum event size to report
270 const(char)* timeTraceFile; /// File path of output file
271
272 ///
273 bool parsingUnittestsRequired() @safe
274 {
275 return useUnitTests || ddoc.doOutput || dihdr.doOutput;
276 }
277 }
278
279 enum mars_ext = "d"; // for D source files
280 enum doc_ext = "html"; // for Ddoc generated files
281 enum ddoc_ext = "ddoc"; // for Ddoc macro include files
282 enum dd_ext = "dd"; // for Ddoc source files
283 enum hdr_ext = "di"; // for D 'header' import files
284 enum json_ext = "json"; // for JSON files
285 enum map_ext = "map"; // for .map files
286 enum c_ext = "c"; // for C source files
287 enum i_ext = "i"; // for preprocessed C source file
288
289 /**
290 * Collection of global compiler settings and global state used by the frontend
291 */
292 extern (C++) struct Global
293 {
294 const(char)[] inifilename; /// filename of configuration file as given by `-conf=`, or default value
295
296 string copyright = "Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved";
297 string written = "written by Walter Bright";
298
299 Array!(ImportPathInfo) path; /// Array of path informations which form the import lookup path
300 Array!(const(char)*) importPaths; /// Array of char*'s which form the import lookup path without metadata
301 Array!(const(char)*) filePath; /// Array of char*'s which form the file import lookup path
302
303 private enum string _version = import("VERSION");
304 char[26] datetime; /// string returned by ctime()
305 CompileEnv compileEnv;
306
307 Param params; /// command line parameters
308 uint errors; /// number of errors reported so far
309 uint deprecations; /// number of deprecations reported so far
310 uint warnings; /// number of warnings reported so far
311 uint gag; /// !=0 means gag reporting of errors & warnings
312 uint gaggedErrors; /// number of errors reported while gagged
313 uint gaggedWarnings; /// number of warnings reported while gagged
314
315 void* console; /// opaque pointer to console for controlling text attributes
316
317 Array!Identifier versionids; /// command line versions and predefined versions
318 Array!Identifier debugids; /// command line debug versions and predefined versions
319
320 bool hasMainFunction; /// Whether a main function has already been compiled in (for -main switch)
321 uint varSequenceNumber = 1; /// Relative lifetime of `VarDeclaration` within a function, used for `scope` checks
322
323 /// Cache files read from disk
324 FileManager fileManager;
325
326 enum recursionLimit = 500; /// number of recursive template expansions before abort
327
328 ErrorSink errorSink; /// where the error messages go
329 ErrorSink errorSinkNull; /// where the error messages are ignored
330
331 extern (C++) DArray!ubyte function(FileName, Loc, ref OutBuffer) preprocess;
332
333 nothrow:
334
335 /**
336 * Start ignoring compile errors instead of reporting them.
337 *
338 * Used for speculative compilation like `__traits(compiles, XXX)`, but also internally
339 * to e.g. try out an `alias this` rewrite without comitting to it.
340 *
341 * Works like a stack, so N calls to `startGagging` should be paired with N
342 * calls to `endGagging`.
343 *
344 * Returns: the current number of gagged errors, which should later be passed to `endGagging`
345 */
346 extern (C++) uint startGagging() @safe
347 {
348 ++gag;
349 gaggedWarnings = 0;
350 return gaggedErrors;
351 }
352
353 /**
354 * Stop gagging, restoring the old gagged state before the most recent call to `startGagging`.
355 *
356 * Params:
357 * oldGagged = the previous number of errors, as returned by `startGagging`
358 * Returns: true if errors occurred while gagged.
359 */
360 extern (C++) bool endGagging(uint oldGagged) @safe
361 {
362 bool anyErrs = (gaggedErrors != oldGagged);
363 --gag;
364 // Restore the original state of gagged errors; set total errors
365 // to be original errors + new ungagged errors.
366 errors -= (gaggedErrors - oldGagged);
367 gaggedErrors = oldGagged;
368 return anyErrs;
369 }
370
371 /**
372 * Increment the error count to record that an error has occurred in the current context.
373 *
374 * An error message may or may not have been printed.
375 */
376 extern (C++) void increaseErrorCount() @safe
377 {
378 if (gag)
379 ++gaggedErrors;
380 ++errors;
381 }
382
383 extern (C++) void _init()
384 {
385 errorSink = new ErrorSinkCompiler;
386 errorSinkNull = new ErrorSinkNull;
387
388 this.fileManager = new FileManager();
389 version (MARS)
390 {
391 compileEnv.vendor = "Digital Mars D";
392
393 // -color=auto is the default value
394 import dmd.console : detectTerminal, detectColorPreference;
395 params.v.color = detectTerminal() && detectColorPreference();
396 }
397 else version (IN_GCC)
398 {
399 compileEnv.vendor = "GNU D";
400 }
401 else version (IN_LLVM)
402 {
403 compileEnv.vendor = "LDC";
404
405 import dmd.console : detectTerminal;
406 params.v.color = detectTerminal();
407 }
408
409 params.v.errorPrintMode = ErrorPrintMode.printErrorContext; // Enable error context globally by default
410 compileEnv.versionNumber = parseVersionNumber(versionString());
411
412 /* Initialize date, time, and timestamp
413 */
414 import core.stdc.time;
415 import core.stdc.stdlib : getenv;
416
417 time_t ct;
418 // https://issues.dlang.org/show_bug.cgi?id=20444
419 if (auto p = getenv("SOURCE_DATE_EPOCH"))
420 {
421 if (!ct.parseDigits(p[0 .. strlen(p)]))
422 errorSink.error(Loc.initial, "value of environment variable `SOURCE_DATE_EPOCH` should be a valid UNIX timestamp, not: `%s`", p);
423 }
424 else
425 core.stdc.time.time(&ct);
426 const p = ctime(&ct);
427 assert(p);
428 datetime[] = p[0 .. 26];
429
430 __gshared char[11 + 1] date = 0; // put in BSS segment
431 __gshared char[8 + 1] time = 0;
432 __gshared char[24 + 1] timestamp = 0;
433
434 const dsz = snprintf(&date[0], date.length, "%.6s %.4s", p + 4, p + 20);
435 const tsz = snprintf(&time[0], time.length, "%.8s", p + 11);
436 const tssz = snprintf(&timestamp[0], timestamp.length, "%.24s", p);
437 assert(dsz > 0 && tsz > 0 && tssz > 0);
438 compileEnv.time = time[0 .. tsz];
439 compileEnv.date = date[0 .. dsz];
440 compileEnv.timestamp = timestamp[0 .. tssz];
441 }
442
443 /**
444 * Deinitializes the global state of the compiler.
445 *
446 * This can be used to restore the state set by `_init` to its original
447 * state.
448 */
449 extern (D) void deinitialize()
450 {
451 this = this.init;
452 }
453
454 /**
455 * Computes the version number __VERSION__ from the compiler version string.
456 */
457 extern (D) private static uint parseVersionNumber(string version_) @safe
458 {
459 //
460 // parse _version
461 //
462 uint major = 0;
463 uint minor = 0;
464 bool point = false;
465 // skip initial 'v'
466 foreach (const c; version_[1..$])
467 {
468 if ('0' <= c && c <= '9') // isdigit
469 {
470 minor = minor * 10 + c - '0';
471 }
472 else if (c == '.')
473 {
474 if (point)
475 break; // ignore everything after second '.'
476 point = true;
477 major = minor;
478 minor = 0;
479 }
480 else
481 break;
482 }
483 return major * 1000 + minor;
484 }
485
486 /**
487 * Indicate to stateful error sinks that no more errors can be produced.
488 * This is to support error sinks that collect information to produce a
489 * single (say) report.
490 */
491 extern(C++) void plugErrorSinks()
492 {
493 global.errorSink.plugSink();
494 global.errorSinkNull.plugSink();
495 }
496
497 /**
498 Returns: the version as the number that would be returned for __VERSION__
499 */
500 extern(C++) uint versionNumber() @safe
501 {
502 return compileEnv.versionNumber;
503 }
504
505 /**
506 Returns: compiler version string.
507 */
508 extern(D) string versionString() @safe
509 {
510 return _version;
511 }
512
513 /**
514 Returns: compiler version as char string.
515 */
516 extern(C++) const(char*) versionChars()
517 {
518 return _version.ptr;
519 }
520 }
521
522 // Because int64_t and friends may be any integral type of the
523 // correct size, we have to explicitly ask for the correct
524 // integer type to get the correct mangling with dmd
525
526 // Be careful not to care about sign when using dinteger_t
527 // use this instead of integer_t to
528 // avoid conflicts with system #include's
529 alias dinteger_t = ulong;
530 // Signed and unsigned variants
531 alias sinteger_t = long;
532 alias uinteger_t = ulong;
533
534 /// Collection of global state
535 extern (C++) __gshared Global global;