d: Merge upstream dmd 3982604c5, druntime bc58b1e9, phobos 12329adb6.
[official-gcc.git] / gcc / d / dmd / globals.d
blob7409dcc290273ef489325bae58c2281db4e957cf
1 /**
2 * Stores command line options and contains other miscellaneous declarations.
4 * Copyright: Copyright (C) 1999-2021 by The D Language Foundation, All Rights Reserved
5 * Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
6 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/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/src/dmd/globals.d
12 module dmd.globals;
14 import core.stdc.stdint;
15 import dmd.root.array;
16 import dmd.root.filename;
17 import dmd.common.outbuffer;
18 import dmd.identifier;
20 /// Defines a setting for how compiler warnings and deprecations are handled
21 enum DiagnosticReporting : ubyte
23 error, /// generate an error
24 inform, /// generate a warning
25 off, /// disable diagnostic
28 /// How code locations are formatted for diagnostic reporting
29 enum MessageStyle : ubyte
31 digitalmars, /// filename.d(line): message
32 gnu, /// filename.d:line: message, see https://www.gnu.org/prep/standards/html_node/Errors.html
35 /// In which context checks for assertions, contracts, bounds checks etc. are enabled
36 enum CHECKENABLE : ubyte
38 _default, /// initial value
39 off, /// never do checking
40 on, /// always do checking
41 safeonly, /// do checking only in @safe functions
44 /// What should happend when an assertion fails
45 enum CHECKACTION : ubyte
47 D, /// call D assert on failure
48 C, /// call C assert on failure
49 halt, /// cause program halt on failure
50 context, /// call D assert with the error context on failure
53 /// Position Indepent Code setting
54 enum PIC : ubyte
56 fixed, /// located at a specific address
57 pic, /// Position Independent Code
58 pie, /// Position Independent Executable
61 /**
62 Each flag represents a field that can be included in the JSON output.
64 NOTE: set type to uint so its size matches C++ unsigned type
66 enum JsonFieldFlags : uint
68 none = 0,
69 compilerInfo = (1 << 0),
70 buildInfo = (1 << 1),
71 modules = (1 << 2),
72 semantics = (1 << 3),
75 /// Version of C++ standard to support
76 enum CppStdRevision : uint
78 cpp98 = 1997_11,
79 cpp11 = 2011_03,
80 cpp14 = 2014_02,
81 cpp17 = 2017_03,
82 cpp20 = 2020_02,
85 /// Configuration for the C++ header generator
86 enum CxxHeaderMode : uint
88 none, /// Don't generate headers
89 silent, /// Generate headers
90 verbose /// Generate headers and add comments for hidden declarations
93 /// Trivalent boolean to represent the state of a `revert`able change
94 enum FeatureState : byte
96 default_ = -1, /// Not specified by the user
97 disabled = 0, /// Specified as `-revert=`
98 enabled = 1 /// Specified as `-preview=`
101 /// Put command line switches in here
102 extern (C++) struct Param
104 bool obj = true; // write object file
105 bool link = true; // perform link
106 bool dll; // generate shared dynamic library
107 bool lib; // write library file instead of object file(s)
108 bool multiobj; // break one object file into multiple ones
109 bool oneobj; // write one object file instead of multiple ones
110 bool trace; // insert profiling hooks
111 bool tracegc; // instrument calls to 'new'
112 bool verbose; // verbose compile
113 bool vcg_ast; // write-out codegen-ast
114 bool showColumns; // print character (column) numbers in diagnostics
115 bool vtls; // identify thread local variables
116 bool vtemplates; // collect and list statistics on template instantiations
117 bool vtemplatesListInstances; // collect and list statistics on template instantiations origins. TODO: make this an enum when we want to list other kinds of instances
118 bool vgc; // identify gc usage
119 bool vfield; // identify non-mutable field variables
120 bool vcomplex = true; // identify complex/imaginary type usage
121 bool vin; // identify 'in' parameters
122 ubyte symdebug; // insert debug symbolic information
123 bool symdebugref; // insert debug information for all referenced types, too
124 bool optimize; // run optimizer
125 DiagnosticReporting useDeprecated = DiagnosticReporting.inform; // how use of deprecated features are handled
126 bool stackstomp; // add stack stomping code
127 bool useUnitTests; // generate unittest code
128 bool useInline = false; // inline expand functions
129 FeatureState useDIP25; // implement http://wiki.dlang.org/DIP25
130 FeatureState useDIP1000; // implement https://dlang.org/spec/memory-safe-d.html#scope-return-params
131 bool useDIP1021; // implement https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1021.md
132 bool release; // build release version
133 bool preservePaths; // true means don't strip path from source file
134 DiagnosticReporting warnings = DiagnosticReporting.off; // how compiler warnings are handled
135 PIC pic = PIC.fixed; // generate fixed, pic or pie code
136 bool color; // use ANSI colors in console output
137 bool cov; // generate code coverage data
138 ubyte covPercent; // 0..100 code coverage percentage required
139 bool ctfe_cov = false; // generate coverage data for ctfe
140 bool nofloat; // code should not pull in floating point support
141 bool ignoreUnsupportedPragmas; // rather than error on them
142 bool useModuleInfo = true; // generate runtime module information
143 bool useTypeInfo = true; // generate runtime type information
144 bool useExceptions = true; // support exception handling
145 bool noSharedAccess; // read/write access to shared memory objects
146 bool previewIn; // `in` means `[ref] scope const`, accepts rvalues
147 bool shortenedMethods; // allow => in normal function declarations
148 bool betterC; // be a "better C" compiler; no dependency on D runtime
149 bool addMain; // add a default main() function
150 bool allInst; // generate code for all template instantiations
151 bool fix16997 = true; // fix integral promotions for unary + - ~ operators
152 // https://issues.dlang.org/show_bug.cgi?id=16997
153 bool fixAliasThis; // if the current scope has an alias this, check it before searching upper scopes
154 bool inclusiveInContracts; // 'in' contracts of overridden methods must be a superset of parent contract
155 /** The --transition=safe switch should only be used to show code with
156 * silent semantics changes related to @safe improvements. It should not be
157 * used to hide a feature that will have to go through deprecate-then-error
158 * before becoming default.
160 bool ehnogc; // use @nogc exception handling
161 FeatureState dtorFields; // destruct fields of partially constructed objects
162 // https://issues.dlang.org/show_bug.cgi?id=14246
163 bool fieldwise; // do struct equality testing field-wise rather than by memcmp()
164 bool rvalueRefParam; // allow rvalues to be arguments to ref parameters
165 // http://dconf.org/2019/talks/alexandrescu.html
166 // https://gist.github.com/andralex/e5405a5d773f07f73196c05f8339435a
167 // https://digitalmars.com/d/archives/digitalmars/D/Binding_rvalues_to_ref_parameters_redux_325087.html
168 // Implementation: https://github.com/dlang/dmd/pull/9817
170 CppStdRevision cplusplus = CppStdRevision.cpp11; // version of C++ standard to support
172 bool markdown = true; // enable Markdown replacements in Ddoc
173 bool vmarkdown; // list instances of Markdown replacements in Ddoc
175 bool showGaggedErrors; // print gagged errors anyway
176 bool printErrorContext; // print errors with the error context (the error line in the source file)
177 bool manual; // open browser on compiler manual
178 bool usage; // print usage and exit
179 bool mcpuUsage; // print help on -mcpu switch
180 bool transitionUsage; // print help on -transition switch
181 bool checkUsage; // print help on -check switch
182 bool checkActionUsage; // print help on -checkaction switch
183 bool revertUsage; // print help on -revert switch
184 bool previewUsage; // print help on -preview switch
185 bool externStdUsage; // print help on -extern-std switch
186 bool hcUsage; // print help on -HC switch
187 bool logo; // print compiler logo
189 CHECKENABLE useInvariants = CHECKENABLE._default; // generate class invariant checks
190 CHECKENABLE useIn = CHECKENABLE._default; // generate precondition checks
191 CHECKENABLE useOut = CHECKENABLE._default; // generate postcondition checks
192 CHECKENABLE useArrayBounds = CHECKENABLE._default; // when to generate code for array bounds checks
193 CHECKENABLE useAssert = CHECKENABLE._default; // when to generate code for assert()'s
194 CHECKENABLE useSwitchError = CHECKENABLE._default; // check for switches without a default
195 CHECKENABLE boundscheck = CHECKENABLE._default; // state of -boundscheck switch
197 CHECKACTION checkAction = CHECKACTION.D; // action to take when bounds, asserts or switch defaults are violated
199 uint errorLimit = 20;
201 const(char)[] argv0; // program name
202 Array!(const(char)*) modFileAliasStrings; // array of char*'s of -I module filename alias strings
203 Array!(const(char)*)* imppath; // array of char*'s of where to look for import modules
204 Array!(const(char)*)* fileImppath; // array of char*'s of where to look for file import modules
205 const(char)[] objdir; // .obj/.lib file output directory
206 const(char)[] objname; // .obj file output name
207 const(char)[] libname; // .lib file output name
209 bool doDocComments; // process embedded documentation comments
210 const(char)[] docdir; // write documentation file to docdir directory
211 const(char)[] docname; // write documentation file to docname
212 Array!(const(char)*) ddocfiles; // macro include files for Ddoc
214 bool doHdrGeneration; // process embedded documentation comments
215 const(char)[] hdrdir; // write 'header' file to docdir directory
216 const(char)[] hdrname; // write 'header' file to docname
217 bool hdrStripPlainFunctions = true; // strip the bodies of plain (non-template) functions
219 CxxHeaderMode doCxxHdrGeneration; /// Generate 'Cxx header' file
220 const(char)[] cxxhdrdir; // write 'header' file to docdir directory
221 const(char)[] cxxhdrname; // write 'header' file to docname
223 bool doJsonGeneration; // write JSON file
224 const(char)[] jsonfilename; // write JSON file to jsonfilename
225 JsonFieldFlags jsonFieldFlags; // JSON field flags to include
227 OutBuffer* mixinOut; // write expanded mixins for debugging
228 const(char)* mixinFile; // .mixin file output name
229 int mixinLines; // Number of lines in writeMixins
231 uint debuglevel; // debug level
232 Array!(const(char)*)* debugids; // debug identifiers
234 uint versionlevel; // version level
235 Array!(const(char)*)* versionids; // version identifiers
237 const(char)[] defaultlibname; // default library for non-debug builds
238 const(char)[] debuglibname; // default library for debug builds
239 const(char)[] mscrtlib; // MS C runtime library
241 const(char)[] moduleDepsFile; // filename for deps output
242 OutBuffer* moduleDeps; // contents to be written to deps file
244 bool emitMakeDeps; // whether to emit makedeps
245 const(char)[] makeDepsFile; // filename for makedeps output
246 Array!(const(char)*) makeDeps; // dependencies for makedeps
248 MessageStyle messageStyle = MessageStyle.digitalmars; // style of file/line annotations on messages
250 bool run; // run resulting executable
251 Strings runargs; // arguments for executable
253 // Linker stuff
254 Array!(const(char)*) objfiles;
255 Array!(const(char)*) linkswitches;
256 Array!bool linkswitchIsForCC;
257 Array!(const(char)*) libfiles;
258 Array!(const(char)*) dllfiles;
259 const(char)[] deffile;
260 const(char)[] resfile;
261 const(char)[] exefile;
262 const(char)[] mapfile;
265 extern (C++) struct structalign_t
267 private:
268 ushort value = 0; // unknown
269 enum STRUCTALIGN_DEFAULT = 1234; // default = match whatever the corresponding C compiler does
270 bool pack; // use #pragma pack semantics
272 public:
273 pure @safe @nogc nothrow:
274 bool isDefault() const { return value == STRUCTALIGN_DEFAULT; }
275 void setDefault() { value = STRUCTALIGN_DEFAULT; }
276 bool isUnknown() const { return value == 0; } // value is not set
277 void setUnknown() { value = 0; }
278 void set(uint value) { this.value = cast(ushort)value; }
279 uint get() const { return value; }
280 bool isPack() const { return pack; }
281 void setPack(bool pack) { this.pack = pack; }
283 //alias structalign_t = uint;
285 // magic value means "match whatever the underlying C compiler does"
286 // other values are all powers of 2
287 //enum STRUCTALIGN_DEFAULT = (cast(structalign_t)~0);
289 enum mars_ext = "d"; // for D source files
290 enum doc_ext = "html"; // for Ddoc generated files
291 enum ddoc_ext = "ddoc"; // for Ddoc macro include files
292 enum dd_ext = "dd"; // for Ddoc source files
293 enum hdr_ext = "di"; // for D 'header' import files
294 enum json_ext = "json"; // for JSON files
295 enum map_ext = "map"; // for .map files
296 enum c_ext = "c"; // for C source files
297 enum i_ext = "i"; // for preprocessed C source file
300 * Collection of global compiler settings and global state used by the frontend
302 extern (C++) struct Global
304 const(char)[] inifilename; /// filename of configuration file as given by `-conf=`, or default value
306 string copyright = "Copyright (C) 1999-2021 by The D Language Foundation, All Rights Reserved";
307 string written = "written by Walter Bright";
309 Array!(const(char)*)* path; /// Array of char*'s which form the import lookup path
310 Array!(const(char)*)* filePath; /// Array of char*'s which form the file import lookup path
312 private enum string _version = import("VERSION");
313 private enum uint _versionNumber = parseVersionNumber(_version);
315 const(char)[] vendor; /// Compiler backend name
317 Param params; /// command line parameters
318 uint errors; /// number of errors reported so far
319 uint warnings; /// number of warnings reported so far
320 uint gag; /// !=0 means gag reporting of errors & warnings
321 uint gaggedErrors; /// number of errors reported while gagged
322 uint gaggedWarnings; /// number of warnings reported while gagged
324 void* console; /// opaque pointer to console for controlling text attributes
326 Array!Identifier* versionids; /// command line versions and predefined versions
327 Array!Identifier* debugids; /// command line debug versions and predefined versions
329 bool hasMainFunction; /// Whether a main function has already been compiled in (for -main switch)
331 enum recursionLimit = 500; /// number of recursive template expansions before abort
333 nothrow:
336 * Start ignoring compile errors instead of reporting them.
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.
341 * Works like a stack, so N calls to `startGagging` should be paired with N
342 * calls to `endGagging`.
344 * Returns: the current number of gagged errors, which should later be passed to `endGagging`
346 extern (C++) uint startGagging()
348 ++gag;
349 gaggedWarnings = 0;
350 return gaggedErrors;
354 * Stop gagging, restoring the old gagged state before the most recent call to `startGagging`.
356 * Params:
357 * oldGagged = the previous number of errors, as returned by `startGagging`
358 * Returns: true if errors occurred while gagged.
360 extern (C++) bool endGagging(uint oldGagged)
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;
372 * Increment the error count to record that an error has occurred in the current context.
374 * An error message may or may not have been printed.
376 extern (C++) void increaseErrorCount()
378 if (gag)
379 ++gaggedErrors;
380 ++errors;
383 extern (C++) void _init()
385 version (MARS)
387 vendor = "Digital Mars D";
389 // -color=auto is the default value
390 import dmd.console : detectTerminal;
391 params.color = detectTerminal();
393 else version (IN_GCC)
395 vendor = "GNU D";
400 * Deinitializes the global state of the compiler.
402 * This can be used to restore the state set by `_init` to its original
403 * state.
405 extern (D) void deinitialize()
407 this = this.init;
411 * Computes the version number __VERSION__ from the compiler version string.
413 extern (D) private static uint parseVersionNumber(string version_)
416 // parse _version
418 uint major = 0;
419 uint minor = 0;
420 bool point = false;
421 // skip initial 'v'
422 foreach (const c; version_[1..$])
424 if ('0' <= c && c <= '9') // isdigit
426 minor = minor * 10 + c - '0';
428 else if (c == '.')
430 if (point)
431 break; // ignore everything after second '.'
432 point = true;
433 major = minor;
434 minor = 0;
436 else
437 break;
439 return major * 1000 + minor;
443 Returns: the version as the number that would be returned for __VERSION__
445 extern(C++) uint versionNumber()
447 return _versionNumber;
451 Returns: compiler version string.
453 extern(D) string versionString()
455 return _version;
459 Returns: compiler version as char string.
461 extern(C++) const(char*) versionChars()
463 return _version.ptr;
467 Returns: the final defaultlibname based on the command-line parameters
469 extern (D) const(char)[] finalDefaultlibname() const
471 return params.betterC ? null :
472 params.symdebug ? params.debuglibname : params.defaultlibname;
476 // Because int64_t and friends may be any integral type of the
477 // correct size, we have to explicitly ask for the correct
478 // integer type to get the correct mangling with dmd
480 // Be careful not to care about sign when using dinteger_t
481 // use this instead of integer_t to
482 // avoid conflicts with system #include's
483 alias dinteger_t = ulong;
484 // Signed and unsigned variants
485 alias sinteger_t = long;
486 alias uinteger_t = ulong;
488 alias d_int8 = int8_t;
489 alias d_uns8 = uint8_t;
490 alias d_int16 = int16_t;
491 alias d_uns16 = uint16_t;
492 alias d_int32 = int32_t;
493 alias d_uns32 = uint32_t;
494 alias d_int64 = int64_t;
495 alias d_uns64 = uint64_t;
497 version (DMDLIB)
499 version = LocOffset;
503 A source code location
505 Used for error messages, `__FILE__` and `__LINE__` tokens, `__traits(getLocation, XXX)`,
506 debug info etc.
508 struct Loc
510 /// zero-terminated filename string, either absolute or relative to cwd
511 const(char)* filename;
512 uint linnum; /// line number, starting from 1
513 uint charnum; /// utf8 code unit index relative to start of line, starting from 1
514 version (LocOffset)
515 uint fileOffset; /// utf8 code unit index relative to start of file, starting from 0
517 static immutable Loc initial; /// use for default initialization of const ref Loc's
519 nothrow:
520 extern (D) this(const(char)* filename, uint linnum, uint charnum) pure
522 this.linnum = linnum;
523 this.charnum = charnum;
524 this.filename = filename;
527 extern (C++) const(char)* toChars(
528 bool showColumns = global.params.showColumns,
529 ubyte messageStyle = global.params.messageStyle) const pure nothrow
531 OutBuffer buf;
532 if (filename)
534 buf.writestring(filename);
536 if (linnum)
538 final switch (messageStyle)
540 case MessageStyle.digitalmars:
541 buf.writeByte('(');
542 buf.print(linnum);
543 if (showColumns && charnum)
545 buf.writeByte(',');
546 buf.print(charnum);
548 buf.writeByte(')');
549 break;
550 case MessageStyle.gnu: // https://www.gnu.org/prep/standards/html_node/Errors.html
551 buf.writeByte(':');
552 buf.print(linnum);
553 if (showColumns && charnum)
555 buf.writeByte(':');
556 buf.print(charnum);
558 break;
561 return buf.extractChars();
565 * Checks for equivalence by comparing the filename contents (not the pointer) and character location.
567 * Note:
568 * - Uses case-insensitive comparison on Windows
569 * - Ignores `charnum` if `global.params.showColumns` is false.
571 extern (C++) bool equals(ref const(Loc) loc) const
573 return (!global.params.showColumns || charnum == loc.charnum) &&
574 linnum == loc.linnum &&
575 FileName.equals(filename, loc.filename);
579 * `opEquals()` / `toHash()` for AA key usage
581 * Compare filename contents (case-sensitively on Windows too), not
582 * the pointer - a static foreach loop repeatedly mixing in a mixin
583 * may lead to multiple equivalent filenames (`foo.d-mixin-<line>`),
584 * e.g., for test/runnable/test18880.d.
586 extern (D) bool opEquals(ref const(Loc) loc) const @trusted pure nothrow @nogc
588 import core.stdc.string : strcmp;
590 return charnum == loc.charnum &&
591 linnum == loc.linnum &&
592 (filename == loc.filename ||
593 (filename && loc.filename && strcmp(filename, loc.filename) == 0));
596 /// ditto
597 extern (D) size_t toHash() const @trusted pure nothrow
599 import dmd.root.string : toDString;
601 auto hash = hashOf(linnum);
602 hash = hashOf(charnum, hash);
603 hash = hashOf(filename.toDString, hash);
604 return hash;
607 /******************
608 * Returns:
609 * true if Loc has been set to other than the default initialization
611 bool isValid() const pure
613 return filename !is null;
617 /// A linkage attribute as defined by `extern(XXX)`
619 /// https://dlang.org/spec/attribute.html#linkage
620 enum LINK : ubyte
622 default_,
625 cpp,
626 windows,
627 objc,
628 system,
631 /// Whether to mangle an external aggregate as a struct or class, as set by `extern(C++, struct)`
632 enum CPPMANGLE : ubyte
634 def, /// default
635 asStruct, /// `extern(C++, struct)`
636 asClass, /// `extern(C++, class)`
639 /// Function match levels
641 /// https://dlang.org/spec/function.html#function-overloading
642 enum MATCH : int
644 nomatch, /// no match
645 convert, /// match with conversions
646 constant, /// match with conversion to const
647 exact, /// exact match
650 /// Inline setting as defined by `pragma(inline, XXX)`
651 enum PINLINE : ubyte
653 default_, /// as specified on the command line
654 never, /// never inline
655 always, /// always inline
658 alias StorageClass = uinteger_t;
660 /// Collection of global state
661 extern (C++) __gshared Global global;