-
-
Notifications
You must be signed in to change notification settings - Fork 267
/
Copy pathcompiler.d
415 lines (380 loc) · 12.9 KB
/
compiler.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/**
* Describes a back-end compiler and implements compiler-specific actions.
*
* Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/compiler.d, _compiler.d)
* Documentation: https://dlang.org/phobos/dmd_compiler.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/compiler.d
*/
module dmd.compiler;
import core.stdc.string;
import dmd.astenums;
import dmd.arraytypes;
import dmd.ctfeexpr;
import dmd.dmodule;
import dmd.errors;
import dmd.expression;
import dmd.globals;
import dmd.id;
import dmd.identifier;
import dmd.mtype;
import dmd.typesem;
import dmd.root.array;
import dmd.root.ctfloat;
version (DMDLIB)
{
version = CallbackAPI;
}
extern (C++) __gshared
{
bool includeImports = false;
// array of module patterns used to include/exclude imported modules
Array!(const(char)*) includeModulePatterns;
Modules compiledImports;
}
/**
* A data structure that describes a back-end compiler and implements
* compiler-specific actions.
*/
extern (C++) struct Compiler
{
/******************************
* Encode the given expression, which is assumed to be an rvalue literal
* as another type for use in CTFE.
* This corresponds roughly to the idiom *(Type *)&e.
*/
extern (C++) static Expression paintAsType(UnionExp* pue, Expression e, Type type)
{
union U
{
int int32value;
long int64value;
float float32value;
double float64value;
}
U u = void;
assert(e.type.size() == type.size());
switch (e.type.ty)
{
case Tint32:
case Tuns32:
u.int32value = cast(int) e.toInteger();
break;
case Tint64:
case Tuns64:
u.int64value = cast(long) e.toInteger();
break;
case Tfloat32:
u.float32value = cast(float) e.toReal();
break;
case Tfloat64:
u.float64value = cast(double) e.toReal();
break;
case Tfloat80:
assert(e.type.size() == 8); // 64-bit target `real`
goto case Tfloat64;
default:
assert(0, "Unsupported source type");
}
real_t r = void;
switch (type.ty)
{
case Tint32:
case Tuns32:
emplaceExp!(IntegerExp)(pue, e.loc, u.int32value, type);
break;
case Tint64:
case Tuns64:
emplaceExp!(IntegerExp)(pue, e.loc, u.int64value, type);
break;
case Tfloat32:
r = u.float32value;
emplaceExp!(RealExp)(pue, e.loc, r, type);
break;
case Tfloat64:
r = u.float64value;
emplaceExp!(RealExp)(pue, e.loc, r, type);
break;
case Tfloat80:
assert(type.size() == 8); // 64-bit target `real`
goto case Tfloat64;
default:
assert(0, "Unsupported target type");
}
return pue.exp();
}
/******************************
* For the given module, perform any post parsing analysis.
* Certain compiler backends (ie: GDC) have special placeholder
* modules whose source are empty, but code gets injected
* immediately after loading.
*/
extern (C++) static void onParseModule(Module m)
{
}
/**
* A callback function that is called once an imported module is
* parsed. If the callback returns true, then it tells the
* frontend that the driver intends on compiling the import.
*/
extern(C++) static bool onImport(Module m)
{
if (includeImports && (m.filetype == FileType.d || m.filetype == FileType.c))
{
if (includeImportedModuleCheck(ModuleComponentRange(
m.md ? m.md.packages : [], m.ident, m.isPackageFile)))
{
if (global.params.v.verbose)
message("compileimport (%s)", m.srcfile.toChars);
compiledImports.push(m);
return true; // this import will be compiled
}
}
return false; // this import will not be compiled
}
version (CallbackAPI)
{
import dmd.statement;
import dmd.dscope;
alias OnStatementSemanticStart = void function(Statement, Scope*);
alias OnStatementSemanticDone = void function(Statement, Scope*);
/**
* Used to insert functionality before the start of the
* semantic analysis of a statement when importing DMD as a library
*/
__gshared OnStatementSemanticStart onStatementSemanticStart
= function void(Statement s, Scope* sc) {};
/**
* Used to insert functionality after the end of the
* semantic analysis of a statement when importing DMD as a library
*/
__gshared OnStatementSemanticDone onStatementSemanticDone
= function void(Statement s, Scope* sc) {};
}
}
/******************************
* Private helpers for Compiler::onImport.
*/
// A range of component identifiers for a module
private struct ModuleComponentRange
{
Identifier[] packages;
Identifier name;
bool isPackageFile;
size_t index;
@property auto totalLength() const { return packages.length + 1 + (isPackageFile ? 1 : 0); }
@property auto empty() { return index >= totalLength(); }
@property auto front() const
{
if (index < packages.length)
return packages[index];
if (index == packages.length)
return name;
return Identifier.idPool("package");
}
void popFront() @safe { index++; }
}
/*
* Determines if the given module should be included in the compilation.
* Returns:
* True if the given module should be included in the compilation.
*/
private bool includeImportedModuleCheck(ModuleComponentRange components)
in { assert(includeImports); }
do
{
createMatchNodes();
size_t nodeIndex = 0;
while (nodeIndex < matchNodes.length)
{
//printf("matcher ");printMatcher(nodeIndex);printf("\n");
auto info = matchNodes[nodeIndex++];
if (info.depth <= components.totalLength())
{
size_t nodeOffset = 0;
for (auto range = components;;range.popFront())
{
if (range.empty || nodeOffset >= info.depth)
{
// MATCH
return !info.isExclude;
}
if (!(range.front is matchNodes[nodeIndex + nodeOffset].id))
{
break;
}
nodeOffset++;
}
}
nodeIndex += info.depth;
}
assert(nodeIndex == matchNodes.length, "code bug");
return includeByDefault;
}
// Matching module names is done with an array of matcher nodes.
// The nodes are sorted by "component depth" from largest to smallest
// so that the first match is always the longest (best) match.
private struct MatcherNode
{
union
{
struct
{
ushort depth;
bool isExclude;
}
Identifier id;
}
this(Identifier id) { this.id = id; }
this(bool isExclude, ushort depth)
{
this.depth = depth;
this.isExclude = isExclude;
}
}
/*
* $(D includeByDefault) determines whether to include/exclude modules when they don't
* match any pattern. This setting changes depending on if the user provided any "inclusive" module
* patterns. When a single "inclusive" module pattern is given, it likely means the user only
* intends to include modules they've "included", however, if no module patterns are given or they
* are all "exclusive", then it is likely they intend to include everything except modules
* that have been excluded. i.e.
* ---
* -i=-foo // include everything except modules that match "foo*"
* -i=foo // only include modules that match "foo*" (exclude everything else)
* ---
* Note that this default behavior can be overridden using the '.' module pattern. i.e.
* ---
* -i=-foo,-. // this excludes everything
* -i=foo,. // this includes everything except the default exclusions (-std,-core,-etc.-object)
* ---
*/
private __gshared bool includeByDefault = true;
private __gshared Array!MatcherNode matchNodes;
/*
* Creates the global list of match nodes used to match module names
* given strings provided by the -i commmand line option.
*/
private void createMatchNodes()
{
static size_t findSortedIndexToAddForDepth(size_t depth)
{
size_t index = 0;
while (index < matchNodes.length)
{
auto info = matchNodes[index];
if (depth > info.depth)
break;
index += 1 + info.depth;
}
return index;
}
if (matchNodes.length != 0)
return;
foreach (modulePattern; includeModulePatterns)
{
const depth = parseModulePatternDepth(modulePattern[0 .. strlen(modulePattern)]);
const entryIndex = findSortedIndexToAddForDepth(depth);
matchNodes.split(entryIndex, depth + 1);
parseModulePattern(modulePattern, &matchNodes[entryIndex], depth);
// if at least 1 "include pattern" is given, then it is assumed the
// user only wants to include modules that were explicitly given, which
// changes the default behavior from inclusion to exclusion.
if (includeByDefault && !matchNodes[entryIndex].isExclude)
{
//printf("Matcher: found 'include pattern', switching default behavior to exclusion\n");
includeByDefault = false;
}
}
// Add the default 1 depth matchers
MatcherNode[10] defaultDepth1MatchNodes = [
MatcherNode(true, 1), MatcherNode(Id.std),
MatcherNode(true, 1), MatcherNode(Id.core),
MatcherNode(true, 1), MatcherNode(Id.etc),
MatcherNode(true, 1), MatcherNode(Id.ldc), // IN_LLVM
MatcherNode(true, 1), MatcherNode(Id.object),
];
const index = findSortedIndexToAddForDepth(1);
matchNodes.split(index, defaultDepth1MatchNodes.length);
auto slice = matchNodes[];
slice[index .. index + defaultDepth1MatchNodes.length] = defaultDepth1MatchNodes[];
}
/*
* Determines the depth of the given module pattern.
* Params:
* modulePattern = The module pattern to determine the depth of.
* Returns:
* The component depth of the given module pattern.
*/
pure @safe
private ushort parseModulePatternDepth(const char[] modulePattern)
{
const length = modulePattern.length;
size_t i = length && modulePattern[0] == '-'; // skip past leading '-'
// handle special case
if (i + 1 == length && modulePattern[i] == '.')
return 0;
int depth = 1;
foreach (c; modulePattern[i .. length])
depth += c == '.';
return cast(ushort)depth;
}
unittest
{
assert(".".parseModulePatternDepth == 0);
assert("-.".parseModulePatternDepth == 0);
assert("abc".parseModulePatternDepth == 1);
assert("-abc".parseModulePatternDepth == 1);
assert("abc.foo".parseModulePatternDepth == 2);
assert("-abc.foo".parseModulePatternDepth == 2);
}
/*
* Parses a 'module pattern', which is the "include import" components
* given on the command line, i.e. "-i=<module_pattern>,<module_pattern>,...".
* Params:
* modulePattern = The module pattern to parse.
* dst = the data structure to save the parsed module pattern to.
* depth = the depth of the module pattern previously retrieved from $(D parseModulePatternDepth).
*/
private void parseModulePattern(const(char)* modulePattern, MatcherNode* dst, ushort depth)
{
bool isExclude = false;
if (modulePattern[0] == '-')
{
isExclude = true;
modulePattern++;
}
*dst = MatcherNode(isExclude, depth);
dst++;
// Create and add identifiers for each component in the modulePattern
if (depth > 0)
{
auto idStart = modulePattern;
auto lastNode = dst + depth - 1;
for (; dst < lastNode; dst++)
{
for (;; modulePattern++)
{
if (*modulePattern == '.')
{
assert(modulePattern > idStart, "empty module pattern");
*dst = MatcherNode(Identifier.idPool(idStart[0 .. modulePattern - idStart]));
modulePattern++;
idStart = modulePattern;
break;
}
}
}
for (;; modulePattern++)
{
if (*modulePattern == '\0')
{
assert(modulePattern > idStart, "empty module pattern");
*lastNode = MatcherNode(Identifier.idPool(idStart[0 .. modulePattern - idStart]));
break;
}
}
}
}