1
2 /* Compiler implementation of the D programming language
3 * Copyright (C) 1999-2023 by The D Language Foundation, All Rights Reserved
4 * written by Walter Bright
5 * https://www.digitalmars.com
6 * Distributed under the Boost Software License, Version 1.0.
7 * https://www.boost.org/LICENSE_1_0.txt
8 * https://github.com/dlang/dmd/blob/master/src/dmd/globals.h
9 */
10
11 #pragma once
12
13 #include "root/dcompat.h"
14 #include "root/ctfloat.h"
15 #include "common/outbuffer.h"
16 #include "root/filename.h"
17 #include "compiler.h"
18
19 // Can't include arraytypes.h here, need to declare these directly.
20 template <typename TYPE> struct Array;
21
22 class ErrorSink;
23 class FileManager;
24 struct Loc;
25
26 typedef unsigned char Diagnostic;
27 enum
28 {
29 DIAGNOSTICerror, // generate an error
30 DIAGNOSTICinform, // generate a warning
31 DIAGNOSTICoff // disable diagnostic
32 };
33
34 enum class MessageStyle : unsigned char
35 {
36 digitalmars, // file(line,column): message
37 gnu // file:line:column: message
38 };
39
40 // The state of array bounds checking
41 typedef unsigned char CHECKENABLE;
42 enum
43 {
44 CHECKENABLEdefault, // initial value
45 CHECKENABLEoff, // never do bounds checking
46 CHECKENABLEon, // always do bounds checking
47 CHECKENABLEsafeonly // do bounds checking only in @safe functions
48 };
49
50 typedef unsigned char CHECKACTION;
51 enum
52 {
53 CHECKACTION_D, // call D assert on failure
54 CHECKACTION_C, // call C assert on failure
55 CHECKACTION_halt, // cause program halt on failure
56 CHECKACTION_context // call D assert with the error context on failure
57 };
58
59 enum JsonFieldFlags
60 {
61 none = 0,
62 compilerInfo = (1 << 0),
63 buildInfo = (1 << 1),
64 modules = (1 << 2),
65 semantics = (1 << 3)
66 };
67
68 enum CppStdRevision
69 {
70 CppStdRevisionCpp98 = 199711,
71 CppStdRevisionCpp11 = 201103,
72 CppStdRevisionCpp14 = 201402,
73 CppStdRevisionCpp17 = 201703,
74 CppStdRevisionCpp20 = 202002
75 };
76
77 /// Trivalent boolean to represent the state of a `revert`able change
78 enum class FeatureState : signed char
79 {
80 default_ = -1, /// Not specified by the user
81 disabled = 0, /// Specified as `-revert=`
82 enabled = 1 /// Specified as `-preview=`
83 };
84
85 struct Output
86 {
87 /// Configuration for the compiler generator
88 d_bool doOutput; // Output is enabled
89 d_bool fullOutput; // Generate comments for hidden declarations (for -HC),
90 // and don't strip the bodies of plain (non-template) functions (for -H)
91 DString dir; // write to directory 'dir'
92 DString name; // write to file 'name'
93 Array<const char*> files; // Other files associated with this output,
94 // e.g. macro include files for Ddoc, dependencies for makedeps
95 OutBuffer* buffer; // if this output is buffered, this is the buffer
96 int bufferLines; // number of lines written to the buffer
97 };
98
99 // Put command line switches in here
100 struct Param
101 {
102 d_bool obj; // write object file
103 d_bool multiobj; // break one object file into multiple ones
104 d_bool trace; // insert profiling hooks
105 d_bool tracegc; // instrument calls to 'new'
106 d_bool verbose; // verbose compile
107 d_bool vcg_ast; // write-out codegen-ast
108 d_bool showColumns; // print character (column) numbers in diagnostics
109 d_bool vtls; // identify thread local variables
110 d_bool vtemplates; // collect and list statistics on template instantiations
111 d_bool vtemplatesListInstances; // collect and list statistics on template instantiations origins
112 d_bool vgc; // identify gc usage
113 d_bool vfield; // identify non-mutable field variables
114 d_bool vcomplex; // identify complex/imaginary type usage
115 d_bool vin; // identify 'in' parameters
116 Diagnostic useDeprecated;
117 d_bool useUnitTests; // generate unittest code
118 d_bool useInline; // inline expand functions
119 d_bool release; // build release version
120 d_bool preservePaths; // true means don't strip path from source file
121 Diagnostic warnings;
122 d_bool color; // use ANSI colors in console output
123 d_bool cov; // generate code coverage data
124 unsigned char covPercent; // 0..100 code coverage percentage required
125 d_bool ctfe_cov; // generate coverage data for ctfe
126 d_bool ignoreUnsupportedPragmas; // rather than error on them
127 d_bool useModuleInfo; // generate runtime module information
128 d_bool useTypeInfo; // generate runtime type information
129 d_bool useExceptions; // support exception handling
130 d_bool betterC; // be a "better C" compiler; no dependency on D runtime
131 d_bool addMain; // add a default main() function
132 d_bool allInst; // generate code for all template instantiations
133 d_bool bitfields; // support C style bit fields
134 CppStdRevision cplusplus; // version of C++ name mangling to support
135 d_bool showGaggedErrors; // print gagged errors anyway
136 d_bool printErrorContext; // print errors with the error context (the error line in the source file)
137 d_bool manual; // open browser on compiler manual
138 d_bool usage; // print usage and exit
139 d_bool mcpuUsage; // print help on -mcpu switch
140 d_bool transitionUsage; // print help on -transition switch
141 d_bool checkUsage; // print help on -check switch
142 d_bool checkActionUsage; // print help on -checkaction switch
143 d_bool revertUsage; // print help on -revert switch
144 d_bool previewUsage; // print help on -preview switch
145 d_bool externStdUsage; // print help on -extern-std switch
146 d_bool hcUsage; // print help on -HC switch
147 d_bool logo; // print logo;
148
149 // Options for `-preview=/-revert=`
150 FeatureState useDIP25; // implement https://wiki.dlang.org/DIP25
151 FeatureState useDIP1000; // implement https://dlang.org/spec/memory-safe-d.html#scope-return-params
152 d_bool ehnogc; // use @nogc exception handling
153 d_bool useDIP1021; // implement https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1021.md
154 d_bool fieldwise; // do struct equality testing field-wise rather than by memcmp()
155 d_bool fixAliasThis; // if the current scope has an alias this, check it before searching upper scopes
156 FeatureState rvalueRefParam; // allow rvalues to be arguments to ref parameters
157 // https://dconf.org/2019/talks/alexandrescu.html
158 // https://gist.github.com/andralex/e5405a5d773f07f73196c05f8339435a
159 // https://digitalmars.com/d/archives/digitalmars/D/Binding_rvalues_to_ref_parameters_redux_325087.html
160 // Implementation: https://github.com/dlang/dmd/pull/9817
161 FeatureState noSharedAccess; // read/write access to shared memory objects
162 d_bool previewIn; // `in` means `[ref] scope const`, accepts rvalues
163 d_bool inclusiveInContracts; // 'in' contracts of overridden methods must be a superset of parent contract
164 d_bool shortenedMethods; // allow => in normal function declarations
165 d_bool fixImmutableConv; // error on unsound immutable conversion - https://github.com/dlang/dmd/pull/14070
166 d_bool fix16997; // fix integral promotions for unary + - ~ operators
167 // https://issues.dlang.org/show_bug.cgi?id=16997
168 FeatureState dtorFields; // destruct fields of partially constructed objects
169 // https://issues.dlang.org/show_bug.cgi?id=14246
170 FeatureState systemVariables; // limit access to variables marked @system from @safe code
171
172 CHECKENABLE useInvariants; // generate class invariant checks
173 CHECKENABLE useIn; // generate precondition checks
174 CHECKENABLE useOut; // generate postcondition checks
175 CHECKENABLE useArrayBounds; // when to generate code for array bounds checks
176 CHECKENABLE useAssert; // when to generate code for assert()'s
177 CHECKENABLE useSwitchError; // check for switches without a default
178 CHECKENABLE boundscheck; // state of -boundscheck switch
179
180 CHECKACTION checkAction; // action to take when bounds, asserts or switch defaults are violated
181
182 unsigned errorLimit;
183 unsigned errorSupplementLimit; // Limit the number of supplemental messages for each error (0 means unlimited)
184
185 DString argv0; // program name
186 Array<const char *> modFileAliasStrings; // array of char*'s of -I module filename alias strings
187 Array<const char *> *imppath; // array of char*'s of where to look for import modules
188 Array<const char *> *fileImppath; // array of char*'s of where to look for file import modules
189 DString objdir; // .obj/.lib file output directory
190 DString objname; // .obj file output name
191 DString libname; // .lib file output name
192
193 Output ddoc; // Generate embedded documentation comments
194 Output dihdr; // Generate `.di` 'header' files
195 Output cxxhdr; // Generate 'Cxx header' file
196 Output json; // Generate JSON file
197 unsigned jsonFieldFlags; // JSON field flags to include
198 Output makeDeps; // Generate make file dependencies
199 Output mixinOut; // write expanded mixins for debugging
200 Output moduleDeps; // Generate `.deps` module dependencies
201
202 unsigned debuglevel; // debug level
203 Array<const char *> *debugids; // debug identifiers
204
205 unsigned versionlevel; // version level
206 Array<const char *> *versionids; // version identifiers
207
208
209 MessageStyle messageStyle; // style of file/line annotations on messages
210
211 d_bool run; // run resulting executable
212 Strings runargs; // arguments for executable
213
214 Array<const char *> cppswitches; // preprocessor switches
215
216 // Linker stuff
217 Array<const char *> objfiles;
218 Array<const char *> linkswitches;
219 Array<bool> linkswitchIsForCC;
220 Array<const char *> libfiles;
221 Array<const char *> dllfiles;
222 DString deffile;
223 DString resfile;
224 DString exefile;
225 DString mapfile;
226 };
227
228 struct structalign_t
229 {
230 unsigned short value;
231 d_bool pack;
232
233 bool isDefault() const;
234 void setDefault();
235 bool isUnknown() const;
236 void setUnknown();
237 void set(unsigned value);
238 unsigned get() const;
239 bool isPack() const;
240 void setPack(bool pack);
241 };
242
243 // magic value means "match whatever the underlying C compiler does"
244 // other values are all powers of 2
245 //#define STRUCTALIGN_DEFAULT ((structalign_t) ~0)
246
247 const DString mars_ext = "d";
248 const DString doc_ext = "html"; // for Ddoc generated files
249 const DString ddoc_ext = "ddoc"; // for Ddoc macro include files
250 const DString dd_ext = "dd"; // for Ddoc source files
251 const DString hdr_ext = "di"; // for D 'header' import files
252 const DString json_ext = "json"; // for JSON files
253 const DString map_ext = "map"; // for .map files
254
255 struct Global
256 {
257 DString inifilename;
258
259 const DString copyright;
260 const DString written;
261 Array<const char *> *path; // Array of char*'s which form the import lookup path
262 Array<const char *> *filePath; // Array of char*'s which form the file import lookup path
263
264 DString vendor; // Compiler backend name
265
266 Param params;
267 unsigned errors; // number of errors reported so far
268 unsigned warnings; // number of warnings reported so far
269 unsigned gag; // !=0 means gag reporting of errors & warnings
270 unsigned gaggedErrors; // number of errors reported while gagged
271 unsigned gaggedWarnings; // number of warnings reported while gagged
272
273 void* console; // opaque pointer to console for controlling text attributes
274
275 Array<class Identifier*>* versionids; // command line versions and predefined versions
276 Array<class Identifier*>* debugids; // command line debug versions and predefined versions
277
278 d_bool hasMainFunction;
279 unsigned varSequenceNumber;
280
281 FileManager* fileManager;
282 ErrorSink* errorSink; // where the error messages go
283
284 FileName (*preprocess)(FileName, const Loc&, bool&, OutBuffer&);
285
286 /* Start gagging. Return the current number of gagged errors
287 */
288 unsigned startGagging();
289
290 /* End gagging, restoring the old gagged state.
291 * Return true if errors occurred while gagged.
292 */
293 bool endGagging(unsigned oldGagged);
294
295 /* Increment the error count to record that an error
296 * has occurred in the current context. An error message
297 * may or may not have been printed.
298 */
299 void increaseErrorCount();
300
301 void _init();
302
303 /**
304 Returns: the version as the number that would be returned for __VERSION__
305 */
306 unsigned versionNumber();
307
308 /**
309 Returns: the compiler version string.
310 */
311 const char * versionChars();
312 };
313
314 extern Global global;
315
316 // Because int64_t and friends may be any integral type of the correct size,
317 // we have to explicitly ask for the correct integer type to get the correct
318 // mangling with dmd. The #if logic here should match the mangling of
319 // Tint64 and Tuns64 in cppmangle.d.
320 #if MARS && DMD_VERSION >= 2079 && DMD_VERSION <= 2081 && \
321 __APPLE__ && __SIZEOF_LONG__ == 8
322 // DMD versions between 2.079 and 2.081 mapped D long to int64_t on OS X.
323 typedef uint64_t dinteger_t;
324 typedef int64_t sinteger_t;
325 typedef uint64_t uinteger_t;
326 #elif __SIZEOF_LONG__ == 8
327 // Be careful not to care about sign when using dinteger_t
328 // use this instead of integer_t to
329 // avoid conflicts with system #include's
330 typedef unsigned long dinteger_t;
331 // Signed and unsigned variants
332 typedef long sinteger_t;
333 typedef unsigned long uinteger_t;
334 #else
335 typedef unsigned long long dinteger_t;
336 typedef long long sinteger_t;
337 typedef unsigned long long uinteger_t;
338 #endif
339
340 // file location
341 struct Loc
342 {
343 const char *filename; // either absolute or relative to cwd
344 unsigned linnum;
345 unsigned charnum;
346
347 static void set(bool showColumns, MessageStyle messageStyle);
348
349 static bool showColumns;
350 static MessageStyle messageStyle;
351
352 Loc()
353 {
354 linnum = 0;
355 charnum = 0;
356 filename = NULL;
357 }
358
359 Loc(const char *filename, unsigned linnum, unsigned charnum)
360 {
361 this->linnum = linnum;
362 this->charnum = charnum;
363 this->filename = filename;
364 }
365
366 const char *toChars(
367 bool showColumns = Loc::showColumns,
368 MessageStyle messageStyle = Loc::messageStyle) const;
369 bool equals(const Loc& loc) const;
370 };
371
372 enum class LINK : uint8_t
373 {
374 default_,
375 d,
376 c,
377 cpp,
378 windows,
379 objc,
380 system
381 };
382
383 enum class CPPMANGLE : uint8_t
384 {
385 def,
386 asStruct,
387 asClass
388 };
389
390 enum class MATCH : int
391 {
392 nomatch, // no match
393 convert, // match with conversions
394 constant, // match with conversion to const
395 exact // exact match
396 };
397
398 enum class PINLINE : uint8_t
399 {
400 default_, // as specified on the command line
401 never, // never inline
402 always // always inline
403 };
404
405 enum class FileType : uint8_t
406 {
407 d, /// normal D source file
408 dhdr, /// D header file (.di)
409 ddoc, /// Ddoc documentation file (.dd)
410 c, /// C source file
411 };
412
413 typedef uinteger_t StorageClass;